diff --git a/app/ante/eip712_test.go b/app/ante/eip712_test.go index 5c593ebe..2fe416ca 100644 --- a/app/ante/eip712_test.go +++ b/app/ante/eip712_test.go @@ -34,11 +34,9 @@ import ( "github.com/stretchr/testify/suite" "github.com/0glabs/0g-chain/app" - cdptypes "github.com/0glabs/0g-chain/x/cdp/types" evmutilkeeper "github.com/0glabs/0g-chain/x/evmutil/keeper" evmutiltestutil "github.com/0glabs/0g-chain/x/evmutil/testutil" evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types" - hardtypes "github.com/0glabs/0g-chain/x/hard/types" pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" ) @@ -138,7 +136,6 @@ func (suite *EIP712TestSuite) createTestEIP712CosmosTxBuilder( func (suite *EIP712TestSuite) SetupTest() { tApp := app.NewTestApp() suite.tApp = tApp - cdc := tApp.AppCodec() suite.evmutilKeeper = tApp.GetEvmutilKeeper() @@ -173,46 +170,46 @@ func (suite *EIP712TestSuite) SetupTest() { feemarketGenesis.Params.EnableHeight = 1 feemarketGenesis.Params.NoBaseFee = false - cdpGenState := cdptypes.DefaultGenesisState() - cdpGenState.Params.GlobalDebtLimit = sdk.NewInt64Coin("usdx", 53000000000000) - cdpGenState.Params.CollateralParams = cdptypes.CollateralParams{ - { - Denom: USDCCoinDenom, - Type: USDCCDPType, - LiquidationRatio: sdk.MustNewDecFromStr("1.01"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.OneDec(), - AuctionSize: sdkmath.NewIntFromUint64(10000000000), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - SpotMarketID: "usdc:usd", - LiquidationMarketID: "usdc:usd:30", - ConversionFactor: sdkmath.NewInt(18), - }, - } + // cdpGenState := cdptypes.DefaultGenesisState() + // cdpGenState.Params.GlobalDebtLimit = sdk.NewInt64Coin("usdx", 53000000000000) + // cdpGenState.Params.CollateralParams = cdptypes.CollateralParams{ + // { + // Denom: USDCCoinDenom, + // Type: USDCCDPType, + // LiquidationRatio: sdk.MustNewDecFromStr("1.01"), + // DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), + // StabilityFee: sdk.OneDec(), + // AuctionSize: sdkmath.NewIntFromUint64(10000000000), + // LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), + // CheckCollateralizationIndexCount: sdkmath.NewInt(10), + // KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), + // SpotMarketID: "usdc:usd", + // LiquidationMarketID: "usdc:usd:30", + // ConversionFactor: sdkmath.NewInt(18), + // }, + // } - hardGenState := hardtypes.DefaultGenesisState() - hardGenState.Params.MoneyMarkets = []hardtypes.MoneyMarket{ - { - Denom: "usdx", - BorrowLimit: hardtypes.BorrowLimit{ - HasMaxLimit: true, - MaximumLimit: sdk.MustNewDecFromStr("100000000000"), - LoanToValue: sdk.MustNewDecFromStr("1"), - }, - SpotMarketID: "usdx:usd", - ConversionFactor: sdkmath.NewInt(1_000_000), - InterestRateModel: hardtypes.InterestRateModel{ - BaseRateAPY: sdk.MustNewDecFromStr("0.05"), - BaseMultiplier: sdk.MustNewDecFromStr("2"), - Kink: sdk.MustNewDecFromStr("0.8"), - JumpMultiplier: sdk.MustNewDecFromStr("10"), - }, - ReserveFactor: sdk.MustNewDecFromStr("0.05"), - KeeperRewardPercentage: sdk.ZeroDec(), - }, - } + // hardGenState := hardtypes.DefaultGenesisState() + // hardGenState.Params.MoneyMarkets = []hardtypes.MoneyMarket{ + // { + // Denom: "usdx", + // BorrowLimit: hardtypes.BorrowLimit{ + // HasMaxLimit: true, + // MaximumLimit: sdk.MustNewDecFromStr("100000000000"), + // LoanToValue: sdk.MustNewDecFromStr("1"), + // }, + // SpotMarketID: "usdx:usd", + // ConversionFactor: sdkmath.NewInt(1_000_000), + // InterestRateModel: hardtypes.InterestRateModel{ + // BaseRateAPY: sdk.MustNewDecFromStr("0.05"), + // BaseMultiplier: sdk.MustNewDecFromStr("2"), + // Kink: sdk.MustNewDecFromStr("0.8"), + // JumpMultiplier: sdk.MustNewDecFromStr("10"), + // }, + // ReserveFactor: sdk.MustNewDecFromStr("0.05"), + // KeeperRewardPercentage: sdk.ZeroDec(), + // }, + // } pricefeedGenState := pricefeedtypes.DefaultGenesisState() pricefeedGenState.Params.Markets = []pricefeedtypes.Market{ @@ -262,8 +259,8 @@ func (suite *EIP712TestSuite) SetupTest() { genState := app.GenesisState{ evmtypes.ModuleName: cdc.MustMarshalJSON(evmGs), feemarkettypes.ModuleName: cdc.MustMarshalJSON(feemarketGenesis), - cdptypes.ModuleName: cdc.MustMarshalJSON(&cdpGenState), - hardtypes.ModuleName: cdc.MustMarshalJSON(&hardGenState), + // cdptypes.ModuleName: cdc.MustMarshalJSON(&cdpGenState), + // hardtypes.ModuleName: cdc.MustMarshalJSON(&hardGenState), pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pricefeedGenState), } @@ -607,21 +604,21 @@ func (suite *EIP712TestSuite) TestEIP712Tx() { suite.usdcEVMAddr, usdcAmt, ) - usdxAmt := sdkmath.NewInt(1_000_000).Mul(sdkmath.NewInt(tc.usdxToMintAmt)) - mintMsg := cdptypes.NewMsgCreateCDP( - suite.testAddr, - sdk.NewCoin(USDCCoinDenom, usdcAmt), - sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt), - USDCCDPType, - ) - lendMsg := hardtypes.NewMsgDeposit( - suite.testAddr, - sdk.NewCoins(sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt)), - ) + // usdxAmt := sdkmath.NewInt(1_000_000).Mul(sdkmath.NewInt(tc.usdxToMintAmt)) + // mintMsg := cdptypes.NewMsgCreateCDP( + // suite.testAddr, + // sdk.NewCoin(USDCCoinDenom, usdcAmt), + // sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt), + // USDCCDPType, + // ) + // lendMsg := hardtypes.NewMsgDeposit( + // suite.testAddr, + // sdk.NewCoins(sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt)), + // ) msgs := []sdk.Msg{ &convertMsg, - &mintMsg, - &lendMsg, + // &mintMsg, + // &lendMsg, } if tc.updateMsgs != nil { msgs = tc.updateMsgs(msgs) @@ -665,17 +662,17 @@ func (suite *EIP712TestSuite) TestEIP712Tx() { suite.Require().Equal(sdk.ZeroInt(), amt.Amount) // validate cdp - cdp, found := suite.tApp.GetCDPKeeper().GetCdpByOwnerAndCollateralType(suite.ctx, suite.testAddr, USDCCDPType) - 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", sdkmath.NewInt(99_000_000)), cdp.Principal) + // cdp, found := suite.tApp.GetCDPKeeper().GetCdpByOwnerAndCollateralType(suite.ctx, suite.testAddr, USDCCDPType) + // 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", 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", sdkmath.NewInt(99_000_000))), hardDeposit.Amount) + // 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", sdkmath.NewInt(99_000_000))), hardDeposit.Amount) } else { suite.Require().NotEqual(resDeliverTx.Code, uint32(0), resCheckTx.Log) suite.Require().Contains(resDeliverTx.Log, tc.errMsg) @@ -695,21 +692,21 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() { suite.usdcEVMAddr, usdcAmt, ) - usdxAmt := sdkmath.NewInt(1_000_000).Mul(sdkmath.NewInt(99)) - mintMsg := cdptypes.NewMsgCreateCDP( - suite.testAddr, - sdk.NewCoin(USDCCoinDenom, usdcAmt), - sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt), - USDCCDPType, - ) - lendMsg := hardtypes.NewMsgDeposit( - suite.testAddr, - sdk.NewCoins(sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt)), - ) + // usdxAmt := sdkmath.NewInt(1_000_000).Mul(sdkmath.NewInt(99)) + // mintMsg := cdptypes.NewMsgCreateCDP( + // suite.testAddr, + // sdk.NewCoin(USDCCoinDenom, usdcAmt), + // sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt), + // USDCCDPType, + // ) + // lendMsg := hardtypes.NewMsgDeposit( + // suite.testAddr, + // sdk.NewCoins(sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt)), + // ) depositMsgs := []sdk.Msg{ &convertMsg, - &mintMsg, - &lendMsg, + // &mintMsg, + // &lendMsg, } // deliver deposit msg @@ -727,10 +724,10 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() { suite.Require().Equal(resDeliverTx.Code, uint32(0), resDeliverTx.Log) // 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", sdkmath.NewInt(99_000_000))), hardDeposit.Amount) + // 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", sdkmath.NewInt(99_000_000))), hardDeposit.Amount) // validate erc20 balance coinBal, err := suite.evmutilKeeper.QueryERC20BalanceOf(suite.ctx, suite.usdcEVMAddr, suite.testEVMAddr) @@ -743,18 +740,18 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() { suite.testEVMAddr.String(), sdk.NewCoin(USDCCoinDenom, usdcAmt), ) - cdpWithdrawMsg := cdptypes.NewMsgRepayDebt( - suite.testAddr, - USDCCDPType, - sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt), - ) - hardWithdrawMsg := hardtypes.NewMsgWithdraw( - suite.testAddr, - sdk.NewCoins(sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt)), - ) + // cdpWithdrawMsg := cdptypes.NewMsgRepayDebt( + // suite.testAddr, + // USDCCDPType, + // sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt), + // ) + // hardWithdrawMsg := hardtypes.NewMsgWithdraw( + // suite.testAddr, + // sdk.NewCoins(sdk.NewCoin(cdptypes.DefaultStableDenom, usdxAmt)), + // ) withdrawMsgs := []sdk.Msg{ - &hardWithdrawMsg, - &cdpWithdrawMsg, + // &hardWithdrawMsg, + // &cdpWithdrawMsg, &withdrawConvertMsg, } @@ -772,10 +769,10 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() { suite.Require().Equal(resDeliverTx.Code, uint32(0), resDeliverTx.Log) // validate hard & cdp should be repayed - _, found = suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr) - suite.Require().False(found) - _, found = suite.tApp.GetCDPKeeper().GetCdpByOwnerAndCollateralType(suite.ctx, suite.testAddr, USDCCDPType) - suite.Require().False(found) + // _, found = suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr) + // suite.Require().False(found) + // _, found = suite.tApp.GetCDPKeeper().GetCdpByOwnerAndCollateralType(suite.ctx, suite.testAddr, USDCCDPType) + // suite.Require().False(found) // validate user cosmos erc20/usd balance bk := suite.tApp.GetBankKeeper() diff --git a/app/app.go b/app/app.go index d7b00cee..da17f0a7 100644 --- a/app/app.go +++ b/app/app.go @@ -107,60 +107,24 @@ import ( "github.com/0glabs/0g-chain/app/ante" kavaparams "github.com/0glabs/0g-chain/app/params" - "github.com/0glabs/0g-chain/x/auction" - auctionkeeper "github.com/0glabs/0g-chain/x/auction/keeper" - auctiontypes "github.com/0glabs/0g-chain/x/auction/types" "github.com/0glabs/0g-chain/x/bep3" bep3keeper "github.com/0glabs/0g-chain/x/bep3/keeper" bep3types "github.com/0glabs/0g-chain/x/bep3/types" - "github.com/0glabs/0g-chain/x/cdp" - cdpkeeper "github.com/0glabs/0g-chain/x/cdp/keeper" - cdptypes "github.com/0glabs/0g-chain/x/cdp/types" "github.com/0glabs/0g-chain/x/committee" committeeclient "github.com/0glabs/0g-chain/x/committee/client" committeekeeper "github.com/0glabs/0g-chain/x/committee/keeper" committeetypes "github.com/0glabs/0g-chain/x/committee/types" - "github.com/0glabs/0g-chain/x/community" - communityclient "github.com/0glabs/0g-chain/x/community/client" - communitykeeper "github.com/0glabs/0g-chain/x/community/keeper" - communitytypes "github.com/0glabs/0g-chain/x/community/types" - earn "github.com/0glabs/0g-chain/x/earn" - earnclient "github.com/0glabs/0g-chain/x/earn/client" - earnkeeper "github.com/0glabs/0g-chain/x/earn/keeper" - earntypes "github.com/0glabs/0g-chain/x/earn/types" evmutil "github.com/0glabs/0g-chain/x/evmutil" evmutilkeeper "github.com/0glabs/0g-chain/x/evmutil/keeper" evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types" - "github.com/0glabs/0g-chain/x/hard" - hardkeeper "github.com/0glabs/0g-chain/x/hard/keeper" - hardtypes "github.com/0glabs/0g-chain/x/hard/types" - "github.com/0glabs/0g-chain/x/incentive" - incentivekeeper "github.com/0glabs/0g-chain/x/incentive/keeper" - incentivetypes "github.com/0glabs/0g-chain/x/incentive/types" issuance "github.com/0glabs/0g-chain/x/issuance" issuancekeeper "github.com/0glabs/0g-chain/x/issuance/keeper" issuancetypes "github.com/0glabs/0g-chain/x/issuance/types" - "github.com/0glabs/0g-chain/x/kavadist" - kavadistclient "github.com/0glabs/0g-chain/x/kavadist/client" - kavadistkeeper "github.com/0glabs/0g-chain/x/kavadist/keeper" - kavadisttypes "github.com/0glabs/0g-chain/x/kavadist/types" - "github.com/0glabs/0g-chain/x/liquid" - liquidkeeper "github.com/0glabs/0g-chain/x/liquid/keeper" - liquidtypes "github.com/0glabs/0g-chain/x/liquid/types" metrics "github.com/0glabs/0g-chain/x/metrics" metricstypes "github.com/0glabs/0g-chain/x/metrics/types" pricefeed "github.com/0glabs/0g-chain/x/pricefeed" pricefeedkeeper "github.com/0glabs/0g-chain/x/pricefeed/keeper" pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" - "github.com/0glabs/0g-chain/x/router" - routerkeeper "github.com/0glabs/0g-chain/x/router/keeper" - routertypes "github.com/0glabs/0g-chain/x/router/types" - savings "github.com/0glabs/0g-chain/x/savings" - savingskeeper "github.com/0glabs/0g-chain/x/savings/keeper" - savingstypes "github.com/0glabs/0g-chain/x/savings/types" - "github.com/0glabs/0g-chain/x/swap" - swapkeeper "github.com/0glabs/0g-chain/x/swap/keeper" - swaptypes "github.com/0glabs/0g-chain/x/swap/types" validatorvesting "github.com/0glabs/0g-chain/x/validator-vesting" validatorvestingrest "github.com/0glabs/0g-chain/x/validator-vesting/client/rest" validatorvestingtypes "github.com/0glabs/0g-chain/x/validator-vesting/types" @@ -189,12 +153,12 @@ var ( upgradeclient.LegacyCancelProposalHandler, ibcclientclient.UpdateClientProposalHandler, ibcclientclient.UpgradeProposalHandler, - kavadistclient.ProposalHandler, + // kavadistclient.ProposalHandler, committeeclient.ProposalHandler, - earnclient.DepositProposalHandler, - earnclient.WithdrawProposalHandler, - communityclient.LendDepositProposalHandler, - communityclient.LendWithdrawProposalHandler, + // earnclient.DepositProposalHandler, + // earnclient.WithdrawProposalHandler, + // communityclient.LendDepositProposalHandler, + // communityclient.LendWithdrawProposalHandler, }), params.AppModuleBasic{}, crisis.AppModuleBasic{}, @@ -210,24 +174,24 @@ var ( vesting.AppModuleBasic{}, evm.AppModuleBasic{}, feemarket.AppModuleBasic{}, - kavadist.AppModuleBasic{}, - auction.AppModuleBasic{}, + // kavadist.AppModuleBasic{}, + // auction.AppModuleBasic{}, issuance.AppModuleBasic{}, bep3.AppModuleBasic{}, pricefeed.AppModuleBasic{}, - swap.AppModuleBasic{}, - cdp.AppModuleBasic{}, - hard.AppModuleBasic{}, + // swap.AppModuleBasic{}, + // cdp.AppModuleBasic{}, + // hard.AppModuleBasic{}, committee.AppModuleBasic{}, - incentive.AppModuleBasic{}, - savings.AppModuleBasic{}, + // incentive.AppModuleBasic{}, + // savings.AppModuleBasic{}, validatorvesting.AppModuleBasic{}, evmutil.AppModuleBasic{}, - liquid.AppModuleBasic{}, - earn.AppModuleBasic{}, - router.AppModuleBasic{}, + // liquid.AppModuleBasic{}, + // earn.AppModuleBasic{}, + // router.AppModuleBasic{}, mint.AppModuleBasic{}, - community.AppModuleBasic{}, + // community.AppModuleBasic{}, metrics.AppModuleBasic{}, consensus.AppModuleBasic{}, ) @@ -236,28 +200,28 @@ var ( // If these are changed, the permissions stored in accounts // must also be migrated during a chain upgrade. mAccPerms = map[string][]string{ - authtypes.FeeCollectorName: nil, - distrtypes.ModuleName: nil, - stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, - stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, - govtypes.ModuleName: {authtypes.Burner}, - ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, - evmtypes.ModuleName: {authtypes.Minter, authtypes.Burner}, // used for secure addition and subtraction of balance using module account - evmutiltypes.ModuleName: {authtypes.Minter, authtypes.Burner}, - kavadisttypes.KavaDistMacc: {authtypes.Minter}, - auctiontypes.ModuleName: nil, + authtypes.FeeCollectorName: nil, + distrtypes.ModuleName: nil, + stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, + stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, + govtypes.ModuleName: {authtypes.Burner}, + ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + evmtypes.ModuleName: {authtypes.Minter, authtypes.Burner}, // used for secure addition and subtraction of balance using module account + evmutiltypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + // kavadisttypes.KavaDistMacc: {authtypes.Minter}, + // auctiontypes.ModuleName: nil, issuancetypes.ModuleAccountName: {authtypes.Minter, authtypes.Burner}, bep3types.ModuleName: {authtypes.Burner, authtypes.Minter}, - swaptypes.ModuleName: nil, - cdptypes.ModuleName: {authtypes.Minter, authtypes.Burner}, - cdptypes.LiquidatorMacc: {authtypes.Minter, authtypes.Burner}, - hardtypes.ModuleAccountName: {authtypes.Minter}, - savingstypes.ModuleAccountName: nil, - liquidtypes.ModuleAccountName: {authtypes.Minter, authtypes.Burner}, - earntypes.ModuleAccountName: nil, - kavadisttypes.FundModuleAccount: nil, - minttypes.ModuleName: {authtypes.Minter}, - communitytypes.ModuleName: nil, + // swaptypes.ModuleName: nil, + // cdptypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + // cdptypes.LiquidatorMacc: {authtypes.Minter, authtypes.Burner}, + // hardtypes.ModuleAccountName: {authtypes.Minter}, + // savingstypes.ModuleAccountName: nil, + // liquidtypes.ModuleAccountName: {authtypes.Minter, authtypes.Burner}, + // earntypes.ModuleAccountName: nil, + // kavadisttypes.FundModuleAccount: nil, + minttypes.ModuleName: {authtypes.Minter}, + // communitytypes.ModuleName: nil, } ) @@ -300,40 +264,40 @@ type App struct { memKeys map[string]*storetypes.MemoryStoreKey // keepers from all the modules - accountKeeper authkeeper.AccountKeeper - bankKeeper bankkeeper.Keeper - capabilityKeeper *capabilitykeeper.Keeper - stakingKeeper *stakingkeeper.Keeper - distrKeeper distrkeeper.Keeper - govKeeper govkeeper.Keeper - paramsKeeper paramskeeper.Keeper - authzKeeper authzkeeper.Keeper - crisisKeeper crisiskeeper.Keeper - slashingKeeper slashingkeeper.Keeper - ibcKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly - packetForwardKeeper *packetforwardkeeper.Keeper - evmKeeper *evmkeeper.Keeper - evmutilKeeper evmutilkeeper.Keeper - feeMarketKeeper feemarketkeeper.Keeper - upgradeKeeper upgradekeeper.Keeper - evidenceKeeper evidencekeeper.Keeper - transferKeeper ibctransferkeeper.Keeper - kavadistKeeper kavadistkeeper.Keeper - auctionKeeper auctionkeeper.Keeper - issuanceKeeper issuancekeeper.Keeper - bep3Keeper bep3keeper.Keeper - pricefeedKeeper pricefeedkeeper.Keeper - swapKeeper swapkeeper.Keeper - cdpKeeper cdpkeeper.Keeper - hardKeeper hardkeeper.Keeper - committeeKeeper committeekeeper.Keeper - incentiveKeeper incentivekeeper.Keeper - savingsKeeper savingskeeper.Keeper - liquidKeeper liquidkeeper.Keeper - earnKeeper earnkeeper.Keeper - routerKeeper routerkeeper.Keeper - mintKeeper mintkeeper.Keeper - communityKeeper communitykeeper.Keeper + accountKeeper authkeeper.AccountKeeper + bankKeeper bankkeeper.Keeper + capabilityKeeper *capabilitykeeper.Keeper + stakingKeeper *stakingkeeper.Keeper + distrKeeper distrkeeper.Keeper + govKeeper govkeeper.Keeper + paramsKeeper paramskeeper.Keeper + authzKeeper authzkeeper.Keeper + crisisKeeper crisiskeeper.Keeper + slashingKeeper slashingkeeper.Keeper + ibcKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly + packetForwardKeeper *packetforwardkeeper.Keeper + evmKeeper *evmkeeper.Keeper + evmutilKeeper evmutilkeeper.Keeper + feeMarketKeeper feemarketkeeper.Keeper + upgradeKeeper upgradekeeper.Keeper + evidenceKeeper evidencekeeper.Keeper + transferKeeper ibctransferkeeper.Keeper + // kavadistKeeper kavadistkeeper.Keeper + // auctionKeeper auctionkeeper.Keeper + issuanceKeeper issuancekeeper.Keeper + bep3Keeper bep3keeper.Keeper + pricefeedKeeper pricefeedkeeper.Keeper + // swapKeeper swapkeeper.Keeper + // cdpKeeper cdpkeeper.Keeper + // hardKeeper hardkeeper.Keeper + committeeKeeper committeekeeper.Keeper + // incentiveKeeper incentivekeeper.Keeper + // savingsKeeper savingskeeper.Keeper + // liquidKeeper liquidkeeper.Keeper + // earnKeeper earnkeeper.Keeper + // routerKeeper routerkeeper.Keeper + mintKeeper mintkeeper.Keeper + // communityKeeper communitykeeper.Keeper consensusParamsKeeper consensusparamkeeper.Keeper // make scoped keepers public for test purposes @@ -384,11 +348,15 @@ func NewApp( govtypes.StoreKey, paramstypes.StoreKey, ibcexported.StoreKey, upgradetypes.StoreKey, evidencetypes.StoreKey, ibctransfertypes.StoreKey, evmtypes.StoreKey, feemarkettypes.StoreKey, authzkeeper.StoreKey, - capabilitytypes.StoreKey, kavadisttypes.StoreKey, auctiontypes.StoreKey, + capabilitytypes.StoreKey, + // kavadisttypes.StoreKey, auctiontypes.StoreKey, issuancetypes.StoreKey, bep3types.StoreKey, pricefeedtypes.StoreKey, - swaptypes.StoreKey, cdptypes.StoreKey, hardtypes.StoreKey, communitytypes.StoreKey, - committeetypes.StoreKey, incentivetypes.StoreKey, evmutiltypes.StoreKey, - savingstypes.StoreKey, earntypes.StoreKey, minttypes.StoreKey, + // swaptypes.StoreKey, cdptypes.StoreKey, hardtypes.StoreKey, communitytypes.StoreKey, + committeetypes.StoreKey, + // incentivetypes.StoreKey, + evmutiltypes.StoreKey, + // savingstypes.StoreKey, earntypes.StoreKey, + minttypes.StoreKey, consensusparamtypes.StoreKey, crisistypes.StoreKey, ) tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey, evmtypes.TransientKey, feemarkettypes.TransientKey) @@ -422,23 +390,23 @@ func NewApp( slashingSubspace := app.paramsKeeper.Subspace(slashingtypes.ModuleName) govSubspace := app.paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govv1.ParamKeyTable()) crisisSubspace := app.paramsKeeper.Subspace(crisistypes.ModuleName) - kavadistSubspace := app.paramsKeeper.Subspace(kavadisttypes.ModuleName) - auctionSubspace := app.paramsKeeper.Subspace(auctiontypes.ModuleName) + // kavadistSubspace := app.paramsKeeper.Subspace(kavadisttypes.ModuleName)/ + // auctionSubspace := app.paramsKeeper.Subspace(auctiontypes.ModuleName) issuanceSubspace := app.paramsKeeper.Subspace(issuancetypes.ModuleName) bep3Subspace := app.paramsKeeper.Subspace(bep3types.ModuleName) pricefeedSubspace := app.paramsKeeper.Subspace(pricefeedtypes.ModuleName) - swapSubspace := app.paramsKeeper.Subspace(swaptypes.ModuleName) - cdpSubspace := app.paramsKeeper.Subspace(cdptypes.ModuleName) - hardSubspace := app.paramsKeeper.Subspace(hardtypes.ModuleName) - incentiveSubspace := app.paramsKeeper.Subspace(incentivetypes.ModuleName) - savingsSubspace := app.paramsKeeper.Subspace(savingstypes.ModuleName) + // swapSubspace := app.paramsKeeper.Subspace(swaptypes.ModuleName) + // cdpSubspace := app.paramsKeeper.Subspace(cdptypes.ModuleName) + // hardSubspace := app.paramsKeeper.Subspace(hardtypes.ModuleName) + // incentiveSubspace := app.paramsKeeper.Subspace(incentivetypes.ModuleName) + // savingsSubspace := app.paramsKeeper.Subspace(savingstypes.ModuleName) ibcSubspace := app.paramsKeeper.Subspace(ibcexported.ModuleName) ibctransferSubspace := app.paramsKeeper.Subspace(ibctransfertypes.ModuleName) packetforwardSubspace := app.paramsKeeper.Subspace(packetforwardtypes.ModuleName).WithKeyTable(packetforwardtypes.ParamKeyTable()) feemarketSubspace := app.paramsKeeper.Subspace(feemarkettypes.ModuleName) evmSubspace := app.paramsKeeper.Subspace(evmtypes.ModuleName) evmutilSubspace := app.paramsKeeper.Subspace(evmutiltypes.ModuleName) - earnSubspace := app.paramsKeeper.Subspace(earntypes.ModuleName) + // earnSubspace := app.paramsKeeper.Subspace(earntypes.ModuleName) mintSubspace := app.paramsKeeper.Subspace(minttypes.ModuleName) // set the BaseApp's parameter store @@ -602,13 +570,13 @@ func NewApp( ibcRouter.AddRoute(ibctransfertypes.ModuleName, transferStack) app.ibcKeeper.SetRouter(ibcRouter) - app.auctionKeeper = auctionkeeper.NewKeeper( - appCodec, - keys[auctiontypes.StoreKey], - auctionSubspace, - app.bankKeeper, - app.accountKeeper, - ) + // app.auctionKeeper = auctionkeeper.NewKeeper( + // appCodec, + // keys[auctiontypes.StoreKey], + // auctionSubspace, + // app.bankKeeper, + // app.accountKeeper, + // ) app.issuanceKeeper = issuancekeeper.NewKeeper( appCodec, keys[issuancetypes.StoreKey], @@ -629,68 +597,68 @@ func NewApp( keys[pricefeedtypes.StoreKey], pricefeedSubspace, ) - swapKeeper := swapkeeper.NewKeeper( - appCodec, - keys[swaptypes.StoreKey], - swapSubspace, - app.accountKeeper, - app.bankKeeper, - ) - cdpKeeper := cdpkeeper.NewKeeper( - appCodec, - keys[cdptypes.StoreKey], - cdpSubspace, - app.pricefeedKeeper, - app.auctionKeeper, - app.bankKeeper, - app.accountKeeper, - mAccPerms, - ) - hardKeeper := hardkeeper.NewKeeper( - appCodec, - keys[hardtypes.StoreKey], - hardSubspace, - app.accountKeeper, - app.bankKeeper, - app.pricefeedKeeper, - app.auctionKeeper, - ) - app.liquidKeeper = liquidkeeper.NewDefaultKeeper( - appCodec, - app.accountKeeper, - app.bankKeeper, - app.stakingKeeper, - &app.distrKeeper, - ) - savingsKeeper := savingskeeper.NewKeeper( - appCodec, - keys[savingstypes.StoreKey], - savingsSubspace, - app.accountKeeper, - app.bankKeeper, - app.liquidKeeper, - ) - earnKeeper := earnkeeper.NewKeeper( - appCodec, - keys[earntypes.StoreKey], - earnSubspace, - app.accountKeeper, - app.bankKeeper, - &app.liquidKeeper, - &hardKeeper, - &savingsKeeper, - &app.distrKeeper, - ) + // swapKeeper := swapkeeper.NewKeeper( + // appCodec, + // keys[swaptypes.StoreKey], + // swapSubspace, + // app.accountKeeper, + // app.bankKeeper, + // ) + // cdpKeeper := cdpkeeper.NewKeeper( + // appCodec, + // keys[cdptypes.StoreKey], + // cdpSubspace, + // app.pricefeedKeeper, + // app.auctionKeeper, + // app.bankKeeper, + // app.accountKeeper, + // mAccPerms, + // ) + // hardKeeper := hardkeeper.NewKeeper( + // appCodec, + // keys[hardtypes.StoreKey], + // hardSubspace, + // app.accountKeeper, + // app.bankKeeper, + // app.pricefeedKeeper, + // app.auctionKeeper, + // ) + // app.liquidKeeper = liquidkeeper.NewDefaultKeeper( + // appCodec, + // app.accountKeeper, + // app.bankKeeper, + // app.stakingKeeper, + // &app.distrKeeper, + // ) + // savingsKeeper := savingskeeper.NewKeeper( + // appCodec, + // keys[savingstypes.StoreKey], + // savingsSubspace, + // app.accountKeeper, + // app.bankKeeper, + // app.liquidKeeper, + // ) + // earnKeeper := earnkeeper.NewKeeper( + // appCodec, + // keys[earntypes.StoreKey], + // earnSubspace, + // app.accountKeeper, + // app.bankKeeper, + // &app.liquidKeeper, + // &hardKeeper, + // &savingsKeeper, + // &app.distrKeeper, + // ) - app.kavadistKeeper = kavadistkeeper.NewKeeper( - appCodec, - keys[kavadisttypes.StoreKey], - kavadistSubspace, - app.bankKeeper, - app.accountKeeper, - app.distrKeeper, - app.loadBlockedMaccAddrs(), - ) + // app.kavadistKeeper = kavadistkeeper.NewKeeper( + // appCodec, + // keys[kavadisttypes.StoreKey], + // kavadistSubspace, + // app.bankKeeper, + // app.accountKeeper, + // app.distrKeeper, + // app.loadBlockedMaccAddrs(), + // ) app.mintKeeper = mintkeeper.NewKeeper( appCodec, @@ -703,48 +671,48 @@ func NewApp( ) // x/community's deposit/withdraw to lend proposals depend on hard keeper. - app.communityKeeper = communitykeeper.NewKeeper( - appCodec, - keys[communitytypes.StoreKey], - app.accountKeeper, - app.bankKeeper, - &cdpKeeper, - app.distrKeeper, - &hardKeeper, - &app.mintKeeper, - &app.kavadistKeeper, - app.stakingKeeper, - govAuthAddr, - ) + // app.communityKeeper = communitykeeper.NewKeeper( + // appCodec, + // keys[communitytypes.StoreKey], + // app.accountKeeper, + // app.bankKeeper, + // &cdpKeeper, + // app.distrKeeper, + // &hardKeeper, + // &app.mintKeeper, + // &app.kavadistKeeper, + // app.stakingKeeper, + // govAuthAddr, + // ) - app.incentiveKeeper = incentivekeeper.NewKeeper( - appCodec, - keys[incentivetypes.StoreKey], - incentiveSubspace, - app.bankKeeper, - &cdpKeeper, - &hardKeeper, - app.accountKeeper, - app.stakingKeeper, - &swapKeeper, - &savingsKeeper, - &app.liquidKeeper, - &earnKeeper, - app.mintKeeper, - app.distrKeeper, - app.pricefeedKeeper, - ) - app.routerKeeper = routerkeeper.NewKeeper( - &app.earnKeeper, - app.liquidKeeper, - app.stakingKeeper, - ) + // app.incentiveKeeper = incentivekeeper.NewKeeper( + // appCodec, + // keys[incentivetypes.StoreKey], + // incentiveSubspace, + // app.bankKeeper, + // &cdpKeeper, + // &hardKeeper, + // app.accountKeeper, + // app.stakingKeeper, + // &swapKeeper, + // &savingsKeeper, + // &app.liquidKeeper, + // &earnKeeper, + // app.mintKeeper, + // app.distrKeeper, + // app.pricefeedKeeper, + // ) + // app.routerKeeper = routerkeeper.NewKeeper( + // &app.earnKeeper, + // app.liquidKeeper, + // app.stakingKeeper, + // ) // create committee keeper with router committeeGovRouter := govv1beta1.NewRouter() committeeGovRouter. AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). - AddRoute(communitytypes.RouterKey, community.NewCommunityPoolProposalHandler(app.communityKeeper)). + // AddRoute(communitytypes.RouterKey, community.NewCommunityPoolProposalHandler(app.communityKeeper)). AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.paramsKeeper)). AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(&app.upgradeKeeper)) // Note: the committee proposal handler is not registered on the committee router. This means committees cannot create or update other committees. @@ -763,14 +731,14 @@ func NewApp( stakingtypes.NewMultiStakingHooks( app.distrKeeper.Hooks(), app.slashingKeeper.Hooks(), - app.incentiveKeeper.Hooks(), + // app.incentiveKeeper.Hooks(), )) - app.swapKeeper = *swapKeeper.SetHooks(app.incentiveKeeper.Hooks()) - app.cdpKeeper = *cdpKeeper.SetHooks(cdptypes.NewMultiCDPHooks(app.incentiveKeeper.Hooks())) - app.hardKeeper = *hardKeeper.SetHooks(hardtypes.NewMultiHARDHooks(app.incentiveKeeper.Hooks())) - app.savingsKeeper = savingsKeeper // savings incentive hooks disabled - app.earnKeeper = *earnKeeper.SetHooks(app.incentiveKeeper.Hooks()) + // app.swapKeeper = *swapKeeper.SetHooks(app.incentiveKeeper.Hooks()) + // app.cdpKeeper = *cdpKeeper.SetHooks(cdptypes.NewMultiCDPHooks(app.incentiveKeeper.Hooks())) + // app.hardKeeper = *hardKeeper.SetHooks(hardtypes.NewMultiHARDHooks(app.incentiveKeeper.Hooks())) + // app.savingsKeeper = savingsKeeper // savings incentive hooks disabled + // app.earnKeeper = *earnKeeper.SetHooks(app.incentiveKeeper.Hooks()) // create gov keeper with router // NOTE this must be done after any keepers referenced in the gov router (ie committee) are defined @@ -780,9 +748,9 @@ func NewApp( AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.paramsKeeper)). AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(&app.upgradeKeeper)). AddRoute(ibcclienttypes.RouterKey, ibcclient.NewClientProposalHandler(app.ibcKeeper.ClientKeeper)). - AddRoute(kavadisttypes.RouterKey, kavadist.NewCommunityPoolMultiSpendProposalHandler(app.kavadistKeeper)). - AddRoute(earntypes.RouterKey, earn.NewCommunityPoolProposalHandler(app.earnKeeper)). - AddRoute(communitytypes.RouterKey, community.NewCommunityPoolProposalHandler(app.communityKeeper)). + // AddRoute(kavadisttypes.RouterKey, kavadist.NewCommunityPoolMultiSpendProposalHandler(app.kavadistKeeper)). + // AddRoute(earntypes.RouterKey, earn.NewCommunityPoolProposalHandler(app.earnKeeper)). + // AddRoute(communitytypes.RouterKey, community.NewCommunityPoolProposalHandler(app.communityKeeper)). AddRoute(committeetypes.RouterKey, committee.NewProposalHandler(app.committeeKeeper)) govConfig := govtypes.DefaultConfig() @@ -801,8 +769,10 @@ func NewApp( // override x/gov tally handler with custom implementation tallyHandler := NewTallyHandler( - app.govKeeper, *app.stakingKeeper, app.savingsKeeper, app.earnKeeper, - app.liquidKeeper, app.bankKeeper, + app.govKeeper, *app.stakingKeeper, + // app.savingsKeeper, app.earnKeeper, + // app.liquidKeeper, + app.bankKeeper, ) app.govKeeper.SetTallyHandler(tallyHandler) @@ -829,25 +799,25 @@ func NewApp( transferModule, vesting.NewAppModule(app.accountKeeper, app.bankKeeper), authzmodule.NewAppModule(appCodec, app.authzKeeper, app.accountKeeper, app.bankKeeper, app.interfaceRegistry), - kavadist.NewAppModule(app.kavadistKeeper, app.accountKeeper), - auction.NewAppModule(app.auctionKeeper, app.accountKeeper, app.bankKeeper), + // kavadist.NewAppModule(app.kavadistKeeper, app.accountKeeper), + // auction.NewAppModule(app.auctionKeeper, app.accountKeeper, app.bankKeeper), issuance.NewAppModule(app.issuanceKeeper, app.accountKeeper, app.bankKeeper), bep3.NewAppModule(app.bep3Keeper, app.accountKeeper, app.bankKeeper), pricefeed.NewAppModule(app.pricefeedKeeper, app.accountKeeper), validatorvesting.NewAppModule(app.bankKeeper), - swap.NewAppModule(app.swapKeeper, app.accountKeeper), - cdp.NewAppModule(app.cdpKeeper, app.accountKeeper, app.pricefeedKeeper, app.bankKeeper), - hard.NewAppModule(app.hardKeeper, app.accountKeeper, app.bankKeeper, app.pricefeedKeeper), + // swap.NewAppModule(app.swapKeeper, app.accountKeeper), + // cdp.NewAppModule(app.cdpKeeper, app.accountKeeper, app.pricefeedKeeper, app.bankKeeper), + // hard.NewAppModule(app.hardKeeper, app.accountKeeper, app.bankKeeper, app.pricefeedKeeper), committee.NewAppModule(app.committeeKeeper, app.accountKeeper), - incentive.NewAppModule(app.incentiveKeeper, app.accountKeeper, app.bankKeeper, app.cdpKeeper), + // incentive.NewAppModule(app.incentiveKeeper, app.accountKeeper, app.bankKeeper, app.cdpKeeper), evmutil.NewAppModule(app.evmutilKeeper, app.bankKeeper, app.accountKeeper), - savings.NewAppModule(app.savingsKeeper, app.accountKeeper, app.bankKeeper), - liquid.NewAppModule(app.liquidKeeper), - earn.NewAppModule(app.earnKeeper, app.accountKeeper, app.bankKeeper), - router.NewAppModule(app.routerKeeper), + // savings.NewAppModule(app.savingsKeeper, app.accountKeeper, app.bankKeeper), + // liquid.NewAppModule(app.liquidKeeper), + // earn.NewAppModule(app.earnKeeper, app.accountKeeper, app.bankKeeper), + // router.NewAppModule(app.routerKeeper), // nil InflationCalculationFn, use SDK's default inflation function mint.NewAppModule(appCodec, app.mintKeeper, app.accountKeeper, nil, mintSubspace), - community.NewAppModule(app.communityKeeper, app.accountKeeper), + // community.NewAppModule(app.communityKeeper, app.accountKeeper), metrics.NewAppModule(options.TelemetryOptions), ) @@ -863,7 +833,7 @@ func NewApp( committeetypes.ModuleName, // Community begin blocker should run before x/mint and x/kavadist since // the disable inflation upgrade will update those modules' params. - communitytypes.ModuleName, + // communitytypes.ModuleName, minttypes.ModuleName, distrtypes.ModuleName, // During begin block slashing happens after distr.BeginBlocker so that @@ -874,18 +844,18 @@ func NewApp( stakingtypes.ModuleName, feemarkettypes.ModuleName, evmtypes.ModuleName, - kavadisttypes.ModuleName, + // kavadisttypes.ModuleName, // Auction begin blocker will close out expired auctions and pay debt back to cdp. // It should be run before cdp begin blocker which cancels out debt with stable and starts more auctions. - auctiontypes.ModuleName, - cdptypes.ModuleName, + // auctiontypes.ModuleName, + // cdptypes.ModuleName, bep3types.ModuleName, - hardtypes.ModuleName, + // hardtypes.ModuleName, issuancetypes.ModuleName, - incentivetypes.ModuleName, + // incentivetypes.ModuleName, ibcexported.ModuleName, // Add all remaining modules with an empty begin blocker below since cosmos 0.45.0 requires it - swaptypes.ModuleName, + // swaptypes.ModuleName, vestingtypes.ModuleName, pricefeedtypes.ModuleName, validatorvestingtypes.ModuleName, @@ -898,10 +868,10 @@ func NewApp( paramstypes.ModuleName, authz.ModuleName, evmutiltypes.ModuleName, - savingstypes.ModuleName, - liquidtypes.ModuleName, - earntypes.ModuleName, - routertypes.ModuleName, + // savingstypes.ModuleName, + // liquidtypes.ModuleName, + // earntypes.ModuleName, + // routertypes.ModuleName, consensusparamtypes.ModuleName, packetforwardtypes.ModuleName, ) @@ -917,19 +887,19 @@ func NewApp( pricefeedtypes.ModuleName, // Add all remaining modules with an empty end blocker below since cosmos 0.45.0 requires it capabilitytypes.ModuleName, - incentivetypes.ModuleName, + // incentivetypes.ModuleName, issuancetypes.ModuleName, slashingtypes.ModuleName, distrtypes.ModuleName, - auctiontypes.ModuleName, + // auctiontypes.ModuleName, bep3types.ModuleName, - cdptypes.ModuleName, - hardtypes.ModuleName, + // cdptypes.ModuleName, + // hardtypes.ModuleName, committeetypes.ModuleName, upgradetypes.ModuleName, evidencetypes.ModuleName, - kavadisttypes.ModuleName, - swaptypes.ModuleName, + // kavadisttypes.ModuleName, + // swaptypes.ModuleName, vestingtypes.ModuleName, ibcexported.ModuleName, validatorvestingtypes.ModuleName, @@ -940,12 +910,12 @@ func NewApp( paramstypes.ModuleName, authz.ModuleName, evmutiltypes.ModuleName, - savingstypes.ModuleName, - liquidtypes.ModuleName, - earntypes.ModuleName, - routertypes.ModuleName, + // savingstypes.ModuleName, + // liquidtypes.ModuleName, + // earntypes.ModuleName, + // routertypes.ModuleName, minttypes.ModuleName, - communitytypes.ModuleName, + // communitytypes.ModuleName, metricstypes.ModuleName, consensusparamtypes.ModuleName, packetforwardtypes.ModuleName, @@ -967,28 +937,28 @@ func NewApp( ibctransfertypes.ModuleName, evmtypes.ModuleName, feemarkettypes.ModuleName, - kavadisttypes.ModuleName, - auctiontypes.ModuleName, + // kavadisttypes.ModuleName, + // auctiontypes.ModuleName, issuancetypes.ModuleName, - savingstypes.ModuleName, + // savingstypes.ModuleName, bep3types.ModuleName, pricefeedtypes.ModuleName, - swaptypes.ModuleName, - cdptypes.ModuleName, // reads market prices, so must run after pricefeed genesis - hardtypes.ModuleName, - incentivetypes.ModuleName, // reads cdp params, so must run after cdp genesis + // swaptypes.ModuleName, + // cdptypes.ModuleName, // reads market prices, so must run after pricefeed genesis + // hardtypes.ModuleName, + // incentivetypes.ModuleName, // reads cdp params, so must run after cdp genesis committeetypes.ModuleName, evmutiltypes.ModuleName, - earntypes.ModuleName, - communitytypes.ModuleName, + // earntypes.ModuleName, + // communitytypes.ModuleName, genutiltypes.ModuleName, // runs arbitrary txs included in genisis state, so run after modules have been initialized // Add all remaining modules with an empty InitGenesis below since cosmos 0.45.0 requires it vestingtypes.ModuleName, paramstypes.ModuleName, upgradetypes.ModuleName, validatorvestingtypes.ModuleName, - liquidtypes.ModuleName, - routertypes.ModuleName, + // liquidtypes.ModuleName, + // routertypes.ModuleName, metricstypes.ModuleName, consensusparamtypes.ModuleName, packetforwardtypes.ModuleName, @@ -1198,15 +1168,15 @@ func (app *App) loadBlockedMaccAddrs() map[string]bool { modAccAddrs := app.ModuleAccountAddrs() allowedMaccs := map[string]bool{ // kavadist - app.accountKeeper.GetModuleAddress(kavadisttypes.ModuleName).String(): true, + // app.accountKeeper.GetModuleAddress(kavadisttypes.ModuleName).String(): true, // earn - app.accountKeeper.GetModuleAddress(earntypes.ModuleName).String(): true, + // app.accountKeeper.GetModuleAddress(earntypes.ModuleName).String(): true, // liquid - app.accountKeeper.GetModuleAddress(liquidtypes.ModuleName).String(): true, + // app.accountKeeper.GetModuleAddress(liquidtypes.ModuleName).String(): true, // kavadist fund - app.accountKeeper.GetModuleAddress(kavadisttypes.FundModuleAccount).String(): true, + // app.accountKeeper.GetModuleAddress(kavadisttypes.FundModuleAccount).String(): true, // community - app.accountKeeper.GetModuleAddress(communitytypes.ModuleAccountName).String(): true, + // app.accountKeeper.GetModuleAddress(communitytypes.ModuleAccountName).String(): true, // NOTE: if adding evmutil, adjust the cosmos-coins-fully-backed-invariant accordingly. } diff --git a/app/tally_handler.go b/app/tally_handler.go index f8c2e599..961eae15 100644 --- a/app/tally_handler.go +++ b/app/tally_handler.go @@ -2,10 +2,6 @@ package app import ( sdkmath "cosmossdk.io/math" - earnkeeper "github.com/0glabs/0g-chain/x/earn/keeper" - liquidkeeper "github.com/0glabs/0g-chain/x/liquid/keeper" - liquidtypes "github.com/0glabs/0g-chain/x/liquid/types" - savingskeeper "github.com/0glabs/0g-chain/x/savings/keeper" 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" @@ -20,24 +16,26 @@ var _ govv1.TallyHandler = TallyHandler{} type TallyHandler struct { gk govkeeper.Keeper stk stakingkeeper.Keeper - svk savingskeeper.Keeper - ek earnkeeper.Keeper - lk liquidkeeper.Keeper - bk bankkeeper.Keeper + // svk savingskeeper.Keeper + // ek earnkeeper.Keeper + // lk liquidkeeper.Keeper + bk bankkeeper.Keeper } // NewTallyHandler creates a new tally handler. func NewTallyHandler( - gk govkeeper.Keeper, stk stakingkeeper.Keeper, svk savingskeeper.Keeper, - ek earnkeeper.Keeper, lk liquidkeeper.Keeper, bk bankkeeper.Keeper, + gk govkeeper.Keeper, stk stakingkeeper.Keeper, + // svk savingskeeper.Keeper, + // ek earnkeeper.Keeper, lk liquidkeeper.Keeper, + bk bankkeeper.Keeper, ) TallyHandler { return TallyHandler{ gk: gk, stk: stk, - svk: svk, - ek: ek, - lk: lk, - bk: bk, + // svk: svk, + // ek: ek, + // lk: lk, + bk: bk, } } @@ -105,34 +103,34 @@ func (th TallyHandler) Tally( }) // get voter bkava and update total voting power and results - addrBkava := th.getAddrBkava(ctx, voter).toCoins() - for _, coin := range addrBkava { - valAddr, err := liquidtypes.ParseLiquidStakingTokenDenom(coin.Denom) - if err != nil { - break - } + // addrBkava := th.getAddrBkava(ctx, voter).toCoins() + // for _, coin := range addrBkava { + // valAddr, err := liquidtypes.ParseLiquidStakingTokenDenom(coin.Denom) + // if err != nil { + // break + // } - // reduce delegator shares by the amount of voter bkava for the validator - valAddrStr := valAddr.String() - if val, ok := currValidators[valAddrStr]; ok { - val.DelegatorDeductions = val.DelegatorDeductions.Add(sdk.NewDecFromInt(coin.Amount)) - currValidators[valAddrStr] = val - } + // // reduce delegator shares by the amount of voter bkava for the validator + // valAddrStr := valAddr.String() + // if val, ok := currValidators[valAddrStr]; ok { + // val.DelegatorDeductions = val.DelegatorDeductions.Add(sdk.NewDecFromInt(coin.Amount)) + // currValidators[valAddrStr] = val + // } - // votingPower = amount of ukava coin - stakedCoins, err := th.lk.GetStakedTokensForDerivatives(ctx, sdk.NewCoins(coin)) - if err != nil { - // error is returned only if the bkava denom is incorrect, which should never happen here. - panic(err) - } - votingPower := sdk.NewDecFromInt(stakedCoins.Amount) + // // votingPower = amount of ukava coin + // stakedCoins, err := th.lk.GetStakedTokensForDerivatives(ctx, sdk.NewCoins(coin)) + // if err != nil { + // // error is returned only if the bkava denom is incorrect, which should never happen here. + // panic(err) + // } + // votingPower := sdk.NewDecFromInt(stakedCoins.Amount) - for _, option := range vote.Options { - subPower := votingPower.Mul(sdk.MustNewDecFromStr(option.Weight)) - results[option.Option] = results[option.Option].Add(subPower) - } - totalVotingPower = totalVotingPower.Add(votingPower) - } + // for _, option := range vote.Options { + // subPower := votingPower.Mul(sdk.MustNewDecFromStr(option.Weight)) + // results[option.Option] = results[option.Option].Add(subPower) + // } + // totalVotingPower = totalVotingPower.Add(votingPower) + // } th.gk.DeleteVote(ctx, vote.ProposalId, voter) return false @@ -219,38 +217,38 @@ func (th TallyHandler) getAddrBkava(ctx sdk.Context, addr sdk.AccAddress) bkavaB // addBkavaFromWallet adds all addr balances of bkava in x/bank. func (th TallyHandler) addBkavaFromWallet(ctx sdk.Context, addr sdk.AccAddress, bkava bkavaByDenom) { - coins := th.bk.GetAllBalances(ctx, addr) - for _, coin := range coins { - if th.lk.IsDerivativeDenom(ctx, coin.Denom) { - bkava.add(coin) - } - } + // coins := th.bk.GetAllBalances(ctx, addr) + // for _, coin := range coins { + // if th.lk.IsDerivativeDenom(ctx, coin.Denom) { + // bkava.add(coin) + // } + // } } // addBkavaFromSavings adds all addr deposits of bkava in x/savings. func (th TallyHandler) addBkavaFromSavings(ctx sdk.Context, addr sdk.AccAddress, bkava bkavaByDenom) { - deposit, found := th.svk.GetDeposit(ctx, addr) - if !found { - return - } - for _, coin := range deposit.Amount { - if th.lk.IsDerivativeDenom(ctx, coin.Denom) { - bkava.add(coin) - } - } + // deposit, found := th.svk.GetDeposit(ctx, addr) + // if !found { + // return + // } + // for _, coin := range deposit.Amount { + // if th.lk.IsDerivativeDenom(ctx, coin.Denom) { + // bkava.add(coin) + // } + // } } // addBkavaFromEarn adds all addr deposits of bkava in x/earn. func (th TallyHandler) addBkavaFromEarn(ctx sdk.Context, addr sdk.AccAddress, bkava bkavaByDenom) { - shares, found := th.ek.GetVaultAccountShares(ctx, addr) - if !found { - return - } - for _, share := range shares { - if th.lk.IsDerivativeDenom(ctx, share.Denom) { - if coin, err := th.ek.ConvertToAssets(ctx, share); err == nil { - bkava.add(coin) - } - } - } + // shares, found := th.ek.GetVaultAccountShares(ctx, addr) + // if !found { + // return + // } + // for _, share := range shares { + // if th.lk.IsDerivativeDenom(ctx, share.Denom) { + // if coin, err := th.ek.ConvertToAssets(ctx, share); err == nil { + // bkava.add(coin) + // } + // } + // } } diff --git a/app/tally_handler_test.go b/app/tally_handler_test.go index 2dae1da8..3935aff0 100644 --- a/app/tally_handler_test.go +++ b/app/tally_handler_test.go @@ -16,9 +16,6 @@ import ( stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/suite" - - earntypes "github.com/0glabs/0g-chain/x/earn/types" - liquidtypes "github.com/0glabs/0g-chain/x/liquid/types" ) // d is an alias for sdk.MustNewDecFromStr @@ -51,9 +48,9 @@ func (suite *tallyHandlerSuite) SetupTest() { suite.tallier = NewTallyHandler( suite.app.GetGovKeeper(), stakingKeeper, - suite.app.GetSavingsKeeper(), - suite.app.GetEarnKeeper(), - suite.app.GetLiquidKeeper(), + // suite.app.GetSavingsKeeper(), + // suite.app.GetEarnKeeper(), + // suite.app.GetLiquidKeeper(), suite.app.GetBankKeeper(), ) } @@ -271,39 +268,40 @@ func (suite *tallyHandlerSuite) newBondCoin(amount sdkmath.Int) sdk.Coin { } func (suite *tallyHandlerSuite) allowBKavaEarnDeposits() { - ek := suite.app.GetEarnKeeper() - earnParams := ek.GetParams(suite.ctx) + // ek := suite.app.GetEarnKeeper() + // earnParams := ek.GetParams(suite.ctx) - vault := earntypes.NewAllowedVault( - liquidtypes.DefaultDerivativeDenom, - earntypes.StrategyTypes{earntypes.STRATEGY_TYPE_SAVINGS}, - false, - nil, - ) + // vault := earntypes.NewAllowedVault( + // liquidtypes.DefaultDerivativeDenom, + // earntypes.StrategyTypes{earntypes.STRATEGY_TYPE_SAVINGS}, + // false, + // nil, + // ) - earnParams.AllowedVaults = append(earnParams.AllowedVaults, vault) - ek.SetParams(suite.ctx, earnParams) + // earnParams.AllowedVaults = append(earnParams.AllowedVaults, vault) + // ek.SetParams(suite.ctx, earnParams) - sk := suite.app.GetSavingsKeeper() - savingsParams := sk.GetParams(suite.ctx) - savingsParams.SupportedDenoms = append(savingsParams.SupportedDenoms, liquidtypes.DefaultDerivativeDenom) - sk.SetParams(suite.ctx, savingsParams) + // sk := suite.app.GetSavingsKeeper() + // savingsParams := sk.GetParams(suite.ctx) + // savingsParams.SupportedDenoms = append(savingsParams.SupportedDenoms, liquidtypes.DefaultDerivativeDenom) + // sk.SetParams(suite.ctx, savingsParams) } func (suite *tallyHandlerSuite) earnDeposit(owner sdk.AccAddress, derivative sdk.Coin) { - ek := suite.app.GetEarnKeeper() + // ek := suite.app.GetEarnKeeper() - err := ek.Deposit(suite.ctx, owner, derivative, earntypes.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) + // err := ek.Deposit(suite.ctx, owner, derivative, earntypes.STRATEGY_TYPE_SAVINGS) + // suite.Require().NoError(err) } func (suite *tallyHandlerSuite) mintDerivative(owner sdk.AccAddress, validator sdk.ValAddress, amount sdkmath.Int) sdk.Coin { - lk := suite.app.GetLiquidKeeper() + // lk := suite.app.GetLiquidKeeper() - minted, err := lk.MintDerivative(suite.ctx, owner, validator, suite.newBondCoin(amount)) - suite.Require().NoError(err) + // minted, err := lk.MintDerivative(suite.ctx, owner, validator, suite.newBondCoin(amount)) + // suite.Require().NoError(err) - return minted + // return minted + return sdk.NewCoin("ukava", amount) } func (suite *tallyHandlerSuite) delegateToNewBondedValidator(delegator sdk.AccAddress, amount sdkmath.Int) stakingtypes.ValidatorI { diff --git a/app/test_common.go b/app/test_common.go index ebf23b10..5b654092 100644 --- a/app/test_common.go +++ b/app/test_common.go @@ -41,22 +41,11 @@ import ( feemarketkeeper "github.com/evmos/ethermint/x/feemarket/keeper" "github.com/stretchr/testify/require" - auctionkeeper "github.com/0glabs/0g-chain/x/auction/keeper" bep3keeper "github.com/0glabs/0g-chain/x/bep3/keeper" - cdpkeeper "github.com/0glabs/0g-chain/x/cdp/keeper" committeekeeper "github.com/0glabs/0g-chain/x/committee/keeper" - communitykeeper "github.com/0glabs/0g-chain/x/community/keeper" - earnkeeper "github.com/0glabs/0g-chain/x/earn/keeper" evmutilkeeper "github.com/0glabs/0g-chain/x/evmutil/keeper" - hardkeeper "github.com/0glabs/0g-chain/x/hard/keeper" - incentivekeeper "github.com/0glabs/0g-chain/x/incentive/keeper" issuancekeeper "github.com/0glabs/0g-chain/x/issuance/keeper" - kavadistkeeper "github.com/0glabs/0g-chain/x/kavadist/keeper" - liquidkeeper "github.com/0glabs/0g-chain/x/liquid/keeper" pricefeedkeeper "github.com/0glabs/0g-chain/x/pricefeed/keeper" - routerkeeper "github.com/0glabs/0g-chain/x/router/keeper" - savingskeeper "github.com/0glabs/0g-chain/x/savings/keeper" - swapkeeper "github.com/0glabs/0g-chain/x/swap/keeper" ) var ( @@ -117,24 +106,29 @@ func (tApp TestApp) GetDistrKeeper() distkeeper.Keeper { return tApp.di func (tApp TestApp) GetGovKeeper() govkeeper.Keeper { return tApp.govKeeper } func (tApp TestApp) GetCrisisKeeper() crisiskeeper.Keeper { return tApp.crisisKeeper } func (tApp TestApp) GetParamsKeeper() paramskeeper.Keeper { return tApp.paramsKeeper } -func (tApp TestApp) GetKavadistKeeper() kavadistkeeper.Keeper { return tApp.kavadistKeeper } -func (tApp TestApp) GetAuctionKeeper() auctionkeeper.Keeper { return tApp.auctionKeeper } + +// func (tApp TestApp) GetKavadistKeeper() kavadistkeeper.Keeper { return tApp.kavadistKeeper } +// func (tApp TestApp) GetAuctionKeeper() auctionkeeper.Keeper { return tApp.auctionKeeper } func (tApp TestApp) GetIssuanceKeeper() issuancekeeper.Keeper { return tApp.issuanceKeeper } func (tApp TestApp) GetBep3Keeper() bep3keeper.Keeper { return tApp.bep3Keeper } func (tApp TestApp) GetPriceFeedKeeper() pricefeedkeeper.Keeper { return tApp.pricefeedKeeper } -func (tApp TestApp) GetSwapKeeper() swapkeeper.Keeper { return tApp.swapKeeper } -func (tApp TestApp) GetCDPKeeper() cdpkeeper.Keeper { return tApp.cdpKeeper } -func (tApp TestApp) GetHardKeeper() hardkeeper.Keeper { return tApp.hardKeeper } + +// func (tApp TestApp) GetSwapKeeper() swapkeeper.Keeper { return tApp.swapKeeper } +// func (tApp TestApp) GetCDPKeeper() cdpkeeper.Keeper { return tApp.cdpKeeper } +// func (tApp TestApp) GetHardKeeper() hardkeeper.Keeper { return tApp.hardKeeper } func (tApp TestApp) GetCommitteeKeeper() committeekeeper.Keeper { return tApp.committeeKeeper } -func (tApp TestApp) GetIncentiveKeeper() incentivekeeper.Keeper { return tApp.incentiveKeeper } -func (tApp TestApp) GetEvmutilKeeper() evmutilkeeper.Keeper { return tApp.evmutilKeeper } -func (tApp TestApp) GetEvmKeeper() *evmkeeper.Keeper { return tApp.evmKeeper } -func (tApp TestApp) GetSavingsKeeper() savingskeeper.Keeper { return tApp.savingsKeeper } + +// func (tApp TestApp) GetIncentiveKeeper() incentivekeeper.Keeper { return tApp.incentiveKeeper } +func (tApp TestApp) GetEvmutilKeeper() evmutilkeeper.Keeper { return tApp.evmutilKeeper } +func (tApp TestApp) GetEvmKeeper() *evmkeeper.Keeper { return tApp.evmKeeper } + +// func (tApp TestApp) GetSavingsKeeper() savingskeeper.Keeper { return tApp.savingsKeeper } func (tApp TestApp) GetFeeMarketKeeper() feemarketkeeper.Keeper { return tApp.feeMarketKeeper } -func (tApp TestApp) GetLiquidKeeper() liquidkeeper.Keeper { return tApp.liquidKeeper } -func (tApp TestApp) GetEarnKeeper() earnkeeper.Keeper { return tApp.earnKeeper } -func (tApp TestApp) GetRouterKeeper() routerkeeper.Keeper { return tApp.routerKeeper } -func (tApp TestApp) GetCommunityKeeper() communitykeeper.Keeper { return tApp.communityKeeper } + +// func (tApp TestApp) GetLiquidKeeper() liquidkeeper.Keeper { return tApp.liquidKeeper } +// func (tApp TestApp) GetEarnKeeper() earnkeeper.Keeper { return tApp.earnKeeper } +// func (tApp TestApp) GetRouterKeeper() routerkeeper.Keeper { return tApp.routerKeeper } +// func (tApp TestApp) GetCommunityKeeper() communitykeeper.Keeper { return tApp.communityKeeper } func (tApp TestApp) GetKVStoreKey(key string) *storetypes.KVStoreKey { return tApp.keys[key] diff --git a/app/upgrades.go b/app/upgrades.go index 90823ffa..10146175 100644 --- a/app/upgrades.go +++ b/app/upgrades.go @@ -131,9 +131,9 @@ func upgradeHandler( // Set risky CDP's to sync interest and liquidate every 100 blocks instead // of every block. This significantly improves performance as this cdp // process is a signification porition of time spent during block execution. - cdpParams := app.cdpKeeper.GetParams(ctx) - cdpParams.LiquidationBlockInterval = CDPLiquidationBlockInterval - app.cdpKeeper.SetParams(ctx, cdpParams) + // cdpParams := app.cdpKeeper.GetParams(ctx) + // cdpParams.LiquidationBlockInterval = CDPLiquidationBlockInterval + // app.cdpKeeper.SetParams(ctx, cdpParams) return versionMap, err } diff --git a/client/grpc/query/query.go b/client/grpc/query/query.go index 04515597..9d7179ca 100644 --- a/client/grpc/query/query.go +++ b/client/grpc/query/query.go @@ -24,21 +24,11 @@ import ( evmtypes "github.com/evmos/ethermint/x/evm/types" feemarkettypes "github.com/evmos/ethermint/x/feemarket/types" - auctiontypes "github.com/0glabs/0g-chain/x/auction/types" bep3types "github.com/0glabs/0g-chain/x/bep3/types" - cdptypes "github.com/0glabs/0g-chain/x/cdp/types" committeetypes "github.com/0glabs/0g-chain/x/committee/types" - communitytypes "github.com/0glabs/0g-chain/x/community/types" - earntypes "github.com/0glabs/0g-chain/x/earn/types" evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types" - hardtypes "github.com/0glabs/0g-chain/x/hard/types" - incentivetypes "github.com/0glabs/0g-chain/x/incentive/types" issuancetypes "github.com/0glabs/0g-chain/x/issuance/types" - kavadisttypes "github.com/0glabs/0g-chain/x/kavadist/types" - liquidtypes "github.com/0glabs/0g-chain/x/liquid/types" pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" - savingstypes "github.com/0glabs/0g-chain/x/savings/types" - swaptypes "github.com/0glabs/0g-chain/x/swap/types" ) // QueryClient is a wrapper with all Cosmos and Kava grpc query clients @@ -70,21 +60,21 @@ type QueryClient struct { // kava module query clients - Auction auctiontypes.QueryClient - Bep3 bep3types.QueryClient - Cdp cdptypes.QueryClient + // Auction auctiontypes.QueryClient + Bep3 bep3types.QueryClient + // Cdp cdptypes.QueryClient Committee committeetypes.QueryClient - Community communitytypes.QueryClient - Earn earntypes.QueryClient - Evmutil evmutiltypes.QueryClient - Hard hardtypes.QueryClient - Incentive incentivetypes.QueryClient - Issuance issuancetypes.QueryClient - Kavadist kavadisttypes.QueryClient - Liquid liquidtypes.QueryClient + // Community communitytypes.QueryClient + // Earn earntypes.QueryClient + Evmutil evmutiltypes.QueryClient + // Hard hardtypes.QueryClient + // Incentive incentivetypes.QueryClient + Issuance issuancetypes.QueryClient + // Kavadist kavadisttypes.QueryClient + // Liquid liquidtypes.QueryClient Pricefeed pricefeedtypes.QueryClient - Savings savingstypes.QueryClient - Swap swaptypes.QueryClient + // Savings savingstypes.QueryClient + // Swap swaptypes.QueryClient } // NewQueryClient creates a new QueryClient and initializes all the module query clients @@ -115,21 +105,21 @@ func NewQueryClient(grpcEndpoint string) (*QueryClient, error) { IbcClient: ibcclienttypes.NewQueryClient(conn), IbcTransfer: ibctransfertypes.NewQueryClient(conn), - Auction: auctiontypes.NewQueryClient(conn), - Bep3: bep3types.NewQueryClient(conn), - Cdp: cdptypes.NewQueryClient(conn), + // Auction: auctiontypes.NewQueryClient(conn), + Bep3: bep3types.NewQueryClient(conn), + // Cdp: cdptypes.NewQueryClient(conn), Committee: committeetypes.NewQueryClient(conn), - Community: communitytypes.NewQueryClient(conn), - Earn: earntypes.NewQueryClient(conn), - Evmutil: evmutiltypes.NewQueryClient(conn), - Hard: hardtypes.NewQueryClient(conn), - Incentive: incentivetypes.NewQueryClient(conn), - Issuance: issuancetypes.NewQueryClient(conn), - Kavadist: kavadisttypes.NewQueryClient(conn), - Liquid: liquidtypes.NewQueryClient(conn), + // Community: communitytypes.NewQueryClient(conn), + // Earn: earntypes.NewQueryClient(conn), + Evmutil: evmutiltypes.NewQueryClient(conn), + // Hard: hardtypes.NewQueryClient(conn), + // Incentive: incentivetypes.NewQueryClient(conn), + Issuance: issuancetypes.NewQueryClient(conn), + // Kavadist: kavadisttypes.NewQueryClient(conn), + // Liquid: liquidtypes.NewQueryClient(conn), Pricefeed: pricefeedtypes.NewQueryClient(conn), - Savings: savingstypes.NewQueryClient(conn), - Swap: swaptypes.NewQueryClient(conn), + // Savings: savingstypes.NewQueryClient(conn), + // Swap: swaptypes.NewQueryClient(conn), } return client, nil } diff --git a/client/grpc/query/query_test.go b/client/grpc/query/query_test.go index 47113a0c..568097b1 100644 --- a/client/grpc/query/query_test.go +++ b/client/grpc/query/query_test.go @@ -55,20 +55,20 @@ func TestNewQueryClient_ValidClient(t *testing.T) { require.NotNil(t, client.IbcTransfer) // validate kava clients - require.NotNil(t, client.Auction) + // require.NotNil(t, client.Auction) require.NotNil(t, client.Bep3) - require.NotNil(t, client.Cdp) + // require.NotNil(t, client.Cdp) require.NotNil(t, client.Committee) - require.NotNil(t, client.Community) - require.NotNil(t, client.Earn) + // require.NotNil(t, client.Community) + // require.NotNil(t, client.Earn) require.NotNil(t, client.Evmutil) - require.NotNil(t, client.Hard) - require.NotNil(t, client.Incentive) + // require.NotNil(t, client.Hard) + // require.NotNil(t, client.Incentive) require.NotNil(t, client.Issuance) - require.NotNil(t, client.Kavadist) - require.NotNil(t, client.Liquid) + // require.NotNil(t, client.Kavadist) + // require.NotNil(t, client.Liquid) require.NotNil(t, client.Pricefeed) - require.NotNil(t, client.Savings) - require.NotNil(t, client.Swap) + // require.NotNil(t, client.Savings) + // require.NotNil(t, client.Swap) }) } diff --git a/proto/kava/auction/v1beta1/auction.proto b/proto/kava/auction/v1beta1/auction.proto deleted file mode 100644 index f9772062..00000000 --- a/proto/kava/auction/v1beta1/auction.proto +++ /dev/null @@ -1,98 +0,0 @@ -syntax = "proto3"; -package kava.auction.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/auction/types"; -option (gogoproto.goproto_getters_all) = false; - -// BaseAuction defines common attributes of all auctions -message BaseAuction { - option (cosmos_proto.implements_interface) = "Auction"; - - uint64 id = 1 [(gogoproto.customname) = "ID"]; - - string initiator = 2; - - cosmos.base.v1beta1.Coin lot = 3 [(gogoproto.nullable) = false]; - - bytes bidder = 4 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - - cosmos.base.v1beta1.Coin bid = 5 [(gogoproto.nullable) = false]; - - bool has_received_bids = 6; - - google.protobuf.Timestamp end_time = 7 [ - (gogoproto.nullable) = false, - (gogoproto.stdtime) = true - ]; - - google.protobuf.Timestamp max_end_time = 8 [ - (gogoproto.nullable) = false, - (gogoproto.stdtime) = true - ]; -} - -// SurplusAuction is a forward auction that burns what it receives from bids. -// It is normally used to sell off excess pegged asset acquired by the CDP system. -message SurplusAuction { - option (cosmos_proto.implements_interface) = "Auction"; - - BaseAuction base_auction = 1 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false - ]; -} - -// DebtAuction is a reverse auction that mints what it pays out. -// It is normally used to acquire pegged asset to cover the CDP system's debts that were not covered by selling -// collateral. -message DebtAuction { - option (cosmos_proto.implements_interface) = "Auction"; - - BaseAuction base_auction = 1 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false - ]; - - cosmos.base.v1beta1.Coin corresponding_debt = 2 [(gogoproto.nullable) = false]; -} - -// CollateralAuction is a two phase auction. -// Initially, in forward auction phase, bids can be placed up to a max bid. -// Then it switches to a reverse auction phase, where the initial amount up for auction is bid down. -// Unsold Lot is sent to LotReturns, being divided among the addresses by weight. -// Collateral auctions are normally used to sell off collateral seized from CDPs. -message CollateralAuction { - option (cosmos_proto.implements_interface) = "Auction"; - - BaseAuction base_auction = 1 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false - ]; - - cosmos.base.v1beta1.Coin corresponding_debt = 2 [(gogoproto.nullable) = false]; - - cosmos.base.v1beta1.Coin max_bid = 3 [(gogoproto.nullable) = false]; - - WeightedAddresses lot_returns = 4 [(gogoproto.nullable) = false]; -} - -// WeightedAddresses is a type for storing some addresses and associated weights. -message WeightedAddresses { - repeated bytes addresses = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - - repeated bytes weights = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/auction/v1beta1/genesis.proto b/proto/kava/auction/v1beta1/genesis.proto deleted file mode 100644 index 9b4be0a1..00000000 --- a/proto/kava/auction/v1beta1/genesis.proto +++ /dev/null @@ -1,55 +0,0 @@ -syntax = "proto3"; -package kava.auction.v1beta1; - -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/any.proto"; -import "google/protobuf/duration.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/auction/types"; -option (gogoproto.goproto_getters_all) = false; - -// GenesisState defines the auction module's genesis state. -message GenesisState { - uint64 next_auction_id = 1; - - Params params = 2 [(gogoproto.nullable) = false]; - - // Genesis auctions - repeated google.protobuf.Any auctions = 3 [(cosmos_proto.accepts_interface) = "GenesisAuction"]; -} - -// Params defines the parameters for the issuance module. -message Params { - reserved 2; - reserved "bid_duration"; - - google.protobuf.Duration max_auction_duration = 1 [ - (gogoproto.nullable) = false, - (gogoproto.stdduration) = true - ]; - - google.protobuf.Duration forward_bid_duration = 6 [ - (gogoproto.nullable) = false, - (gogoproto.stdduration) = true - ]; - google.protobuf.Duration reverse_bid_duration = 7 [ - (gogoproto.nullable) = false, - (gogoproto.stdduration) = true - ]; - - bytes increment_surplus = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - bytes increment_debt = 4 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - bytes increment_collateral = 5 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/auction/v1beta1/query.proto b/proto/kava/auction/v1beta1/query.proto deleted file mode 100644 index 40cb9208..00000000 --- a/proto/kava/auction/v1beta1/query.proto +++ /dev/null @@ -1,84 +0,0 @@ -syntax = "proto3"; -package kava.auction.v1beta1; - -import "cosmos/base/query/v1beta1/pagination.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "google/protobuf/any.proto"; -import "kava/auction/v1beta1/genesis.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/auction/types"; - -// Query defines the gRPC querier service for auction module -service Query { - // Params queries all parameters of the auction module. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/auction/v1beta1/params"; - } - - // Auction queries an individual Auction by auction ID - rpc Auction(QueryAuctionRequest) returns (QueryAuctionResponse) { - option (google.api.http).get = "/kava/auction/v1beta1/auctions/{auction_id}"; - } - - // Auctions queries auctions filtered by asset denom, owner address, phase, and auction type - rpc Auctions(QueryAuctionsRequest) returns (QueryAuctionsResponse) { - option (google.api.http).get = "/kava/auction/v1beta1/auctions"; - } - - // NextAuctionID queries the next auction ID - rpc NextAuctionID(QueryNextAuctionIDRequest) returns (QueryNextAuctionIDResponse) { - option (google.api.http).get = "/kava/auction/v1beta1/next-auction-id"; - } -} - -// QueryParamsRequest defines the request type for querying x/auction parameters. -message QueryParamsRequest {} - -// QueryParamsResponse defines the response type for querying x/auction parameters. -message QueryParamsResponse { - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryAuctionRequest is the request type for the Query/Auction RPC method. -message QueryAuctionRequest { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - uint64 auction_id = 1; -} - -// QueryAuctionResponse is the response type for the Query/Auction RPC method. -message QueryAuctionResponse { - google.protobuf.Any auction = 1; -} - -// QueryAuctionsRequest is the request type for the Query/Auctions RPC method. -message QueryAuctionsRequest { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string type = 1; - string owner = 2; - string denom = 3; - string phase = 4; - - // pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 5; -} - -// QueryAuctionsResponse is the response type for the Query/Auctions RPC method. -message QueryAuctionsResponse { - repeated google.protobuf.Any auctions = 1; - - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryNextAuctionIDRequest defines the request type for querying x/auction next auction ID. -message QueryNextAuctionIDRequest {} - -// QueryNextAuctionIDResponse defines the response type for querying x/auction next auction ID. -message QueryNextAuctionIDResponse { - uint64 id = 1; -} diff --git a/proto/kava/auction/v1beta1/tx.proto b/proto/kava/auction/v1beta1/tx.proto deleted file mode 100644 index 37719b75..00000000 --- a/proto/kava/auction/v1beta1/tx.proto +++ /dev/null @@ -1,28 +0,0 @@ -syntax = "proto3"; -package kava.auction.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/auction/types"; - -// Msg defines the auction Msg service. -service Msg { - // PlaceBid message type used by bidders to place bids on auctions - rpc PlaceBid(MsgPlaceBid) returns (MsgPlaceBidResponse); -} - -// MsgPlaceBid represents a message used by bidders to place bids on auctions -message MsgPlaceBid { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - uint64 auction_id = 1; - - string bidder = 2; - - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// MsgPlaceBidResponse defines the Msg/PlaceBid response type. -message MsgPlaceBidResponse {} diff --git a/proto/kava/cdp/v1beta1/cdp.proto b/proto/kava/cdp/v1beta1/cdp.proto deleted file mode 100644 index d75688b5..00000000 --- a/proto/kava/cdp/v1beta1/cdp.proto +++ /dev/null @@ -1,59 +0,0 @@ -syntax = "proto3"; -package kava.cdp.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/cdp/types"; -option (gogoproto.goproto_getters_all) = false; - -// CDP defines the state of a single collateralized debt position. -message CDP { - uint64 id = 1 [(gogoproto.customname) = "ID"]; - bytes owner = 2 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - string type = 3; - cosmos.base.v1beta1.Coin collateral = 4 [(gogoproto.nullable) = false]; - cosmos.base.v1beta1.Coin principal = 5 [(gogoproto.nullable) = false]; - cosmos.base.v1beta1.Coin accumulated_fees = 6 [(gogoproto.nullable) = false]; - google.protobuf.Timestamp fees_updated = 7 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - string interest_factor = 8 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// Deposit defines an amount of coins deposited by an account to a cdp -message Deposit { - uint64 cdp_id = 1 [(gogoproto.customname) = "CdpID"]; - string depositor = 2 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// TotalPrincipal defines the total principal of a given collateral type -message TotalPrincipal { - string collateral_type = 1; - cosmos.base.v1beta1.Coin amount = 2 [(gogoproto.nullable) = false]; -} - -// TotalCollateral defines the total collateral of a given collateral type -message TotalCollateral { - string collateral_type = 1; - cosmos.base.v1beta1.Coin amount = 2 [(gogoproto.nullable) = false]; -} - -// OwnerCDPIndex defines the cdp ids for a single cdp owner -message OwnerCDPIndex { - repeated uint64 cdp_ids = 1 [(gogoproto.customname) = "CdpIDs"]; -} diff --git a/proto/kava/cdp/v1beta1/genesis.proto b/proto/kava/cdp/v1beta1/genesis.proto deleted file mode 100644 index f93c5af9..00000000 --- a/proto/kava/cdp/v1beta1/genesis.proto +++ /dev/null @@ -1,155 +0,0 @@ -syntax = "proto3"; -package kava.cdp.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; -import "kava/cdp/v1beta1/cdp.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/cdp/types"; - -// GenesisState defines the cdp module's genesis state. -message GenesisState { - // params defines all the parameters of the module. - Params params = 1 [(gogoproto.nullable) = false]; - - repeated CDP cdps = 2 [ - (gogoproto.customname) = "CDPs", - (gogoproto.castrepeated) = "CDPs", - (gogoproto.nullable) = false - ]; - repeated Deposit deposits = 3 [ - (gogoproto.castrepeated) = "Deposits", - (gogoproto.nullable) = false - ]; - uint64 starting_cdp_id = 4 [(gogoproto.customname) = "StartingCdpID"]; - string debt_denom = 5; - string gov_denom = 6; - repeated GenesisAccumulationTime previous_accumulation_times = 7 [ - (gogoproto.castrepeated) = "GenesisAccumulationTimes", - (gogoproto.nullable) = false - ]; - repeated GenesisTotalPrincipal total_principals = 8 [ - (gogoproto.castrepeated) = "GenesisTotalPrincipals", - (gogoproto.nullable) = false - ]; -} - -// Params defines the parameters for the cdp module. -message Params { - repeated CollateralParam collateral_params = 1 [ - (gogoproto.castrepeated) = "CollateralParams", - (gogoproto.nullable) = false - ]; - DebtParam debt_param = 2 [(gogoproto.nullable) = false]; - - cosmos.base.v1beta1.Coin global_debt_limit = 3 [(gogoproto.nullable) = false]; - string surplus_auction_threshold = 4 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - string surplus_auction_lot = 5 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - string debt_auction_threshold = 6 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - string debt_auction_lot = 7 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - bool circuit_breaker = 8; - - int64 liquidation_block_interval = 9; -} - -// DebtParam defines governance params for debt assets -message DebtParam { - string denom = 1; - string reference_asset = 2; - string conversion_factor = 3 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - string debt_floor = 4 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; -} - -// CollateralParam defines governance parameters for each collateral type within the cdp module -message CollateralParam { - string denom = 1; - string type = 2; - string liquidation_ratio = 3 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - cosmos.base.v1beta1.Coin debt_limit = 4 [(gogoproto.nullable) = false]; - string stability_fee = 5 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string auction_size = 6 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - string liquidation_penalty = 7 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string spot_market_id = 8 [(gogoproto.customname) = "SpotMarketID"]; - string liquidation_market_id = 9 [(gogoproto.customname) = "LiquidationMarketID"]; - string keeper_reward_percentage = 10 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string check_collateralization_index_count = 11 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - string conversion_factor = 12 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; -} - -// GenesisAccumulationTime defines the previous distribution time and its corresponding denom -message GenesisAccumulationTime { - string collateral_type = 1; - google.protobuf.Timestamp previous_accumulation_time = 2 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - string interest_factor = 3 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// GenesisTotalPrincipal defines the total principal and its corresponding collateral type -message GenesisTotalPrincipal { - string collateral_type = 1; - string total_principal = 2 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/cdp/v1beta1/query.proto b/proto/kava/cdp/v1beta1/query.proto deleted file mode 100644 index e950d998..00000000 --- a/proto/kava/cdp/v1beta1/query.proto +++ /dev/null @@ -1,160 +0,0 @@ -syntax = "proto3"; -package kava.cdp.v1beta1; - -import "cosmos/auth/v1beta1/auth.proto"; -import "cosmos/base/query/v1beta1/pagination.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "google/protobuf/timestamp.proto"; -import "kava/cdp/v1beta1/cdp.proto"; -import "kava/cdp/v1beta1/genesis.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/cdp/types"; - -// Query defines the gRPC querier service for cdp module -service Query { - // Params queries all parameters of the cdp module. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/cdp/v1beta1/params"; - } - - // Accounts queries the CDP module accounts. - rpc Accounts(QueryAccountsRequest) returns (QueryAccountsResponse) { - option (google.api.http).get = "/kava/cdp/v1beta1/accounts"; - } - - // TotalPrincipal queries the total principal of a given collateral type. - rpc TotalPrincipal(QueryTotalPrincipalRequest) returns (QueryTotalPrincipalResponse) { - option (google.api.http).get = "/kava/cdp/v1beta1/totalPrincipal"; - } - - // TotalCollateral queries the total collateral of a given collateral type. - rpc TotalCollateral(QueryTotalCollateralRequest) returns (QueryTotalCollateralResponse) { - option (google.api.http).get = "/kava/cdp/v1beta1/totalCollateral"; - } - - // Cdps queries all active CDPs. - rpc Cdps(QueryCdpsRequest) returns (QueryCdpsResponse) { - option (google.api.http).get = "/kava/cdp/v1beta1/cdps"; - } - - // Cdp queries a CDP with the input owner address and collateral type. - rpc Cdp(QueryCdpRequest) returns (QueryCdpResponse) { - option (google.api.http).get = "/kava/cdp/v1beta1/cdps/{owner}/{collateral_type}"; - } - - // Deposits queries deposits associated with the CDP owned by an address for a collateral type. - rpc Deposits(QueryDepositsRequest) returns (QueryDepositsResponse) { - option (google.api.http).get = "/kava/cdp/v1beta1/cdps/deposits/{owner}/{collateral_type}"; - } -} - -// QueryParamsRequest defines the request type for the Query/Params RPC method. -message QueryParamsRequest {} - -// QueryParamsResponse defines the response type for the Query/Params RPC method. -message QueryParamsResponse { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryAccountsRequest defines the request type for the Query/Accounts RPC method. -message QueryAccountsRequest {} - -// QueryAccountsResponse defines the response type for the Query/Accounts RPC method. -message QueryAccountsResponse { - repeated cosmos.auth.v1beta1.ModuleAccount accounts = 1 [(gogoproto.nullable) = false]; -} - -// QueryCdpRequest defines the request type for the Query/Cdp RPC method. -message QueryCdpRequest { - string collateral_type = 1; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; -} - -// QueryCdpResponse defines the response type for the Query/Cdp RPC method. -message QueryCdpResponse { - CDPResponse cdp = 1 [(gogoproto.nullable) = false]; -} - -// QueryCdpsRequest is the params for a filtered CDP query, the request type for the Query/Cdps RPC method. -message QueryCdpsRequest { - string collateral_type = 1; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - uint64 id = 3 [(gogoproto.customname) = "ID"]; - // sdk.Dec as a string - string ratio = 4; - - cosmos.base.query.v1beta1.PageRequest pagination = 5; -} - -// QueryCdpsResponse defines the response type for the Query/Cdps RPC method. -message QueryCdpsResponse { - repeated CDPResponse cdps = 1 [ - (gogoproto.castrepeated) = "CDPResponses", - (gogoproto.nullable) = false - ]; - - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryDepositsRequest defines the request type for the Query/Deposits RPC method. -message QueryDepositsRequest { - string collateral_type = 1; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; -} - -// QueryDepositsResponse defines the response type for the Query/Deposits RPC method. -message QueryDepositsResponse { - repeated Deposit deposits = 1 [ - (gogoproto.castrepeated) = "Deposits", - (gogoproto.nullable) = false - ]; -} - -// QueryTotalPrincipalRequest defines the request type for the Query/TotalPrincipal RPC method. -message QueryTotalPrincipalRequest { - string collateral_type = 1; -} - -// QueryTotalPrincipalResponse defines the response type for the Query/TotalPrincipal RPC method. -message QueryTotalPrincipalResponse { - repeated TotalPrincipal total_principal = 1 [ - (gogoproto.castrepeated) = "TotalPrincipals", - (gogoproto.nullable) = false - ]; -} - -// QueryTotalCollateralRequest defines the request type for the Query/TotalCollateral RPC method. -message QueryTotalCollateralRequest { - string collateral_type = 1; -} - -// QueryTotalCollateralResponse defines the response type for the Query/TotalCollateral RPC method. -message QueryTotalCollateralResponse { - repeated TotalCollateral total_collateral = 1 [ - (gogoproto.castrepeated) = "TotalCollaterals", - (gogoproto.nullable) = false - ]; -} - -// CDPResponse defines the state of a single collateralized debt position. -message CDPResponse { - uint64 id = 1 [(gogoproto.customname) = "ID"]; - string owner = 2; - string type = 3; - cosmos.base.v1beta1.Coin collateral = 4 [(gogoproto.nullable) = false]; - cosmos.base.v1beta1.Coin principal = 5 [(gogoproto.nullable) = false]; - cosmos.base.v1beta1.Coin accumulated_fees = 6 [(gogoproto.nullable) = false]; - google.protobuf.Timestamp fees_updated = 7 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - string interest_factor = 8; - cosmos.base.v1beta1.Coin collateral_value = 9 [(gogoproto.nullable) = false]; - string collateralization_ratio = 10; -} diff --git a/proto/kava/cdp/v1beta1/tx.proto b/proto/kava/cdp/v1beta1/tx.proto deleted file mode 100644 index 8e1a5628..00000000 --- a/proto/kava/cdp/v1beta1/tx.proto +++ /dev/null @@ -1,91 +0,0 @@ -syntax = "proto3"; -package kava.cdp.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/cdp/types"; - -// Msg defines the cdp Msg service. -service Msg { - // CreateCDP defines a method to create a new CDP. - rpc CreateCDP(MsgCreateCDP) returns (MsgCreateCDPResponse); - // Deposit defines a method to deposit to a CDP. - rpc Deposit(MsgDeposit) returns (MsgDepositResponse); - // Withdraw defines a method to withdraw collateral from a CDP. - rpc Withdraw(MsgWithdraw) returns (MsgWithdrawResponse); - // DrawDebt defines a method to draw debt from a CDP. - rpc DrawDebt(MsgDrawDebt) returns (MsgDrawDebtResponse); - // RepayDebt defines a method to repay debt from a CDP. - rpc RepayDebt(MsgRepayDebt) returns (MsgRepayDebtResponse); - // Liquidate defines a method to attempt to liquidate a CDP whos - // collateralization ratio is under its liquidation ratio. - rpc Liquidate(MsgLiquidate) returns (MsgLiquidateResponse); -} - -// MsgCreateCDP defines a message to create a new CDP. -message MsgCreateCDP { - string sender = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - cosmos.base.v1beta1.Coin collateral = 2 [(gogoproto.nullable) = false]; - cosmos.base.v1beta1.Coin principal = 3 [(gogoproto.nullable) = false]; - string collateral_type = 4; -} - -// MsgCreateCDPResponse defines the Msg/CreateCDP response type. -message MsgCreateCDPResponse { - uint64 cdp_id = 1 [(gogoproto.customname) = "CdpID"]; -} - -// MsgDeposit defines a message to deposit to a CDP. -message MsgDeposit { - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - cosmos.base.v1beta1.Coin collateral = 3 [(gogoproto.nullable) = false]; - string collateral_type = 4; -} - -// MsgDepositResponse defines the Msg/Deposit response type. -message MsgDepositResponse {} - -// MsgWithdraw defines a message to withdraw collateral from a CDP. -message MsgWithdraw { - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - cosmos.base.v1beta1.Coin collateral = 3 [(gogoproto.nullable) = false]; - string collateral_type = 4; -} - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -message MsgWithdrawResponse {} - -// MsgDrawDebt defines a message to draw debt from a CDP. -message MsgDrawDebt { - string sender = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string collateral_type = 2; - cosmos.base.v1beta1.Coin principal = 3 [(gogoproto.nullable) = false]; -} - -// MsgDrawDebtResponse defines the Msg/DrawDebt response type. -message MsgDrawDebtResponse {} - -// MsgRepayDebt defines a message to repay debt from a CDP. -message MsgRepayDebt { - string sender = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string collateral_type = 2; - cosmos.base.v1beta1.Coin payment = 3 [(gogoproto.nullable) = false]; -} - -// MsgRepayDebtResponse defines the Msg/RepayDebt response type. -message MsgRepayDebtResponse {} - -// MsgLiquidate defines a message to attempt to liquidate a CDP whos -// collateralization ratio is under its liquidation ratio. -message MsgLiquidate { - string keeper = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string borrower = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string collateral_type = 3; -} - -// MsgLiquidateResponse defines the Msg/Liquidate response type. -message MsgLiquidateResponse {} diff --git a/proto/kava/community/v1beta1/genesis.proto b/proto/kava/community/v1beta1/genesis.proto deleted file mode 100644 index c772446f..00000000 --- a/proto/kava/community/v1beta1/genesis.proto +++ /dev/null @@ -1,18 +0,0 @@ -syntax = "proto3"; -package kava.community.v1beta1; - -import "gogoproto/gogo.proto"; -import "kava/community/v1beta1/params.proto"; -import "kava/community/v1beta1/staking.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/community/types"; - -// GenesisState defines the community module's genesis state. -message GenesisState { - // params defines all the parameters related to commmunity - Params params = 1 [(gogoproto.nullable) = false]; - - // StakingRewardsState stores the internal staking reward data required to - // track staking rewards across blocks - StakingRewardsState staking_rewards_state = 2 [(gogoproto.nullable) = false]; -} diff --git a/proto/kava/community/v1beta1/params.proto b/proto/kava/community/v1beta1/params.proto deleted file mode 100644 index a594c773..00000000 --- a/proto/kava/community/v1beta1/params.proto +++ /dev/null @@ -1,35 +0,0 @@ -syntax = "proto3"; -package kava.community.v1beta1; - -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/community/types"; - -// Params defines the parameters of the community module. -message Params { - option (gogoproto.equal) = true; - - // upgrade_time_disable_inflation is the time at which to disable mint and kavadist module inflation. - // If set to 0, inflation will be disabled from block 1. - google.protobuf.Timestamp upgrade_time_disable_inflation = 1 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - - // staking_rewards_per_second is the amount paid out to delegators each block from the community account - string staking_rewards_per_second = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", - (gogoproto.nullable) = false - ]; - - // upgrade_time_set_staking_rewards_per_second is the initial staking_rewards_per_second to set - // and use when the disable inflation time is reached - string upgrade_time_set_staking_rewards_per_second = 3 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/community/v1beta1/proposal.proto b/proto/kava/community/v1beta1/proposal.proto deleted file mode 100644 index cb6cd342..00000000 --- a/proto/kava/community/v1beta1/proposal.proto +++ /dev/null @@ -1,57 +0,0 @@ -syntax = "proto3"; -package kava.community.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/community/types"; - -// CommunityPoolLendDepositProposal deposits from the community pool into lend -message CommunityPoolLendDepositProposal { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - repeated cosmos.base.v1beta1.Coin amount = 3 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// CommunityPoolLendWithdrawProposal withdraws a lend position back to the community pool -message CommunityPoolLendWithdrawProposal { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - repeated cosmos.base.v1beta1.Coin amount = 3 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// CommunityCDPRepayDebtProposal repays a cdp debt position owned by the community module -// This proposal exists primarily to allow committees to repay community module cdp debts. -message CommunityCDPRepayDebtProposal { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - string collateral_type = 3; - cosmos.base.v1beta1.Coin payment = 4 [(gogoproto.nullable) = false]; -} - -// CommunityCDPWithdrawCollateralProposal withdraws cdp collateral owned by the community module -// This proposal exists primarily to allow committees to withdraw community module cdp collateral. -message CommunityCDPWithdrawCollateralProposal { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - string collateral_type = 3; - cosmos.base.v1beta1.Coin collateral = 4 [(gogoproto.nullable) = false]; -} diff --git a/proto/kava/community/v1beta1/query.proto b/proto/kava/community/v1beta1/query.proto deleted file mode 100644 index c3f920ef..00000000 --- a/proto/kava/community/v1beta1/query.proto +++ /dev/null @@ -1,81 +0,0 @@ -syntax = "proto3"; -package kava.community.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "kava/community/v1beta1/params.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/community/types"; - -// Query defines the gRPC querier service for x/community. -service Query { - // Params queires the module params. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/community/v1beta1/params"; - } - - // Balance queries the balance of all coins of x/community module. - rpc Balance(QueryBalanceRequest) returns (QueryBalanceResponse) { - option (google.api.http).get = "/kava/community/v1beta1/balance"; - } - - // TotalBalance queries the balance of all coins, including x/distribution, - // x/community, and supplied balances. - rpc TotalBalance(QueryTotalBalanceRequest) returns (QueryTotalBalanceResponse) { - option (google.api.http).get = "/kava/community/v1beta1/total_balance"; - } - - // AnnualizedRewards calculates and returns the current annualized reward percentages, - // like staking rewards, for the chain. - rpc AnnualizedRewards(QueryAnnualizedRewardsRequest) returns (QueryAnnualizedRewardsResponse) { - option (google.api.http).get = "/kava/community/v1beta1/annualized_rewards"; - } -} - -// QueryParams defines the request type for querying x/community params. -message QueryParamsRequest {} - -// QueryParamsResponse defines the response type for querying x/community params. -message QueryParamsResponse { - // params represents the community module parameters - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryBalanceRequest defines the request type for querying x/community balance. -message QueryBalanceRequest {} - -// QueryBalanceResponse defines the response type for querying x/community balance. -message QueryBalanceResponse { - repeated cosmos.base.v1beta1.Coin coins = 1 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// QueryTotalBalanceRequest defines the request type for querying total community pool balance. -message QueryTotalBalanceRequest {} - -// QueryTotalBalanceResponse defines the response type for querying total -// community pool balance. This matches the x/distribution CommunityPool query response. -message QueryTotalBalanceResponse { - // pool defines community pool's coins. - repeated cosmos.base.v1beta1.DecCoin pool = 1 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.DecCoins", - (gogoproto.nullable) = false - ]; -} - -// QueryAnnualizedRewardsRequest defines the request type for querying the annualized rewards. -message QueryAnnualizedRewardsRequest {} - -// QueryAnnualizedRewardsResponse defines the response type for querying the annualized rewards. -message QueryAnnualizedRewardsResponse { - // staking_rewards is the calculated annualized staking rewards percentage rate - string staking_rewards = 1 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/community/v1beta1/staking.proto b/proto/kava/community/v1beta1/staking.proto deleted file mode 100644 index 67a9b0fa..00000000 --- a/proto/kava/community/v1beta1/staking.proto +++ /dev/null @@ -1,26 +0,0 @@ -syntax = "proto3"; -package kava.community.v1beta1; - -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/community/types"; - -// StakingRewardsState represents the state of staking reward accumulation between blocks. -message StakingRewardsState { - // last_accumulation_time represents the last block time which rewards where calculated and distributed. - // This may be zero to signal accumulation should start on the next interval. - google.protobuf.Timestamp last_accumulation_time = 1 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - - // accumulated_truncation_error represents the sum of previous errors due to truncation on payout - // This value will always be on the interval [0, 1). - string last_truncation_error = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/community/v1beta1/tx.proto b/proto/kava/community/v1beta1/tx.proto deleted file mode 100644 index 486f66a0..00000000 --- a/proto/kava/community/v1beta1/tx.proto +++ /dev/null @@ -1,47 +0,0 @@ -syntax = "proto3"; -package kava.community.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "kava/community/v1beta1/params.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/community/types"; -option (gogoproto.equal_all) = true; - -// Msg defines the community Msg service. -service Msg { - // FundCommunityPool defines a method to allow an account to directly fund the community module account. - rpc FundCommunityPool(MsgFundCommunityPool) returns (MsgFundCommunityPoolResponse); - - // UpdateParams defines a method to allow an account to update the community module parameters. - rpc UpdateParams(MsgUpdateParams) returns (MsgUpdateParamsResponse); -} - -// MsgFundCommunityPool allows an account to directly fund the community module account. -message MsgFundCommunityPool { - option (gogoproto.goproto_getters) = false; - - repeated cosmos.base.v1beta1.Coin amount = 1 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; - string depositor = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; -} - -// MsgFundCommunityPoolResponse defines the Msg/FundCommunityPool response type. -message MsgFundCommunityPoolResponse {} - -// MsgUpdateParams allows an account to update the community module parameters. -message MsgUpdateParams { - option (gogoproto.goproto_getters) = false; - - // authority is the address that controls the module (defaults to x/gov unless overwritten). - string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - // params defines the x/community parameters to update. - Params params = 2 [(gogoproto.nullable) = false]; -} - -// MsgUpdateParamsResponse defines the Msg/UpdateParams response type. -message MsgUpdateParamsResponse {} diff --git a/proto/kava/earn/v1beta1/genesis.proto b/proto/kava/earn/v1beta1/genesis.proto deleted file mode 100644 index 177fe7ef..00000000 --- a/proto/kava/earn/v1beta1/genesis.proto +++ /dev/null @@ -1,24 +0,0 @@ -syntax = "proto3"; -package kava.earn.v1beta1; - -import "gogoproto/gogo.proto"; -import "kava/earn/v1beta1/params.proto"; -import "kava/earn/v1beta1/vault.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/earn/types"; - -// GenesisState defines the earn module's genesis state. -message GenesisState { - // params defines all the parameters related to earn - Params params = 1 [(gogoproto.nullable) = false]; - // vault_records defines the available vaults - repeated VaultRecord vault_records = 2 [ - (gogoproto.castrepeated) = "VaultRecords", - (gogoproto.nullable) = false - ]; - // share_records defines the owned shares of each vault - repeated VaultShareRecord vault_share_records = 3 [ - (gogoproto.castrepeated) = "VaultShareRecords", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/earn/v1beta1/params.proto b/proto/kava/earn/v1beta1/params.proto deleted file mode 100644 index 02da3020..00000000 --- a/proto/kava/earn/v1beta1/params.proto +++ /dev/null @@ -1,15 +0,0 @@ -syntax = "proto3"; -package kava.earn.v1beta1; - -import "gogoproto/gogo.proto"; -import "kava/earn/v1beta1/vault.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/earn/types"; - -// Params defines the parameters of the earn module. -message Params { - repeated AllowedVault allowed_vaults = 1 [ - (gogoproto.castrepeated) = "AllowedVaults", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/earn/v1beta1/proposal.proto b/proto/kava/earn/v1beta1/proposal.proto deleted file mode 100644 index d4bc05cd..00000000 --- a/proto/kava/earn/v1beta1/proposal.proto +++ /dev/null @@ -1,55 +0,0 @@ -syntax = "proto3"; -package kava.earn.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/earn/types"; - -// CommunityPoolDepositProposal deposits from the community pool into an earn vault -message CommunityPoolDepositProposal { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// CommunityPoolDepositProposalJSON defines a CommunityPoolDepositProposal with a deposit -message CommunityPoolDepositProposalJSON { - option (gogoproto.goproto_stringer) = true; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; - repeated cosmos.base.v1beta1.Coin deposit = 4 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// CommunityPoolWithdrawProposal withdraws from an earn vault back to community pool -message CommunityPoolWithdrawProposal { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// CommunityPoolWithdrawProposalJSON defines a CommunityPoolWithdrawProposal with a deposit -message CommunityPoolWithdrawProposalJSON { - option (gogoproto.goproto_stringer) = true; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; - repeated cosmos.base.v1beta1.Coin deposit = 4 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} diff --git a/proto/kava/earn/v1beta1/query.proto b/proto/kava/earn/v1beta1/query.proto deleted file mode 100644 index a49302a0..00000000 --- a/proto/kava/earn/v1beta1/query.proto +++ /dev/null @@ -1,160 +0,0 @@ -syntax = "proto3"; -package kava.earn.v1beta1; - -import "cosmos/base/query/v1beta1/pagination.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "kava/earn/v1beta1/params.proto"; -import "kava/earn/v1beta1/strategy.proto"; -import "kava/earn/v1beta1/vault.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/earn/types"; -option (gogoproto.goproto_getters_all) = false; - -// Query defines the gRPC querier service for earn module -service Query { - // Params queries all parameters of the earn module. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/earn/v1beta1/params"; - } - - // Vaults queries all vaults - rpc Vaults(QueryVaultsRequest) returns (QueryVaultsResponse) { - option (google.api.http).get = "/kava/earn/v1beta1/vaults"; - } - - // Vault queries a single vault based on the vault denom - rpc Vault(QueryVaultRequest) returns (QueryVaultResponse) { - option (google.api.http).get = "/kava/earn/v1beta1/vaults/{denom=**}"; - } - - // Deposits queries deposit details based on depositor address and vault - rpc Deposits(QueryDepositsRequest) returns (QueryDepositsResponse) { - option (google.api.http).get = "/kava/earn/v1beta1/deposits"; - } - - // TotalSupply returns the total sum of all coins currently locked into the earn module. - rpc TotalSupply(QueryTotalSupplyRequest) returns (QueryTotalSupplyResponse) { - option (google.api.http).get = "/kava/earn/v1beta1/total_supply"; - } -} - -// QueryParamsRequest defines the request type for querying x/earn parameters. -message QueryParamsRequest {} - -// QueryParamsResponse defines the response type for querying x/earn parameters. -message QueryParamsResponse { - // params represents the earn module parameters - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryVaultsRequest is the request type for the Query/Vaults RPC method. -message QueryVaultsRequest {} - -// QueryVaultsResponse is the response type for the Query/Vaults RPC method. -message QueryVaultsResponse { - // vaults represents the earn module vaults - repeated VaultResponse vaults = 1 [(gogoproto.nullable) = false]; -} - -// QueryVaultRequest is the request type for the Query/Vault RPC method. -message QueryVaultRequest { - // vault filters vault by denom - string denom = 1; -} - -// QueryVaultResponse is the response type for the Query/Vault RPC method. -message QueryVaultResponse { - // vault represents the queried earn module vault - VaultResponse vault = 1 [(gogoproto.nullable) = false]; -} - -// VaultResponse is the response type for a vault. -message VaultResponse { - // denom represents the denom of the vault - string denom = 1; - - // VaultStrategy is the strategy used for this vault. - repeated StrategyType strategies = 2 [(gogoproto.castrepeated) = "StrategyTypes"]; - - // IsPrivateVault is true if the vault only allows depositors contained in - // AllowedDepositors. - bool is_private_vault = 3; - - // AllowedDepositors is a list of addresses that are allowed to deposit to - // this vault if IsPrivateVault is true. Addresses not contained in this list - // are not allowed to deposit into this vault. If IsPrivateVault is false, - // this should be empty and ignored. - repeated string allowed_depositors = 4 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - // TotalShares is the total amount of shares issued to depositors. - string total_shares = 5; - - // TotalValue is the total value of denom coins supplied to the vault if the - // vault were to be liquidated. - string total_value = 6 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; -} - -// QueryDepositsRequest is the request type for the Query/Deposits RPC method. -message QueryDepositsRequest { - // depositor optionally filters deposits by depositor - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - // denom optionally filters deposits by vault denom - string denom = 2; - - // respond with vault value in ukava for bkava vaults - bool value_in_staked_tokens = 3; - - // pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 4; -} - -// QueryDepositsResponse is the response type for the Query/Deposits RPC method. -message QueryDepositsResponse { - // deposits returns the deposits matching the requested parameters - repeated DepositResponse deposits = 1 [(gogoproto.nullable) = false]; - - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// DepositResponse defines a deposit query response type. -message DepositResponse { - // depositor represents the owner of the deposit. - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - // Shares represent the issued shares from their corresponding vaults. - repeated VaultShare shares = 2 [ - (gogoproto.castrepeated) = "VaultShares", - (gogoproto.nullable) = false - ]; - - // Value represents the total accumulated value of denom coins supplied to - // vaults. This may be greater than or equal to amount_supplied depending on - // the strategy. - repeated cosmos.base.v1beta1.Coin value = 3 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// QueryTotalSupplyRequest defines the request type for Query/TotalSupply method. -message QueryTotalSupplyRequest {} - -// TotalSupplyResponse defines the response type for the Query/TotalSupply method. -message QueryTotalSupplyResponse { - // Height is the block height at which these totals apply - int64 height = 1; - // Result is a list of coins supplied to earn - repeated cosmos.base.v1beta1.Coin result = 2 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} diff --git a/proto/kava/earn/v1beta1/strategy.proto b/proto/kava/earn/v1beta1/strategy.proto deleted file mode 100644 index e41d3650..00000000 --- a/proto/kava/earn/v1beta1/strategy.proto +++ /dev/null @@ -1,20 +0,0 @@ -syntax = "proto3"; -package kava.earn.v1beta1; - -import "gogoproto/gogo.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/earn/types"; - -// StrategyType is the type of strategy that a vault uses to optimize yields. -enum StrategyType { - option (gogoproto.goproto_enum_prefix) = false; - - // STRATEGY_TYPE_UNSPECIFIED represents an unspecified or invalid strategy type. - STRATEGY_TYPE_UNSPECIFIED = 0; - // STRATEGY_TYPE_HARD represents the strategy that deposits assets in the Hard - // module. - STRATEGY_TYPE_HARD = 1; - // STRATEGY_TYPE_SAVINGS represents the strategy that deposits assets in the - // Savings module. - STRATEGY_TYPE_SAVINGS = 2; -} diff --git a/proto/kava/earn/v1beta1/tx.proto b/proto/kava/earn/v1beta1/tx.proto deleted file mode 100644 index 1e8539e0..00000000 --- a/proto/kava/earn/v1beta1/tx.proto +++ /dev/null @@ -1,57 +0,0 @@ -syntax = "proto3"; -package kava.earn.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "kava/earn/v1beta1/strategy.proto"; -import "kava/earn/v1beta1/vault.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/earn/types"; - -// Msg defines the earn Msg service. -service Msg { - // Deposit defines a method for depositing assets into a vault - rpc Deposit(MsgDeposit) returns (MsgDepositResponse); - // Withdraw defines a method for withdrawing assets into a vault - rpc Withdraw(MsgWithdraw) returns (MsgWithdrawResponse); -} - -// MsgDeposit represents a message for depositing assedts into a vault -message MsgDeposit { - option (gogoproto.goproto_getters) = false; - - // depositor represents the address to deposit funds from - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // Amount represents the token to deposit. The vault corresponds to the denom - // of the amount coin. - cosmos.base.v1beta1.Coin amount = 2 [(gogoproto.nullable) = false]; - - // Strategy is the vault strategy to use. - StrategyType strategy = 3; -} - -// MsgDepositResponse defines the Msg/Deposit response type. -message MsgDepositResponse { - VaultShare shares = 1 [(gogoproto.nullable) = false]; -} - -// MsgWithdraw represents a message for withdrawing liquidity from a vault -message MsgWithdraw { - option (gogoproto.goproto_getters) = false; - - // from represents the address we are withdrawing for - string from = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - // Amount represents the token to withdraw. The vault corresponds to the denom - // of the amount coin. - cosmos.base.v1beta1.Coin amount = 2 [(gogoproto.nullable) = false]; - - // Strategy is the vault strategy to use. - StrategyType strategy = 3; -} - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -message MsgWithdrawResponse { - VaultShare shares = 1 [(gogoproto.nullable) = false]; -} diff --git a/proto/kava/earn/v1beta1/vault.proto b/proto/kava/earn/v1beta1/vault.proto deleted file mode 100644 index 6660c112..00000000 --- a/proto/kava/earn/v1beta1/vault.proto +++ /dev/null @@ -1,63 +0,0 @@ -syntax = "proto3"; -package kava.earn.v1beta1; - -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "kava/earn/v1beta1/strategy.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/earn/types"; - -// AllowedVault is a vault that is allowed to be created. These can be -// modified via parameter governance. -message AllowedVault { - // Denom is the only supported denomination of the vault for deposits and withdrawals. - string denom = 1; - - // VaultStrategy is the strategy used for this vault. - repeated StrategyType strategies = 2 [(gogoproto.castrepeated) = "StrategyTypes"]; - - // IsPrivateVault is true if the vault only allows depositors contained in - // AllowedDepositors. - bool is_private_vault = 3; - - // AllowedDepositors is a list of addresses that are allowed to deposit to - // this vault if IsPrivateVault is true. Addresses not contained in this list - // are not allowed to deposit into this vault. If IsPrivateVault is false, - // this should be empty and ignored. - repeated bytes allowed_depositors = 4 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; -} - -// VaultRecord is the state of a vault. -message VaultRecord { - // TotalShares is the total distributed number of shares in the vault. - VaultShare total_shares = 1 [(gogoproto.nullable) = false]; -} - -// VaultShareRecord defines the vault shares owned by a depositor. -message VaultShareRecord { - // Depositor represents the owner of the shares - bytes depositor = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - // Shares represent the vault shares owned by the depositor. - repeated VaultShare shares = 2 [ - (gogoproto.castrepeated) = "VaultShares", - (gogoproto.nullable) = false - ]; -} - -// VaultShare defines shares of a vault owned by a depositor. -message VaultShare { - option (gogoproto.goproto_stringer) = false; - - string denom = 1; - string amount = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/hard/v1beta1/genesis.proto b/proto/kava/hard/v1beta1/genesis.proto deleted file mode 100644 index b19bfb70..00000000 --- a/proto/kava/hard/v1beta1/genesis.proto +++ /dev/null @@ -1,58 +0,0 @@ -syntax = "proto3"; -package kava.hard.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; -import "kava/hard/v1beta1/hard.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/hard/types"; - -// GenesisState defines the hard module's genesis state. -message GenesisState { - Params params = 1 [(gogoproto.nullable) = false]; - repeated GenesisAccumulationTime previous_accumulation_times = 2 [ - (gogoproto.castrepeated) = "GenesisAccumulationTimes", - (gogoproto.nullable) = false - ]; - repeated Deposit deposits = 3 [ - (gogoproto.castrepeated) = "Deposits", - (gogoproto.nullable) = false - ]; - repeated Borrow borrows = 4 [ - (gogoproto.castrepeated) = "Borrows", - (gogoproto.nullable) = false - ]; - repeated cosmos.base.v1beta1.Coin total_supplied = 5 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; - repeated cosmos.base.v1beta1.Coin total_borrowed = 6 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; - repeated cosmos.base.v1beta1.Coin total_reserves = 7 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// GenesisAccumulationTime stores the previous distribution time and its corresponding denom. -message GenesisAccumulationTime { - string collateral_type = 1; - google.protobuf.Timestamp previous_accumulation_time = 2 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - string supply_interest_factor = 3 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string borrow_interest_factor = 4 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/hard/v1beta1/hard.proto b/proto/kava/hard/v1beta1/hard.proto deleted file mode 100644 index 6bcd7ada..00000000 --- a/proto/kava/hard/v1beta1/hard.proto +++ /dev/null @@ -1,146 +0,0 @@ -syntax = "proto3"; -package kava.hard.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/hard/types"; -option (gogoproto.goproto_getters_all) = false; - -// Params defines the parameters for the hard module. -message Params { - repeated MoneyMarket money_markets = 1 [ - (gogoproto.castrepeated) = "MoneyMarkets", - (gogoproto.nullable) = false - ]; - string minimum_borrow_usd_value = 2 [ - (gogoproto.customname) = "MinimumBorrowUSDValue", - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// MoneyMarket is a money market for an individual asset. -message MoneyMarket { - string denom = 1; - BorrowLimit borrow_limit = 2 [(gogoproto.nullable) = false]; - string spot_market_id = 3 [(gogoproto.customname) = "SpotMarketID"]; - string conversion_factor = 4 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - InterestRateModel interest_rate_model = 5 [(gogoproto.nullable) = false]; - string reserve_factor = 6 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string keeper_reward_percentage = 7 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// BorrowLimit enforces restrictions on a money market. -message BorrowLimit { - bool has_max_limit = 1 [(gogoproto.jsontag) = "has_max_limit"]; - string maximum_limit = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string loan_to_value = 3 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// InterestRateModel contains information about an asset's interest rate. -message InterestRateModel { - string base_rate_apy = 1 [ - (gogoproto.customname) = "BaseRateAPY", - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string base_multiplier = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string kink = 3 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string jump_multiplier = 4 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// Deposit defines an amount of coins deposited into a hard module account. -message Deposit { - string depositor = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; - repeated SupplyInterestFactor index = 3 [ - (gogoproto.castrepeated) = "SupplyInterestFactors", - (gogoproto.nullable) = false - ]; -} - -// Borrow defines an amount of coins borrowed from a hard module account. -message Borrow { - string borrower = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; - repeated BorrowInterestFactor index = 3 [ - (gogoproto.castrepeated) = "BorrowInterestFactors", - (gogoproto.nullable) = false - ]; -} - -// SupplyInterestFactor defines an individual borrow interest factor. -message SupplyInterestFactor { - string denom = 1; - string value = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// BorrowInterestFactor defines an individual borrow interest factor. -message BorrowInterestFactor { - string denom = 1; - string value = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// CoinsProto defines a Protobuf wrapper around a Coins slice -message CoinsProto { - repeated cosmos.base.v1beta1.Coin coins = 1 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/hard/v1beta1/query.proto b/proto/kava/hard/v1beta1/query.proto deleted file mode 100644 index f4ed0ff6..00000000 --- a/proto/kava/hard/v1beta1/query.proto +++ /dev/null @@ -1,281 +0,0 @@ -syntax = "proto3"; -package kava.hard.v1beta1; - -import "cosmos/auth/v1beta1/auth.proto"; -import "cosmos/base/query/v1beta1/pagination.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "kava/hard/v1beta1/hard.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/hard/types"; - -// Query defines the gRPC querier service for bep3 module. -service Query { - // Params queries module params. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/params"; - } - - // Accounts queries module accounts. - rpc Accounts(QueryAccountsRequest) returns (QueryAccountsResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/accounts"; - } - - // Deposits queries hard deposits. - rpc Deposits(QueryDepositsRequest) returns (QueryDepositsResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/deposits"; - } - - // UnsyncedDeposits queries unsynced deposits. - rpc UnsyncedDeposits(QueryUnsyncedDepositsRequest) returns (QueryUnsyncedDepositsResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/unsynced-deposits"; - } - - // TotalDeposited queries total coins deposited to hard liquidity pools. - rpc TotalDeposited(QueryTotalDepositedRequest) returns (QueryTotalDepositedResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/total-deposited"; - } - - // Borrows queries hard borrows. - rpc Borrows(QueryBorrowsRequest) returns (QueryBorrowsResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/borrows"; - } - - // UnsyncedBorrows queries unsynced borrows. - rpc UnsyncedBorrows(QueryUnsyncedBorrowsRequest) returns (QueryUnsyncedBorrowsResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/unsynced-borrows"; - } - - // TotalBorrowed queries total coins borrowed from hard liquidity pools. - rpc TotalBorrowed(QueryTotalBorrowedRequest) returns (QueryTotalBorrowedResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/total-borrowed"; - } - - // InterestRate queries the hard module interest rates. - rpc InterestRate(QueryInterestRateRequest) returns (QueryInterestRateResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/interest-rate"; - } - - // Reserves queries total hard reserve coins. - rpc Reserves(QueryReservesRequest) returns (QueryReservesResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/reserves"; - } - - // InterestFactors queries hard module interest factors. - rpc InterestFactors(QueryInterestFactorsRequest) returns (QueryInterestFactorsResponse) { - option (google.api.http).get = "/kava/hard/v1beta1/interest-factors"; - } -} - -// QueryParamsRequest is the request type for the Query/Params RPC method. -message QueryParamsRequest {} - -// QueryParamsResponse is the response type for the Query/Params RPC method. -message QueryParamsResponse { - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryAccountsRequest is the request type for the Query/Accounts RPC method. -message QueryAccountsRequest {} - -// QueryAccountsResponse is the response type for the Query/Accounts RPC method. -message QueryAccountsResponse { - repeated cosmos.auth.v1beta1.ModuleAccount accounts = 1 [(gogoproto.nullable) = false]; -} - -// QueryDepositsRequest is the request type for the Query/Deposits RPC method. -message QueryDepositsRequest { - string denom = 1; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - cosmos.base.query.v1beta1.PageRequest pagination = 3; -} - -// QueryDepositsResponse is the response type for the Query/Deposits RPC method. -message QueryDepositsResponse { - repeated DepositResponse deposits = 1 [ - (gogoproto.castrepeated) = "DepositResponses", - (gogoproto.nullable) = false - ]; - - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryUnsyncedDepositsRequest is the request type for the Query/UnsyncedDeposits RPC method. -message QueryUnsyncedDepositsRequest { - string denom = 1; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - cosmos.base.query.v1beta1.PageRequest pagination = 3; -} - -// QueryUnsyncedDepositsResponse is the response type for the Query/UnsyncedDeposits RPC method. -message QueryUnsyncedDepositsResponse { - repeated DepositResponse deposits = 1 [ - (gogoproto.castrepeated) = "DepositResponses", - (gogoproto.nullable) = false - ]; - - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryTotalDepositedRequest is the request type for the Query/TotalDeposited RPC method. -message QueryTotalDepositedRequest { - string denom = 1; -} - -// QueryTotalDepositedResponse is the response type for the Query/TotalDeposited RPC method. -message QueryTotalDepositedResponse { - repeated cosmos.base.v1beta1.Coin supplied_coins = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// QueryBorrowsRequest is the request type for the Query/Borrows RPC method. -message QueryBorrowsRequest { - string denom = 1; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - cosmos.base.query.v1beta1.PageRequest pagination = 3; -} - -// QueryBorrowsResponse is the response type for the Query/Borrows RPC method. -message QueryBorrowsResponse { - repeated BorrowResponse borrows = 1 [ - (gogoproto.castrepeated) = "BorrowResponses", - (gogoproto.nullable) = false - ]; - - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryUnsyncedBorrowsRequest is the request type for the Query/UnsyncedBorrows RPC method. -message QueryUnsyncedBorrowsRequest { - string denom = 1; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - cosmos.base.query.v1beta1.PageRequest pagination = 3; -} - -// QueryUnsyncedBorrowsResponse is the response type for the Query/UnsyncedBorrows RPC method. -message QueryUnsyncedBorrowsResponse { - repeated BorrowResponse borrows = 1 [ - (gogoproto.castrepeated) = "BorrowResponses", - (gogoproto.nullable) = false - ]; - - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryTotalBorrowedRequest is the request type for the Query/TotalBorrowed RPC method. -message QueryTotalBorrowedRequest { - string denom = 1; -} - -// QueryTotalBorrowedResponse is the response type for the Query/TotalBorrowed RPC method. -message QueryTotalBorrowedResponse { - repeated cosmos.base.v1beta1.Coin borrowed_coins = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// QueryInterestRateRequest is the request type for the Query/InterestRate RPC method. -message QueryInterestRateRequest { - string denom = 1; -} - -// QueryInterestRateResponse is the response type for the Query/InterestRate RPC method. -message QueryInterestRateResponse { - repeated MoneyMarketInterestRate interest_rates = 1 [ - (gogoproto.castrepeated) = "MoneyMarketInterestRates", - (gogoproto.nullable) = false - ]; -} - -// QueryReservesRequest is the request type for the Query/Reserves RPC method. -message QueryReservesRequest { - string denom = 1; -} - -// QueryReservesResponse is the response type for the Query/Reserves RPC method. -message QueryReservesResponse { - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// QueryInterestFactorsRequest is the request type for the Query/InterestFactors RPC method. -message QueryInterestFactorsRequest { - string denom = 1; -} - -// QueryInterestFactorsResponse is the response type for the Query/InterestFactors RPC method. -message QueryInterestFactorsResponse { - repeated InterestFactor interest_factors = 1 [ - (gogoproto.castrepeated) = "InterestFactors", - (gogoproto.nullable) = false - ]; -} - -// DepositResponse defines an amount of coins deposited into a hard module account. -message DepositResponse { - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; - repeated SupplyInterestFactorResponse index = 3 [ - (gogoproto.castrepeated) = "SupplyInterestFactorResponses", - (gogoproto.nullable) = false - ]; -} - -// SupplyInterestFactorResponse defines an individual borrow interest factor. -message SupplyInterestFactorResponse { - string denom = 1; - // sdk.Dec as string - string value = 2; -} - -// BorrowResponse defines an amount of coins borrowed from a hard module account. -message BorrowResponse { - string borrower = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; - repeated BorrowInterestFactorResponse index = 3 [ - (gogoproto.castrepeated) = "BorrowInterestFactorResponses", - (gogoproto.nullable) = false - ]; -} - -// BorrowInterestFactorResponse defines an individual borrow interest factor. -message BorrowInterestFactorResponse { - string denom = 1; - // sdk.Dec as string - string value = 2; -} - -// MoneyMarketInterestRate is a unique type returned by interest rate queries -message MoneyMarketInterestRate { - string denom = 1; - // sdk.Dec as String - string supply_interest_rate = 2; - // sdk.Dec as String - string borrow_interest_rate = 3; -} - -// InterestFactor is a unique type returned by interest factor queries -message InterestFactor { - string denom = 1; - // sdk.Dec as String - string borrow_interest_factor = 2; - // sdk.Dec as String - string supply_interest_factor = 3; -} diff --git a/proto/kava/hard/v1beta1/tx.proto b/proto/kava/hard/v1beta1/tx.proto deleted file mode 100644 index c3b032d7..00000000 --- a/proto/kava/hard/v1beta1/tx.proto +++ /dev/null @@ -1,80 +0,0 @@ -syntax = "proto3"; -package kava.hard.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/hard/types"; - -// Msg defines the hard Msg service. -service Msg { - // Deposit defines a method for depositing funds to hard liquidity pool. - rpc Deposit(MsgDeposit) returns (MsgDepositResponse); - // Withdraw defines a method for withdrawing funds from hard liquidity pool. - rpc Withdraw(MsgWithdraw) returns (MsgWithdrawResponse); - // Borrow defines a method for borrowing funds from hard liquidity pool. - rpc Borrow(MsgBorrow) returns (MsgBorrowResponse); - // Repay defines a method for repaying funds borrowed from hard liquidity pool. - rpc Repay(MsgRepay) returns (MsgRepayResponse); - // Liquidate defines a method for attempting to liquidate a borrower that is over their loan-to-value. - rpc Liquidate(MsgLiquidate) returns (MsgLiquidateResponse); -} - -// MsgDeposit defines the Msg/Deposit request type. -message MsgDeposit { - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// MsgDepositResponse defines the Msg/Deposit response type. -message MsgDepositResponse {} - -// MsgWithdraw defines the Msg/Withdraw request type. -message MsgWithdraw { - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -message MsgWithdrawResponse {} - -// MsgBorrow defines the Msg/Borrow request type. -message MsgBorrow { - string borrower = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// MsgBorrowResponse defines the Msg/Borrow response type. -message MsgBorrowResponse {} - -// MsgRepay defines the Msg/Repay request type. -message MsgRepay { - string sender = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - repeated cosmos.base.v1beta1.Coin amount = 3 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// MsgRepayResponse defines the Msg/Repay response type. -message MsgRepayResponse {} - -// MsgLiquidate defines the Msg/Liquidate request type. -message MsgLiquidate { - string keeper = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - string borrower = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; -} - -// MsgLiquidateResponse defines the Msg/Liquidate response type. -message MsgLiquidateResponse {} diff --git a/proto/kava/incentive/v1beta1/apy.proto b/proto/kava/incentive/v1beta1/apy.proto deleted file mode 100644 index e3d8018c..00000000 --- a/proto/kava/incentive/v1beta1/apy.proto +++ /dev/null @@ -1,18 +0,0 @@ -syntax = "proto3"; -package kava.incentive.v1beta1; - -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/incentive/types"; - -// Apy contains the calculated APY for a given collateral type at a specific -// instant in time. -message Apy { - string collateral_type = 1; - string apy = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/incentive/v1beta1/claims.proto b/proto/kava/incentive/v1beta1/claims.proto deleted file mode 100644 index fa51db6f..00000000 --- a/proto/kava/incentive/v1beta1/claims.proto +++ /dev/null @@ -1,171 +0,0 @@ -syntax = "proto3"; -package kava.incentive.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/incentive/types"; -option (gogoproto.goproto_getters_all) = false; - -// -------------- Base Claim Types, Reward Indexes -------------- - -// BaseClaim is a claim with a single reward coin types -message BaseClaim { - option (cosmos_proto.implements_interface) = "Claim"; - - bytes owner = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - - cosmos.base.v1beta1.Coin reward = 2 [(gogoproto.nullable) = false]; -} - -// BaseMultiClaim is a claim with multiple reward coin types -message BaseMultiClaim { - option (cosmos_proto.implements_interface) = "Claim"; - - bytes owner = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - - repeated cosmos.base.v1beta1.Coin reward = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// RewardIndex stores reward accumulation information -message RewardIndex { - string collateral_type = 1; - - bytes reward_factor = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// RewardIndexesProto defines a Protobuf wrapper around a RewardIndexes slice -message RewardIndexesProto { - repeated RewardIndex reward_indexes = 1 [ - (gogoproto.castrepeated) = "RewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// MultiRewardIndex stores reward accumulation information on multiple reward types -message MultiRewardIndex { - string collateral_type = 1; - - repeated RewardIndex reward_indexes = 2 [ - (gogoproto.castrepeated) = "RewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// MultiRewardIndexesProto defines a Protobuf wrapper around a MultiRewardIndexes slice -message MultiRewardIndexesProto { - repeated MultiRewardIndex multi_reward_indexes = 1 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// -------------- Custom Claim Types -------------- - -// USDXMintingClaim is for USDX minting rewards -message USDXMintingClaim { - option (cosmos_proto.implements_interface) = "Claim"; - - BaseClaim base_claim = 1 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false - ]; - - repeated RewardIndex reward_indexes = 2 [ - (gogoproto.castrepeated) = "RewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// HardLiquidityProviderClaim stores the hard liquidity provider rewards that can be claimed by owner -message HardLiquidityProviderClaim { - option (cosmos_proto.implements_interface) = "Claim"; - - BaseMultiClaim base_claim = 1 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false - ]; - - repeated MultiRewardIndex supply_reward_indexes = 2 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; - - repeated MultiRewardIndex borrow_reward_indexes = 3 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// DelegatorClaim stores delegation rewards that can be claimed by owner -message DelegatorClaim { - option (cosmos_proto.implements_interface) = "Claim"; - - BaseMultiClaim base_claim = 1 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false - ]; - - repeated MultiRewardIndex reward_indexes = 2 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// SwapClaim stores the swap rewards that can be claimed by owner -message SwapClaim { - option (cosmos_proto.implements_interface) = "Claim"; - - BaseMultiClaim base_claim = 1 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false - ]; - - repeated MultiRewardIndex reward_indexes = 2 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// SavingsClaim stores the savings rewards that can be claimed by owner -message SavingsClaim { - option (cosmos_proto.implements_interface) = "Claim"; - - BaseMultiClaim base_claim = 1 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false - ]; - - repeated MultiRewardIndex reward_indexes = 2 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// EarnClaim stores the earn rewards that can be claimed by owner -message EarnClaim { - option (cosmos_proto.implements_interface) = "Claim"; - - BaseMultiClaim base_claim = 1 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false - ]; - - repeated MultiRewardIndex reward_indexes = 2 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/incentive/v1beta1/genesis.proto b/proto/kava/incentive/v1beta1/genesis.proto deleted file mode 100644 index 34b05810..00000000 --- a/proto/kava/incentive/v1beta1/genesis.proto +++ /dev/null @@ -1,89 +0,0 @@ -syntax = "proto3"; -package kava.incentive.v1beta1; - -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; -import "kava/incentive/v1beta1/claims.proto"; -import "kava/incentive/v1beta1/params.proto"; - -// import "cosmos/base/v1beta1/coin.proto"; -// import "cosmos/base/v1beta1/coins.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/incentive/types"; -option (gogoproto.goproto_getters_all) = false; - -// AccumulationTime stores the previous reward distribution time and its corresponding collateral type -message AccumulationTime { - string collateral_type = 1; - - google.protobuf.Timestamp previous_accumulation_time = 2 [ - (gogoproto.nullable) = false, - (gogoproto.stdtime) = true - ]; -} - -// GenesisRewardState groups together the global state for a particular reward so it can be exported in genesis. -message GenesisRewardState { - repeated AccumulationTime accumulation_times = 1 [ - (gogoproto.castrepeated) = "AccumulationTimes", - (gogoproto.nullable) = false - ]; - - repeated MultiRewardIndex multi_reward_indexes = 2 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// GenesisState is the state that must be provided at genesis. -message GenesisState { - Params params = 1 [(gogoproto.nullable) = false]; - - GenesisRewardState usdx_reward_state = 2 [ - (gogoproto.customname) = "USDXRewardState", - (gogoproto.nullable) = false - ]; - - GenesisRewardState hard_supply_reward_state = 3 [(gogoproto.nullable) = false]; - - GenesisRewardState hard_borrow_reward_state = 4 [(gogoproto.nullable) = false]; - - GenesisRewardState delegator_reward_state = 5 [(gogoproto.nullable) = false]; - - GenesisRewardState swap_reward_state = 6 [(gogoproto.nullable) = false]; - - repeated USDXMintingClaim usdx_minting_claims = 7 [ - (gogoproto.customname) = "USDXMintingClaims", - (gogoproto.castrepeated) = "USDXMintingClaims", - (gogoproto.nullable) = false - ]; - - repeated HardLiquidityProviderClaim hard_liquidity_provider_claims = 8 [ - (gogoproto.castrepeated) = "HardLiquidityProviderClaims", - (gogoproto.nullable) = false - ]; - - repeated DelegatorClaim delegator_claims = 9 [ - (gogoproto.castrepeated) = "DelegatorClaims", - (gogoproto.nullable) = false - ]; - - repeated SwapClaim swap_claims = 10 [ - (gogoproto.castrepeated) = "SwapClaims", - (gogoproto.nullable) = false - ]; - - GenesisRewardState savings_reward_state = 11 [(gogoproto.nullable) = false]; - - repeated SavingsClaim savings_claims = 12 [ - (gogoproto.castrepeated) = "SavingsClaims", - (gogoproto.nullable) = false - ]; - - GenesisRewardState earn_reward_state = 13 [(gogoproto.nullable) = false]; - - repeated EarnClaim earn_claims = 14 [ - (gogoproto.castrepeated) = "EarnClaims", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/incentive/v1beta1/params.proto b/proto/kava/incentive/v1beta1/params.proto deleted file mode 100644 index 078d4013..00000000 --- a/proto/kava/incentive/v1beta1/params.proto +++ /dev/null @@ -1,121 +0,0 @@ -syntax = "proto3"; -package kava.incentive.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/incentive/types"; -option (gogoproto.goproto_getters_all) = false; - -// RewardPeriod stores the state of an ongoing reward -message RewardPeriod { - bool active = 1; - - string collateral_type = 2; - - google.protobuf.Timestamp start = 3 [ - (gogoproto.nullable) = false, - (gogoproto.stdtime) = true - ]; - - google.protobuf.Timestamp end = 4 [ - (gogoproto.nullable) = false, - (gogoproto.stdtime) = true - ]; - - cosmos.base.v1beta1.Coin rewards_per_second = 5 [(gogoproto.nullable) = false]; -} - -// MultiRewardPeriod supports multiple reward types -message MultiRewardPeriod { - bool active = 1; - - string collateral_type = 2; - - google.protobuf.Timestamp start = 3 [ - (gogoproto.nullable) = false, - (gogoproto.stdtime) = true - ]; - - google.protobuf.Timestamp end = 4 [ - (gogoproto.nullable) = false, - (gogoproto.stdtime) = true - ]; - - repeated cosmos.base.v1beta1.Coin rewards_per_second = 5 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// Multiplier amount the claim rewards get increased by, along with how long the claim rewards are locked -message Multiplier { - string name = 1; - - int64 months_lockup = 2; - - bytes factor = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// MultipliersPerDenom is a map of denoms to a set of multipliers -message MultipliersPerDenom { - string denom = 1; - - repeated Multiplier multipliers = 2 [ - (gogoproto.castrepeated) = "Multipliers", - (gogoproto.nullable) = false - ]; -} - -// Params -message Params { - repeated RewardPeriod usdx_minting_reward_periods = 1 [ - (gogoproto.customname) = "USDXMintingRewardPeriods", - (gogoproto.castrepeated) = "RewardPeriods", - (gogoproto.nullable) = false - ]; - - repeated MultiRewardPeriod hard_supply_reward_periods = 2 [ - (gogoproto.castrepeated) = "MultiRewardPeriods", - (gogoproto.nullable) = false - ]; - - repeated MultiRewardPeriod hard_borrow_reward_periods = 3 [ - (gogoproto.castrepeated) = "MultiRewardPeriods", - (gogoproto.nullable) = false - ]; - - repeated MultiRewardPeriod delegator_reward_periods = 4 [ - (gogoproto.castrepeated) = "MultiRewardPeriods", - (gogoproto.nullable) = false - ]; - - repeated MultiRewardPeriod swap_reward_periods = 5 [ - (gogoproto.castrepeated) = "MultiRewardPeriods", - (gogoproto.nullable) = false - ]; - - repeated MultipliersPerDenom claim_multipliers = 6 [ - (gogoproto.castrepeated) = "MultipliersPerDenoms", - (gogoproto.nullable) = false - ]; - - google.protobuf.Timestamp claim_end = 7 [ - (gogoproto.nullable) = false, - (gogoproto.stdtime) = true - ]; - - repeated MultiRewardPeriod savings_reward_periods = 8 [ - (gogoproto.castrepeated) = "MultiRewardPeriods", - (gogoproto.nullable) = false - ]; - - repeated MultiRewardPeriod earn_reward_periods = 9 [ - (gogoproto.castrepeated) = "MultiRewardPeriods", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/incentive/v1beta1/query.proto b/proto/kava/incentive/v1beta1/query.proto deleted file mode 100644 index c76c0791..00000000 --- a/proto/kava/incentive/v1beta1/query.proto +++ /dev/null @@ -1,130 +0,0 @@ -syntax = "proto3"; -package kava.incentive.v1beta1; - -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "kava/incentive/v1beta1/apy.proto"; -import "kava/incentive/v1beta1/claims.proto"; -import "kava/incentive/v1beta1/params.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/incentive/types"; - -// Query defines the gRPC querier service for incentive module. -service Query { - // Params queries module params. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/incentive/v1beta1/params"; - } - - // Rewards queries reward information for a given user. - rpc Rewards(QueryRewardsRequest) returns (QueryRewardsResponse) { - option (google.api.http).get = "/kava/incentive/v1beta1/rewards"; - } - - // Rewards queries the reward factors. - rpc RewardFactors(QueryRewardFactorsRequest) returns (QueryRewardFactorsResponse) { - option (google.api.http).get = "/kava/incentive/v1beta1/reward_factors"; - } - - // Apy queries incentive reward apy for a reward. - rpc Apy(QueryApyRequest) returns (QueryApyResponse) { - option (google.api.http).get = "/kava/incentive/v1beta1/apy"; - } -} - -// QueryParamsRequest is the request type for the Query/Params RPC method. -message QueryParamsRequest {} - -// QueryParamsResponse is the response type for the Query/Params RPC method. -message QueryParamsResponse { - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryRewardsRequest is the request type for the Query/Rewards RPC method. -message QueryRewardsRequest { - // owner is the address of the user to query rewards for. - string owner = 1; - // reward_type is the type of reward to query rewards for, e.g. hard, earn, - // swap. - string reward_type = 2; - // unsynchronized is a flag to query rewards that are not simulated for reward - // synchronized for the current block. - bool unsynchronized = 3; -} - -// QueryRewardsResponse is the response type for the Query/Rewards RPC method. -message QueryRewardsResponse { - repeated USDXMintingClaim usdx_minting_claims = 1 [ - (gogoproto.customname) = "USDXMintingClaims", - (gogoproto.castrepeated) = "USDXMintingClaims", - (gogoproto.nullable) = false - ]; - - repeated HardLiquidityProviderClaim hard_liquidity_provider_claims = 2 [ - (gogoproto.castrepeated) = "HardLiquidityProviderClaims", - (gogoproto.nullable) = false - ]; - - repeated DelegatorClaim delegator_claims = 3 [ - (gogoproto.castrepeated) = "DelegatorClaims", - (gogoproto.nullable) = false - ]; - - repeated SwapClaim swap_claims = 4 [ - (gogoproto.castrepeated) = "SwapClaims", - (gogoproto.nullable) = false - ]; - - repeated SavingsClaim savings_claims = 5 [ - (gogoproto.castrepeated) = "SavingsClaims", - (gogoproto.nullable) = false - ]; - - repeated EarnClaim earn_claims = 6 [ - (gogoproto.castrepeated) = "EarnClaims", - (gogoproto.nullable) = false - ]; -} - -// QueryRewardFactorsRequest is the request type for the Query/RewardFactors RPC method. -message QueryRewardFactorsRequest {} - -// QueryRewardFactorsResponse is the response type for the Query/RewardFactors RPC method. -message QueryRewardFactorsResponse { - repeated RewardIndex usdx_minting_reward_factors = 1 [ - (gogoproto.castrepeated) = "RewardIndexes", - (gogoproto.nullable) = false - ]; - repeated MultiRewardIndex hard_supply_reward_factors = 2 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; - repeated MultiRewardIndex hard_borrow_reward_factors = 3 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; - repeated MultiRewardIndex delegator_reward_factors = 4 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; - repeated MultiRewardIndex swap_reward_factors = 5 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; - repeated MultiRewardIndex savings_reward_factors = 6 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; - repeated MultiRewardIndex earn_reward_factors = 7 [ - (gogoproto.castrepeated) = "MultiRewardIndexes", - (gogoproto.nullable) = false - ]; -} - -// QueryApysRequest is the request type for the Query/Apys RPC method. -message QueryApyRequest {} - -// QueryApysResponse is the response type for the Query/Apys RPC method. -message QueryApyResponse { - repeated Apy earn = 1 [(gogoproto.nullable) = false]; -} diff --git a/proto/kava/incentive/v1beta1/tx.proto b/proto/kava/incentive/v1beta1/tx.proto deleted file mode 100644 index 6abfb359..00000000 --- a/proto/kava/incentive/v1beta1/tx.proto +++ /dev/null @@ -1,124 +0,0 @@ -syntax = "proto3"; -package kava.incentive.v1beta1; - -import "gogoproto/gogo.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/incentive/types"; - -// Msg defines the incentive Msg service. -service Msg { - // ClaimUSDXMintingReward is a message type used to claim USDX minting rewards - rpc ClaimUSDXMintingReward(MsgClaimUSDXMintingReward) returns (MsgClaimUSDXMintingRewardResponse); - - // ClaimHardReward is a message type used to claim Hard liquidity provider rewards - rpc ClaimHardReward(MsgClaimHardReward) returns (MsgClaimHardRewardResponse); - - // ClaimDelegatorReward is a message type used to claim delegator rewards - rpc ClaimDelegatorReward(MsgClaimDelegatorReward) returns (MsgClaimDelegatorRewardResponse); - - // ClaimSwapReward is a message type used to claim swap rewards - rpc ClaimSwapReward(MsgClaimSwapReward) returns (MsgClaimSwapRewardResponse); - - // ClaimSavingsReward is a message type used to claim savings rewards - rpc ClaimSavingsReward(MsgClaimSavingsReward) returns (MsgClaimSavingsRewardResponse); - - // ClaimEarnReward is a message type used to claim earn rewards - rpc ClaimEarnReward(MsgClaimEarnReward) returns (MsgClaimEarnRewardResponse); -} - -// Selection is a pair of denom and multiplier name. It holds the choice of multiplier a user makes when they claim a -// denom. -message Selection { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string denom = 1; - string multiplier_name = 2; -} - -// MsgClaimUSDXMintingReward message type used to claim USDX minting rewards -message MsgClaimUSDXMintingReward { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string sender = 1; - string multiplier_name = 2; -} - -// MsgClaimUSDXMintingRewardResponse defines the Msg/ClaimUSDXMintingReward response type. -message MsgClaimUSDXMintingRewardResponse {} - -// MsgClaimHardReward message type used to claim Hard liquidity provider rewards -message MsgClaimHardReward { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string sender = 1; - repeated Selection denoms_to_claim = 2 [ - (gogoproto.castrepeated) = "Selections", - (gogoproto.nullable) = false - ]; -} - -// MsgClaimHardRewardResponse defines the Msg/ClaimHardReward response type. -message MsgClaimHardRewardResponse {} - -// MsgClaimDelegatorReward message type used to claim delegator rewards -message MsgClaimDelegatorReward { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string sender = 1; - repeated Selection denoms_to_claim = 2 [ - (gogoproto.castrepeated) = "Selections", - (gogoproto.nullable) = false - ]; -} - -// MsgClaimDelegatorRewardResponse defines the Msg/ClaimDelegatorReward response type. -message MsgClaimDelegatorRewardResponse {} - -// MsgClaimSwapReward message type used to claim delegator rewards -message MsgClaimSwapReward { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string sender = 1; - repeated Selection denoms_to_claim = 2 [ - (gogoproto.castrepeated) = "Selections", - (gogoproto.nullable) = false - ]; -} - -// MsgClaimSwapRewardResponse defines the Msg/ClaimSwapReward response type. -message MsgClaimSwapRewardResponse {} - -// MsgClaimSavingsReward message type used to claim savings rewards -message MsgClaimSavingsReward { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string sender = 1; - repeated Selection denoms_to_claim = 2 [ - (gogoproto.castrepeated) = "Selections", - (gogoproto.nullable) = false - ]; -} - -// MsgClaimSavingsRewardResponse defines the Msg/ClaimSavingsReward response type. -message MsgClaimSavingsRewardResponse {} - -// MsgClaimEarnReward message type used to claim earn rewards -message MsgClaimEarnReward { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string sender = 1; - repeated Selection denoms_to_claim = 2 [ - (gogoproto.castrepeated) = "Selections", - (gogoproto.nullable) = false - ]; -} - -// MsgClaimEarnRewardResponse defines the Msg/ClaimEarnReward response type. -message MsgClaimEarnRewardResponse {} diff --git a/proto/kava/kavadist/v1beta1/genesis.proto b/proto/kava/kavadist/v1beta1/genesis.proto deleted file mode 100644 index 82c440c4..00000000 --- a/proto/kava/kavadist/v1beta1/genesis.proto +++ /dev/null @@ -1,18 +0,0 @@ -syntax = "proto3"; -package kava.kavadist.v1beta1; - -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; -import "kava/kavadist/v1beta1/params.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/kavadist/types"; - -// GenesisState defines the kavadist module's genesis state. -message GenesisState { - Params params = 1 [(gogoproto.nullable) = false]; - - google.protobuf.Timestamp previous_block_time = 2 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/kavadist/v1beta1/params.proto b/proto/kava/kavadist/v1beta1/params.proto deleted file mode 100644 index b31abe43..00000000 --- a/proto/kava/kavadist/v1beta1/params.proto +++ /dev/null @@ -1,83 +0,0 @@ -syntax = "proto3"; -package kava.kavadist.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/kavadist/types"; -option (gogoproto.goproto_getters_all) = false; -option (gogoproto.goproto_stringer_all) = false; - -// Params governance parameters for kavadist module -message Params { - bool active = 1; - repeated Period periods = 3 [(gogoproto.nullable) = false]; - InfrastructureParams infrastructure_params = 4 [(gogoproto.nullable) = false]; -} - -// InfrastructureParams define the parameters for infrastructure rewards. -message InfrastructureParams { - repeated Period infrastructure_periods = 1 [ - (gogoproto.castrepeated) = "Periods", - (gogoproto.nullable) = false - ]; - repeated CoreReward core_rewards = 2 [ - (gogoproto.castrepeated) = "CoreRewards", - (gogoproto.nullable) = false - ]; - repeated PartnerReward partner_rewards = 3 [ - (gogoproto.castrepeated) = "PartnerRewards", - (gogoproto.nullable) = false - ]; - option (gogoproto.goproto_stringer) = true; -} - -// CoreReward defines the reward weights for core infrastructure providers. -message CoreReward { - bytes address = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - string weight = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - option (gogoproto.goproto_stringer) = true; -} - -// PartnerRewards defines the reward schedule for partner infrastructure providers. -message PartnerReward { - bytes address = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - cosmos.base.v1beta1.Coin rewards_per_second = 2 [(gogoproto.nullable) = false]; - option (gogoproto.goproto_stringer) = true; -} - -// Period stores the specified start and end dates, and the inflation, expressed as a decimal -// representing the yearly APR of KAVA tokens that will be minted during that period -message Period { - option (gogoproto.equal) = true; - - // example "2020-03-01T15:20:00Z" - google.protobuf.Timestamp start = 1 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - - // example "2020-06-01T15:20:00Z" - google.protobuf.Timestamp end = 2 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - - // example "1.000000003022265980" - 10% inflation - bytes inflation = 3 [ - (gogoproto.nullable) = false, - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec" - ]; -} diff --git a/proto/kava/kavadist/v1beta1/proposal.proto b/proto/kava/kavadist/v1beta1/proposal.proto deleted file mode 100644 index 1b77e7c2..00000000 --- a/proto/kava/kavadist/v1beta1/proposal.proto +++ /dev/null @@ -1,44 +0,0 @@ -syntax = "proto3"; -package kava.kavadist.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/kavadist/types"; - -// CommunityPoolMultiSpendProposal spends from the community pool by sending to one or more -// addresses -message CommunityPoolMultiSpendProposal { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - repeated MultiSpendRecipient recipient_list = 3 [(gogoproto.nullable) = false]; -} - -// CommunityPoolMultiSpendProposalJSON defines a CommunityPoolMultiSpendProposal with a deposit -message CommunityPoolMultiSpendProposalJSON { - option (gogoproto.goproto_stringer) = true; - option (gogoproto.goproto_getters) = false; - - string title = 1; - string description = 2; - repeated MultiSpendRecipient recipient_list = 3 [(gogoproto.nullable) = false]; - repeated cosmos.base.v1beta1.Coin deposit = 4 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// MultiSpendRecipient defines a recipient and the amount of coins they are receiving -message MultiSpendRecipient { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - string address = 1; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} diff --git a/proto/kava/kavadist/v1beta1/query.proto b/proto/kava/kavadist/v1beta1/query.proto deleted file mode 100644 index a77071d1..00000000 --- a/proto/kava/kavadist/v1beta1/query.proto +++ /dev/null @@ -1,41 +0,0 @@ -syntax = "proto3"; -package kava.kavadist.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "kava/kavadist/v1beta1/params.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/kavadist/types"; - -// Query defines the gRPC querier service. -service Query { - // Params queries the parameters of x/kavadist module. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/kavadist/v1beta1/parameters"; - } - - // Balance queries the balance of all coins of x/kavadist module. - rpc Balance(QueryBalanceRequest) returns (QueryBalanceResponse) { - option (google.api.http).get = "/kava/kavadist/v1beta1/balance"; - } -} - -// QueryParamsRequest defines the request type for querying x/kavadist parameters. -message QueryParamsRequest {} - -// QueryParamsResponse defines the response type for querying x/kavadist parameters. -message QueryParamsResponse { - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryBalanceRequest defines the request type for querying x/kavadist balance. -message QueryBalanceRequest {} - -// QueryBalanceResponse defines the response type for querying x/kavadist balance. -message QueryBalanceResponse { - repeated cosmos.base.v1beta1.Coin coins = 1 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} diff --git a/proto/kava/liquid/v1beta1/query.proto b/proto/kava/liquid/v1beta1/query.proto deleted file mode 100644 index d2560290..00000000 --- a/proto/kava/liquid/v1beta1/query.proto +++ /dev/null @@ -1,52 +0,0 @@ -syntax = "proto3"; -package kava.liquid.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/liquid/types"; -option (gogoproto.goproto_getters_all) = false; - -// Query defines the gRPC querier service for liquid module -service Query { - // DelegatedBalance returns an account's vesting and vested coins currently delegated to validators. - // It ignores coins in unbonding delegations. - rpc DelegatedBalance(QueryDelegatedBalanceRequest) returns (QueryDelegatedBalanceResponse) { - option (google.api.http).get = "/kava/liquid/v1beta1/delegated_balance/{delegator}"; - } - - // TotalSupply returns the total sum of all coins currently locked into the liquid module. - rpc TotalSupply(QueryTotalSupplyRequest) returns (QueryTotalSupplyResponse) { - option (google.api.http).get = "/kava/liquid/v1beta1/total_supply"; - } -} - -// QueryDelegatedBalanceRequest defines the request type for Query/DelegatedBalance method. -message QueryDelegatedBalanceRequest { - // delegator is the address of the account to query - string delegator = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; -} - -// DelegatedBalanceResponse defines the response type for the Query/DelegatedBalance method. -message QueryDelegatedBalanceResponse { - // vested is the amount of all delegated coins that have vested (ie not locked) - cosmos.base.v1beta1.Coin vested = 1 [(gogoproto.nullable) = false]; - // vesting is the amount of all delegated coins that are still vesting (ie locked) - cosmos.base.v1beta1.Coin vesting = 2 [(gogoproto.nullable) = false]; -} - -// QueryTotalSupplyRequest defines the request type for Query/TotalSupply method. -message QueryTotalSupplyRequest {} - -// TotalSupplyResponse defines the response type for the Query/TotalSupply method. -message QueryTotalSupplyResponse { - // Height is the block height at which these totals apply - int64 height = 1; - // Result is a list of coins supplied to liquid - repeated cosmos.base.v1beta1.Coin result = 2 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} diff --git a/proto/kava/liquid/v1beta1/tx.proto b/proto/kava/liquid/v1beta1/tx.proto deleted file mode 100644 index abbac641..00000000 --- a/proto/kava/liquid/v1beta1/tx.proto +++ /dev/null @@ -1,53 +0,0 @@ -syntax = "proto3"; -package kava.liquid.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/liquid/types"; - -// Msg defines the liquid Msg service. -service Msg { - // MintDerivative defines a method for converting a delegation into staking deriviatives. - rpc MintDerivative(MsgMintDerivative) returns (MsgMintDerivativeResponse); - - // BurnDerivative defines a method for converting staking deriviatives into a delegation. - rpc BurnDerivative(MsgBurnDerivative) returns (MsgBurnDerivativeResponse); -} - -// MsgMintDerivative defines the Msg/MintDerivative request type. -message MsgMintDerivative { - // sender is the owner of the delegation to be converted - string sender = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // validator is the validator of the delegation to be converted - string validator = 2; - // amount is the quantity of staked assets to be converted - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// MsgMintDerivativeResponse defines the Msg/MintDerivative response type. -message MsgMintDerivativeResponse { - // received is the amount of staking derivative minted and sent to the sender - cosmos.base.v1beta1.Coin received = 1 [(gogoproto.nullable) = false]; -} - -// MsgBurnDerivative defines the Msg/BurnDerivative request type. -message MsgBurnDerivative { - // sender is the owner of the derivatives to be converted - string sender = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // validator is the validator of the derivatives to be converted - string validator = 2; - // amount is the quantity of derivatives to be converted - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// MsgBurnDerivativeResponse defines the Msg/BurnDerivative response type. -message MsgBurnDerivativeResponse { - // received is the number of delegation shares sent to the sender - string received = 1 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/router/v1beta1/tx.proto b/proto/kava/router/v1beta1/tx.proto deleted file mode 100644 index 7ae32d93..00000000 --- a/proto/kava/router/v1beta1/tx.proto +++ /dev/null @@ -1,80 +0,0 @@ -syntax = "proto3"; -package kava.router.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/router/types"; -option (gogoproto.goproto_getters_all) = false; - -// Msg defines the router Msg service. -service Msg { - // MintDeposit converts a delegation into staking derivatives and deposits it all into an earn vault. - rpc MintDeposit(MsgMintDeposit) returns (MsgMintDepositResponse); - - // DelegateMintDeposit delegates tokens to a validator, then converts them into staking derivatives, - // then deposits to an earn vault. - rpc DelegateMintDeposit(MsgDelegateMintDeposit) returns (MsgDelegateMintDepositResponse); - - // WithdrawBurn removes staking derivatives from an earn vault and converts them back to a staking delegation. - rpc WithdrawBurn(MsgWithdrawBurn) returns (MsgWithdrawBurnResponse); - - // WithdrawBurnUndelegate removes staking derivatives from an earn vault, converts them to a staking delegation, - // then undelegates them from their validator. - rpc WithdrawBurnUndelegate(MsgWithdrawBurnUndelegate) returns (MsgWithdrawBurnUndelegateResponse); -} - -// MsgMintDeposit converts a delegation into staking derivatives and deposits it all into an earn vault. -message MsgMintDeposit { - // depositor represents the owner of the delegation to convert - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // validator is the validator for the depositor's delegation - string validator = 2; - // amount is the delegation balance to convert - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// MsgMintDepositResponse defines the Msg/MsgMintDeposit response type. -message MsgMintDepositResponse {} - -// MsgDelegateMintDeposit delegates tokens to a validator, then converts them into staking derivatives, -// then deposits to an earn vault. -message MsgDelegateMintDeposit { - // depositor represents the owner of the tokens to delegate - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // validator is the address of the validator to delegate to - string validator = 2; - // amount is the tokens to delegate - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// MsgDelegateMintDepositResponse defines the Msg/MsgDelegateMintDeposit response type. -message MsgDelegateMintDepositResponse {} - -// MsgWithdrawBurn removes staking derivatives from an earn vault and converts them back to a staking delegation. -message MsgWithdrawBurn { - // from is the owner of the earn vault to withdraw from - string from = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // validator is the address to select the derivative denom to withdraw - string validator = 2; - // amount is the staked token equivalent to withdraw - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// MsgWithdrawBurnResponse defines the Msg/MsgWithdrawBurn response type. -message MsgWithdrawBurnResponse {} - -// MsgWithdrawBurnUndelegate removes staking derivatives from an earn vault, converts them to a staking delegation, -// then undelegates them from their validator. -message MsgWithdrawBurnUndelegate { - // from is the owner of the earn vault to withdraw from - string from = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // validator is the address to select the derivative denom to withdraw - string validator = 2; - // amount is the staked token equivalent to withdraw - cosmos.base.v1beta1.Coin amount = 3 [(gogoproto.nullable) = false]; -} - -// MsgWithdrawBurnUndelegateResponse defines the Msg/MsgWithdrawBurnUndelegate response type. -message MsgWithdrawBurnUndelegateResponse {} diff --git a/proto/kava/savings/v1beta1/genesis.proto b/proto/kava/savings/v1beta1/genesis.proto deleted file mode 100644 index 0bf5a97c..00000000 --- a/proto/kava/savings/v1beta1/genesis.proto +++ /dev/null @@ -1,18 +0,0 @@ -syntax = "proto3"; -package kava.savings.v1beta1; - -import "gogoproto/gogo.proto"; -import "kava/savings/v1beta1/store.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/savings/types"; - -// GenesisState defines the savings module's genesis state. -message GenesisState { - // params defines all the parameters of the module. - Params params = 1 [(gogoproto.nullable) = false]; - - repeated Deposit deposits = 2 [ - (gogoproto.castrepeated) = "Deposits", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/savings/v1beta1/query.proto b/proto/kava/savings/v1beta1/query.proto deleted file mode 100644 index f1068f8d..00000000 --- a/proto/kava/savings/v1beta1/query.proto +++ /dev/null @@ -1,75 +0,0 @@ -syntax = "proto3"; -package kava.savings.v1beta1; - -import "cosmos/base/query/v1beta1/pagination.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "kava/savings/v1beta1/store.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/savings/types"; - -// Query defines the gRPC querier service for savings module -service Query { - // Params queries all parameters of the savings module. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/savings/v1beta1/params"; - } - - // Deposits queries savings deposits. - rpc Deposits(QueryDepositsRequest) returns (QueryDepositsResponse) { - option (google.api.http).get = "/kava/savings/v1beta1/deposits"; - } - - // TotalSupply returns the total sum of all coins currently locked into the savings module. - rpc TotalSupply(QueryTotalSupplyRequest) returns (QueryTotalSupplyResponse) { - option (google.api.http).get = "/kava/savings/v1beta1/total_supply"; - } -} - -// QueryParamsRequest defines the request type for querying x/savings -// parameters. -message QueryParamsRequest {} - -// QueryParamsResponse defines the response type for querying x/savings -// parameters. -message QueryParamsResponse { - option (gogoproto.goproto_getters) = false; - - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryDepositsRequest defines the request type for querying x/savings -// deposits. -message QueryDepositsRequest { - string denom = 1; - string owner = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - - cosmos.base.query.v1beta1.PageRequest pagination = 3; -} - -// QueryDepositsResponse defines the response type for querying x/savings -// deposits. -message QueryDepositsResponse { - repeated Deposit deposits = 1 [ - (gogoproto.castrepeated) = "Deposits", - (gogoproto.nullable) = false - ]; - - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryTotalSupplyRequest defines the request type for Query/TotalSupply method. -message QueryTotalSupplyRequest {} - -// TotalSupplyResponse defines the response type for the Query/TotalSupply method. -message QueryTotalSupplyResponse { - // Height is the block height at which these totals apply - int64 height = 1; - // Result is a list of coins supplied to savings - repeated cosmos.base.v1beta1.Coin result = 2 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} diff --git a/proto/kava/savings/v1beta1/store.proto b/proto/kava/savings/v1beta1/store.proto deleted file mode 100644 index ddc0c372..00000000 --- a/proto/kava/savings/v1beta1/store.proto +++ /dev/null @@ -1,27 +0,0 @@ -syntax = "proto3"; -package kava.savings.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/savings/types"; -option (gogoproto.goproto_getters_all) = false; - -// Params defines the parameters for the savings module. -message Params { - repeated string supported_denoms = 1; -} - -// Deposit defines an amount of coins deposited into a savings module account. -message Deposit { - string depositor = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/savings/v1beta1/tx.proto b/proto/kava/savings/v1beta1/tx.proto deleted file mode 100644 index 009895d4..00000000 --- a/proto/kava/savings/v1beta1/tx.proto +++ /dev/null @@ -1,41 +0,0 @@ -syntax = "proto3"; -package kava.savings.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/savings/types"; - -// Msg defines the savings Msg service. -service Msg { - // Deposit defines a method for depositing funds to the savings module account - rpc Deposit(MsgDeposit) returns (MsgDepositResponse); - - // Withdraw defines a method for withdrawing funds to the savings module account - rpc Withdraw(MsgWithdraw) returns (MsgWithdrawResponse); -} - -// MsgDeposit defines the Msg/Deposit request type. -message MsgDeposit { - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// MsgDepositResponse defines the Msg/Deposit response type. -message MsgDepositResponse {} - -// MsgWithdraw defines the Msg/Withdraw request type. -message MsgWithdraw { - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -message MsgWithdrawResponse {} diff --git a/proto/kava/swap/v1beta1/genesis.proto b/proto/kava/swap/v1beta1/genesis.proto deleted file mode 100644 index 7b87c61d..00000000 --- a/proto/kava/swap/v1beta1/genesis.proto +++ /dev/null @@ -1,23 +0,0 @@ -syntax = "proto3"; -package kava.swap.v1beta1; - -import "gogoproto/gogo.proto"; -import "kava/swap/v1beta1/swap.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/swap/types"; - -// GenesisState defines the swap module's genesis state. -message GenesisState { - // params defines all the parameters related to swap - Params params = 1 [(gogoproto.nullable) = false]; - // pool_records defines the available pools - repeated PoolRecord pool_records = 2 [ - (gogoproto.castrepeated) = "PoolRecords", - (gogoproto.nullable) = false - ]; - // share_records defines the owned shares of each pool - repeated ShareRecord share_records = 3 [ - (gogoproto.castrepeated) = "ShareRecords", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/swap/v1beta1/query.proto b/proto/kava/swap/v1beta1/query.proto deleted file mode 100644 index e021c683..00000000 --- a/proto/kava/swap/v1beta1/query.proto +++ /dev/null @@ -1,118 +0,0 @@ -syntax = "proto3"; -package kava.swap.v1beta1; - -import "cosmos/base/query/v1beta1/pagination.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "kava/swap/v1beta1/swap.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/swap/types"; - -// Query defines the gRPC querier service for swap module -service Query { - // Params queries all parameters of the swap module. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/kava/swap/v1beta1/params"; - } - // Pools queries pools based on pool ID - rpc Pools(QueryPoolsRequest) returns (QueryPoolsResponse) { - option (google.api.http).get = "/kava/swap/v1beta1/pools"; - } - // Deposits queries deposit details based on owner address and pool - rpc Deposits(QueryDepositsRequest) returns (QueryDepositsResponse) { - option (google.api.http).get = "/kava/swap/v1beta1/deposits"; - } -} - -// QueryParamsRequest defines the request type for querying x/swap parameters. -message QueryParamsRequest { - option (gogoproto.goproto_getters) = false; -} - -// QueryParamsResponse defines the response type for querying x/swap parameters. -message QueryParamsResponse { - option (gogoproto.goproto_getters) = false; - - // params represents the swap module parameters - Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryPoolsRequest is the request type for the Query/Pools RPC method. -message QueryPoolsRequest { - // pool_id filters pools by id - string pool_id = 1; - // pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 2; -} - -// QueryPoolsResponse is the response type for the Query/Pools RPC method. -message QueryPoolsResponse { - // pools represents returned pools - repeated PoolResponse pools = 1 [(gogoproto.nullable) = false]; - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// Pool represents the state of a single pool -message PoolResponse { - option (gogoproto.goproto_getters) = false; - - // name represents the name of the pool - string name = 1; - // coins represents the total reserves of the pool - repeated cosmos.base.v1beta1.Coin coins = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; - // total_shares represents the total shares of the pool - string total_shares = 3 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; -} - -// QueryDepositsRequest is the request type for the Query/Deposits RPC method. -message QueryDepositsRequest { - option (gogoproto.goproto_getters) = false; - - // owner optionally filters deposits by owner - string owner = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // pool_id optionally fitlers deposits by pool id - string pool_id = 2; - // pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 3; -} - -// QueryDepositsResponse is the response type for the Query/Deposits RPC method. -message QueryDepositsResponse { - option (gogoproto.goproto_getters) = false; - - // deposits returns the deposits matching the requested parameters - repeated DepositResponse deposits = 1 [(gogoproto.nullable) = false]; - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// DepositResponse defines a single deposit query response type. -message DepositResponse { - option (gogoproto.goproto_getters) = false; - - // depositor represents the owner of the deposit - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // pool_id represents the pool the deposit is for - string pool_id = 2; - // shares_owned presents the shares owned by the depositor for the pool - string shares_owned = 3 [ - (cosmos_proto.scalar) = "cosmos.AddressString", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - // shares_value represents the coin value of the shares_owned - repeated cosmos.base.v1beta1.Coin shares_value = 4 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/swap/v1beta1/swap.proto b/proto/kava/swap/v1beta1/swap.proto deleted file mode 100644 index edec360c..00000000 --- a/proto/kava/swap/v1beta1/swap.proto +++ /dev/null @@ -1,69 +0,0 @@ -syntax = "proto3"; -package kava.swap.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/swap/types"; - -// Params defines the parameters for the swap module. -message Params { - option (gogoproto.goproto_stringer) = false; // false here because we define Stringer method in params.go - - // allowed_pools defines that pools that are allowed to be created - repeated AllowedPool allowed_pools = 1 [ - (gogoproto.castrepeated) = "AllowedPools", - (gogoproto.nullable) = false - ]; - // swap_fee defines the swap fee for all pools - string swap_fee = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// AllowedPool defines a pool that is allowed to be created -message AllowedPool { - option (gogoproto.goproto_stringer) = false; // false here because we define Stringer method in params.go - - // token_a represents the a token allowed - string token_a = 1; - // token_b represents the b token allowed - string token_b = 2; -} - -// PoolRecord represents the state of a liquidity pool -// and is used to store the state of a denominated pool -message PoolRecord { - // pool_id represents the unique id of the pool - string pool_id = 1 [(gogoproto.customname) = "PoolID"]; - // reserves_a is the a token coin reserves - cosmos.base.v1beta1.Coin reserves_a = 2 [(gogoproto.nullable) = false]; - // reserves_b is the a token coin reserves - cosmos.base.v1beta1.Coin reserves_b = 3 [(gogoproto.nullable) = false]; - // total_shares is the total distrubuted shares of the pool - string total_shares = 4 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; -} - -// ShareRecord stores the shares owned for a depositor and pool -message ShareRecord { - // depositor represents the owner of the shares - bytes depositor = 1 [ - (cosmos_proto.scalar) = "cosmos.AddressBytes", - (gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress" - ]; - // pool_id represents the pool the shares belong to - string pool_id = 2 [(gogoproto.customname) = "PoolID"]; - // shares_owned represents the number of shares owned by depsoitor for the pool_id - string shares_owned = 3 [ - (cosmos_proto.scalar) = "cosmos.Int", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/kava/swap/v1beta1/tx.proto b/proto/kava/swap/v1beta1/tx.proto deleted file mode 100644 index d52ec9b7..00000000 --- a/proto/kava/swap/v1beta1/tx.proto +++ /dev/null @@ -1,114 +0,0 @@ -syntax = "proto3"; -package kava.swap.v1beta1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/0glabs/0g-chain/x/swap/types"; - -// Msg defines the swap Msg service. -service Msg { - // Deposit defines a method for depositing liquidity into a pool - rpc Deposit(MsgDeposit) returns (MsgDepositResponse); - // Withdraw defines a method for withdrawing liquidity into a pool - rpc Withdraw(MsgWithdraw) returns (MsgWithdrawResponse); - // SwapExactForTokens represents a message for trading exact coinA for coinB - rpc SwapExactForTokens(MsgSwapExactForTokens) returns (MsgSwapExactForTokensResponse); - // SwapForExactTokens represents a message for trading coinA for an exact coinB - rpc SwapForExactTokens(MsgSwapForExactTokens) returns (MsgSwapForExactTokensResponse); -} - -// MsgDeposit represents a message for depositing liquidity into a pool -message MsgDeposit { - option (gogoproto.goproto_getters) = false; - - // depositor represents the address to deposit funds from - string depositor = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // token_a represents one token of deposit pair - cosmos.base.v1beta1.Coin token_a = 2 [(gogoproto.nullable) = false]; - // token_b represents one token of deposit pair - cosmos.base.v1beta1.Coin token_b = 3 [(gogoproto.nullable) = false]; - // slippage represents the max decimal percentage price change - string slippage = 4 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - // deadline represents the unix timestamp to complete the deposit by - int64 deadline = 5; -} - -// MsgDepositResponse defines the Msg/Deposit response type. -message MsgDepositResponse {} - -// MsgWithdraw represents a message for withdrawing liquidity from a pool -message MsgWithdraw { - option (gogoproto.goproto_getters) = false; - - // from represents the address we are withdrawing for - string from = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // shares represents the amount of shares to withdraw - string shares = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - // min_token_a represents the minimum a token to withdraw - cosmos.base.v1beta1.Coin min_token_a = 3 [(gogoproto.nullable) = false]; - // min_token_a represents the minimum a token to withdraw - cosmos.base.v1beta1.Coin min_token_b = 4 [(gogoproto.nullable) = false]; - // deadline represents the unix timestamp to complete the withdraw by - int64 deadline = 5; -} - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -message MsgWithdrawResponse {} - -// MsgSwapExactForTokens represents a message for trading exact coinA for coinB -message MsgSwapExactForTokens { - option (gogoproto.goproto_getters) = false; - - // represents the address swaping the tokens - string requester = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // exact_token_a represents the exact amount to swap for token_b - cosmos.base.v1beta1.Coin exact_token_a = 2 [(gogoproto.nullable) = false]; - // token_b represents the desired token_b to swap for - cosmos.base.v1beta1.Coin token_b = 3 [(gogoproto.nullable) = false]; - // slippage represents the maximum change in token_b allowed - string slippage = 4 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - // deadline represents the unix timestamp to complete the swap by - int64 deadline = 5; -} - -// MsgSwapExactForTokensResponse defines the Msg/SwapExactForTokens response -// type. -message MsgSwapExactForTokensResponse {} - -// MsgSwapForExactTokens represents a message for trading coinA for an exact -// coinB -message MsgSwapForExactTokens { - option (gogoproto.goproto_getters) = false; - - // represents the address swaping the tokens - string requester = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - // token_a represents the desired token_a to swap for - cosmos.base.v1beta1.Coin token_a = 2 [(gogoproto.nullable) = false]; - // exact_token_b represents the exact token b amount to swap for token a - cosmos.base.v1beta1.Coin exact_token_b = 3 [(gogoproto.nullable) = false]; - // slippage represents the maximum change in token_a allowed - string slippage = 4 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - // deadline represents the unix timestamp to complete the swap by - int64 deadline = 5; -} - -// MsgSwapForExactTokensResponse defines the Msg/SwapForExactTokensResponse -// response type. -message MsgSwapForExactTokensResponse {} diff --git a/tests/e2e/e2e_community_update_params_test.go b/tests/e2e/e2e_community_update_params_test.go index 9fa1262d..8e0a56ea 100644 --- a/tests/e2e/e2e_community_update_params_test.go +++ b/tests/e2e/e2e_community_update_params_test.go @@ -1,186 +1,176 @@ package e2e_test import ( - "context" "encoding/hex" - "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" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - - "github.com/0glabs/0g-chain/tests/e2e/testutil" - "github.com/0glabs/0g-chain/tests/util" - communitytypes "github.com/0glabs/0g-chain/x/community/types" ) -func (suite *IntegrationTestSuite) TestCommunityUpdateParams_NonAuthority() { - // ARRANGE - // setup kava account - funds := ukava(1e5) // .1 KAVA - kavaAcc := suite.Kava.NewFundedAccount("community-non-authority", sdk.NewCoins(funds)) +// func (suite *IntegrationTestSuite) TestCommunityUpdateParams_NonAuthority() { +// // ARRANGE +// // setup kava account +// funds := ukava(1e5) // .1 KAVA +// kavaAcc := suite.Kava.NewFundedAccount("community-non-authority", sdk.NewCoins(funds)) - gasLimit := int64(2e5) - fee := ukava(200) +// gasLimit := int64(2e5) +// fee := ukava(200) - msg := communitytypes.NewMsgUpdateParams( - kavaAcc.SdkAddress, - communitytypes.DefaultParams(), - ) +// msg := communitytypes.NewMsgUpdateParams( +// kavaAcc.SdkAddress, +// communitytypes.DefaultParams(), +// ) - // ACT - req := util.KavaMsgRequest{ - Msgs: []sdk.Msg{&msg}, - GasLimit: uint64(gasLimit), - FeeAmount: sdk.NewCoins(fee), - Memo: "this is a failure!", - } - res := kavaAcc.SignAndBroadcastKavaTx(req) +// // ACT +// req := util.KavaMsgRequest{ +// Msgs: []sdk.Msg{&msg}, +// GasLimit: uint64(gasLimit), +// FeeAmount: sdk.NewCoins(fee), +// Memo: "this is a failure!", +// } +// res := kavaAcc.SignAndBroadcastKavaTx(req) - // ASSERT - _, err := util.WaitForSdkTxCommit(suite.Kava.Grpc.Query.Tx, res.Result.TxHash, 6*time.Second) - suite.Require().Error(err) - suite.Require().ErrorContains( - err, - govtypes.ErrInvalidSigner.Error(), - "should return with authority check error", - ) -} +// // ASSERT +// _, err := util.WaitForSdkTxCommit(suite.Kava.Grpc.Query.Tx, res.Result.TxHash, 6*time.Second) +// suite.Require().Error(err) +// suite.Require().ErrorContains( +// err, +// govtypes.ErrInvalidSigner.Error(), +// "should return with authority check error", +// ) +// } -func (suite *IntegrationTestSuite) TestCommunityUpdateParams_Authority() { - // ARRANGE - govParamsRes, err := suite.Kava.Grpc.Query.Gov.Params(context.Background(), &govv1.QueryParamsRequest{ - ParamsType: govv1.ParamDeposit, - }) - suite.NoError(err) +// func (suite *IntegrationTestSuite) TestCommunityUpdateParams_Authority() { +// // ARRANGE +// govParamsRes, err := suite.Kava.Grpc.Query.Gov.Params(context.Background(), &govv1.QueryParamsRequest{ +// ParamsType: govv1.ParamDeposit, +// }) +// suite.NoError(err) - // Check initial params - communityParamsResInitial, err := suite.Kava.Grpc.Query.Community.Params( - context.Background(), - &communitytypes.QueryParamsRequest{}, - ) - suite.Require().NoError(err) +// // Check initial params +// communityParamsResInitial, err := suite.Kava.Grpc.Query.Community.Params( +// context.Background(), +// &communitytypes.QueryParamsRequest{}, +// ) +// suite.Require().NoError(err) - // setup kava account - // .1 KAVA + min deposit amount for proposal - funds := sdk.NewCoins(ukava(1e5)).Add(govParamsRes.DepositParams.MinDeposit...) - kavaAcc := suite.Kava.NewFundedAccount("community-update-params", funds) +// // setup kava account +// // .1 KAVA + min deposit amount for proposal +// funds := sdk.NewCoins(ukava(1e5)).Add(govParamsRes.DepositParams.MinDeposit...) +// kavaAcc := suite.Kava.NewFundedAccount("community-update-params", funds) - gasLimit := int64(2e5) - fee := ukava(200) +// gasLimit := int64(2e5) +// fee := ukava(200) - // Wait until switchover actually happens - When testing without the upgrade - // handler that sets a relative switchover time, the switchover time in - // genesis should be set in the past so it runs immediately. - suite.Require().Eventually( - func() bool { - params, err := suite.Kava.Grpc.Query.Community.Params( - context.Background(), - &communitytypes.QueryParamsRequest{}, - ) - suite.Require().NoError(err) +// // Wait until switchover actually happens - When testing without the upgrade +// // handler that sets a relative switchover time, the switchover time in +// // genesis should be set in the past so it runs immediately. +// suite.Require().Eventually( +// func() bool { +// params, err := suite.Kava.Grpc.Query.Community.Params( +// context.Background(), +// &communitytypes.QueryParamsRequest{}, +// ) +// suite.Require().NoError(err) - return params.Params.UpgradeTimeDisableInflation.Equal(time.Time{}) - }, - 20*time.Second, - 1*time.Second, - "switchover should happen", - ) +// return params.Params.UpgradeTimeDisableInflation.Equal(time.Time{}) +// }, +// 20*time.Second, +// 1*time.Second, +// "switchover should happen", +// ) - // Add 1 to the staking rewards per second - newStakingRewardsPerSecond := communityParamsResInitial.Params. - StakingRewardsPerSecond. - Add(sdkmath.LegacyNewDec(1)) +// // Add 1 to the staking rewards per second +// newStakingRewardsPerSecond := communityParamsResInitial.Params. +// StakingRewardsPerSecond. +// Add(sdkmath.LegacyNewDec(1)) - // 1. Proposal - // Only modify stakingRewardsPerSecond, as to not re-run the switchover and - // to not influence other tests - updateParamsMsg := communitytypes.NewMsgUpdateParams( - authtypes.NewModuleAddress(govtypes.ModuleName), // authority - communitytypes.NewParams( - time.Time{}, // after switchover, is empty - newStakingRewardsPerSecond, // only modify stakingRewardsPerSecond - communityParamsResInitial.Params.UpgradeTimeSetStakingRewardsPerSecond, - ), - ) +// // 1. Proposal +// // Only modify stakingRewardsPerSecond, as to not re-run the switchover and +// // to not influence other tests +// updateParamsMsg := communitytypes.NewMsgUpdateParams( +// authtypes.NewModuleAddress(govtypes.ModuleName), // authority +// communitytypes.NewParams( +// time.Time{}, // after switchover, is empty +// newStakingRewardsPerSecond, // only modify stakingRewardsPerSecond +// communityParamsResInitial.Params.UpgradeTimeSetStakingRewardsPerSecond, +// ), +// ) - // Make sure we're actually changing the params - suite.NotEqual( - updateParamsMsg.Params, - communityParamsResInitial.Params, - "new params should be different from existing", - ) +// // Make sure we're actually changing the params +// suite.NotEqual( +// updateParamsMsg.Params, +// communityParamsResInitial.Params, +// "new params should be different from existing", +// ) - proposalMsg, err := govv1.NewMsgSubmitProposal( - []sdk.Msg{&updateParamsMsg}, - govParamsRes.Params.MinDeposit, - kavaAcc.SdkAddress.String(), - "community-update-params", - "title", - "summary", - ) - suite.NoError(err) +// proposalMsg, err := govv1.NewMsgSubmitProposal( +// []sdk.Msg{&updateParamsMsg}, +// govParamsRes.Params.MinDeposit, +// kavaAcc.SdkAddress.String(), +// "community-update-params", +// "title", +// "summary", +// ) +// suite.NoError(err) - req := util.KavaMsgRequest{ - Msgs: []sdk.Msg{proposalMsg}, - GasLimit: uint64(gasLimit), - FeeAmount: sdk.NewCoins(fee), - Memo: "this is a proposal please accept me", - } - res := kavaAcc.SignAndBroadcastKavaTx(req) - suite.Require().NoError(res.Err) +// req := util.KavaMsgRequest{ +// Msgs: []sdk.Msg{proposalMsg}, +// GasLimit: uint64(gasLimit), +// FeeAmount: sdk.NewCoins(fee), +// Memo: "this is a proposal please accept me", +// } +// res := kavaAcc.SignAndBroadcastKavaTx(req) +// suite.Require().NoError(res.Err) - // Wait for proposal to be submitted - txRes, err := util.WaitForSdkTxCommit(suite.Kava.Grpc.Query.Tx, res.Result.TxHash, 6*time.Second) - suite.Require().NoError(err) +// // Wait for proposal to be submitted +// txRes, err := util.WaitForSdkTxCommit(suite.Kava.Grpc.Query.Tx, res.Result.TxHash, 6*time.Second) +// suite.Require().NoError(err) - // Parse tx response to get proposal id - var govRes govv1.MsgSubmitProposalResponse - suite.decodeTxMsgResponse(txRes, &govRes) +// // Parse tx response to get proposal id +// var govRes govv1.MsgSubmitProposalResponse +// suite.decodeTxMsgResponse(txRes, &govRes) - // 2. Vote for proposal from whale account - whale := suite.Kava.GetAccount(testutil.FundedAccountName) - voteMsg := govv1.NewMsgVote( - whale.SdkAddress, - govRes.ProposalId, - govv1.OptionYes, - "", - ) +// // 2. Vote for proposal from whale account +// whale := suite.Kava.GetAccount(testutil.FundedAccountName) +// voteMsg := govv1.NewMsgVote( +// whale.SdkAddress, +// govRes.ProposalId, +// govv1.OptionYes, +// "", +// ) - voteReq := util.KavaMsgRequest{ - Msgs: []sdk.Msg{voteMsg}, - GasLimit: uint64(gasLimit), - FeeAmount: sdk.NewCoins(fee), - Memo: "voting", - } - voteRes := whale.SignAndBroadcastKavaTx(voteReq) - suite.Require().NoError(voteRes.Err) +// voteReq := util.KavaMsgRequest{ +// Msgs: []sdk.Msg{voteMsg}, +// GasLimit: uint64(gasLimit), +// FeeAmount: sdk.NewCoins(fee), +// Memo: "voting", +// } +// voteRes := whale.SignAndBroadcastKavaTx(voteReq) +// suite.Require().NoError(voteRes.Err) - _, err = util.WaitForSdkTxCommit(suite.Kava.Grpc.Query.Tx, voteRes.Result.TxHash, 6*time.Second) - suite.Require().NoError(err) +// _, err = util.WaitForSdkTxCommit(suite.Kava.Grpc.Query.Tx, voteRes.Result.TxHash, 6*time.Second) +// suite.Require().NoError(err) - // 3. Wait until proposal passes - suite.Require().Eventually(func() bool { - proposalRes, err := suite.Kava.Grpc.Query.Gov.Proposal(context.Background(), &govv1.QueryProposalRequest{ - ProposalId: govRes.ProposalId, - }) - suite.NoError(err) +// // 3. Wait until proposal passes +// suite.Require().Eventually(func() bool { +// proposalRes, err := suite.Kava.Grpc.Query.Gov.Proposal(context.Background(), &govv1.QueryProposalRequest{ +// ProposalId: govRes.ProposalId, +// }) +// suite.NoError(err) - return proposalRes.Proposal.Status == govv1.StatusPassed - }, 60*time.Second, 1*time.Second) +// return proposalRes.Proposal.Status == govv1.StatusPassed +// }, 60*time.Second, 1*time.Second) - // Check parameters are updated - communityParamsRes, err := suite.Kava.Grpc.Query.Community.Params( - context.Background(), - &communitytypes.QueryParamsRequest{}, - ) - suite.Require().NoError(err) +// // Check parameters are updated +// communityParamsRes, err := suite.Kava.Grpc.Query.Community.Params( +// context.Background(), +// &communitytypes.QueryParamsRequest{}, +// ) +// suite.Require().NoError(err) - suite.Equal(updateParamsMsg.Params, communityParamsRes.Params) -} +// suite.Equal(updateParamsMsg.Params, communityParamsRes.Params) +// } func (suite *IntegrationTestSuite) decodeTxMsgResponse(txRes *sdk.TxResponse, ptr codec.ProtoMarshaler) { // convert txRes.Data hex string to bytes diff --git a/tests/e2e/e2e_evm_contracts_test.go b/tests/e2e/e2e_evm_contracts_test.go index 5e0163d5..4375c916 100644 --- a/tests/e2e/e2e_evm_contracts_test.go +++ b/tests/e2e/e2e_evm_contracts_test.go @@ -11,7 +11,6 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/0glabs/0g-chain/app" - cdptypes "github.com/0glabs/0g-chain/x/cdp/types" evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types" "github.com/0glabs/0g-chain/tests/e2e/contracts/greeter" @@ -111,7 +110,7 @@ func (suite *IntegrationTestSuite) TestEip712BasicMessageAuthorization() { func (suite *IntegrationTestSuite) TestEip712ConvertToCoinAndDepositToLend() { // cdp requires minimum of $11 collateral amount := sdk.NewInt(11e6) // 11 USDT - principal := sdk.NewCoin("usdx", sdk.NewInt(10e6)) + // principal := sdk.NewCoin("usdx", sdk.NewInt(10e6)) sdkDenom := suite.DeployedErc20.CosmosDenom // create new funded account @@ -127,17 +126,17 @@ func (suite *IntegrationTestSuite) TestEip712ConvertToCoinAndDepositToLend() { evmutiltypes.NewInternalEVMAddress(suite.DeployedErc20.Address), amount, ) - depositMsg := cdptypes.NewMsgCreateCDP( - depositor.SdkAddress, - sdk.NewCoin(sdkDenom, amount), - principal, - suite.DeployedErc20.CdpCollateralType, - ) + // depositMsg := cdptypes.NewMsgCreateCDP( + // depositor.SdkAddress, + // sdk.NewCoin(sdkDenom, amount), + // principal, + // suite.DeployedErc20.CdpCollateralType, + // ) msgs := []sdk.Msg{ // convert to coin &convertMsg, // deposit into cdp (Mint), take out USDX - &depositMsg, + // &depositMsg, } // create tx @@ -169,27 +168,27 @@ func (suite *IntegrationTestSuite) TestEip712ConvertToCoinAndDepositToLend() { suite.BigIntsEqual(big.NewInt(0), balance, "expected no erc20 balance") // check that account has cdp - cdpRes, err := suite.Kava.Grpc.Query.Cdp.Cdp(context.Background(), &cdptypes.QueryCdpRequest{ - CollateralType: suite.DeployedErc20.CdpCollateralType, - Owner: depositor.SdkAddress.String(), - }) - suite.NoError(err) - suite.True(cdpRes.Cdp.Collateral.Amount.Equal(amount)) - suite.True(cdpRes.Cdp.Principal.Equal(principal)) + // cdpRes, err := suite.Kava.Grpc.Query.Cdp.Cdp(context.Background(), &cdptypes.QueryCdpRequest{ + // CollateralType: suite.DeployedErc20.CdpCollateralType, + // Owner: depositor.SdkAddress.String(), + // }) + // suite.NoError(err) + // suite.True(cdpRes.Cdp.Collateral.Amount.Equal(amount)) + // suite.True(cdpRes.Cdp.Principal.Equal(principal)) // withdraw deposit & convert back to erc20 (this allows refund to recover erc20s used in test) - withdraw := cdptypes.NewMsgRepayDebt( - depositor.SdkAddress, - suite.DeployedErc20.CdpCollateralType, - principal, - ) + // withdraw := cdptypes.NewMsgRepayDebt( + // depositor.SdkAddress, + // suite.DeployedErc20.CdpCollateralType, + // principal, + // ) convertBack := evmutiltypes.NewMsgConvertCoinToERC20( depositor.SdkAddress.String(), depositor.EvmAddress.Hex(), sdk.NewCoin(sdkDenom, amount), ) withdrawAndConvertBack := util.KavaMsgRequest{ - Msgs: []sdk.Msg{&withdraw, &convertBack}, + Msgs: []sdk.Msg{ /*&withdraw,*/ &convertBack}, GasLimit: 1e6, FeeAmount: sdk.NewCoins(ukava(1000)), Data: "withdrawing from mint & converting back to erc20", diff --git a/tests/e2e/e2e_upgrade_handler_test.go b/tests/e2e/e2e_upgrade_handler_test.go index b22569c7..8e1db1d4 100644 --- a/tests/e2e/e2e_upgrade_handler_test.go +++ b/tests/e2e/e2e_upgrade_handler_test.go @@ -3,7 +3,6 @@ package e2e_test import ( "time" - cdptypes "github.com/0glabs/0g-chain/x/cdp/types" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" tmtypes "github.com/cometbft/cometbft/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -99,25 +98,25 @@ func (suite *IntegrationTestSuite) TestUpgradeParams_Consensus() { suite.Require().Equal(expectedParams, *paramsAfter.Params, "x/consensus params after upgrade should be as expected") } -func (suite *IntegrationTestSuite) TestUpgradeParams_CDP_Interval() { - suite.SkipIfUpgradeDisabled() +// func (suite *IntegrationTestSuite) TestUpgradeParams_CDP_Interval() { +// suite.SkipIfUpgradeDisabled() - beforeUpgradeCtx := suite.Kava.Grpc.CtxAtHeight(suite.UpgradeHeight - 1) - afterUpgradeCtx := suite.Kava.Grpc.CtxAtHeight(suite.UpgradeHeight) +// beforeUpgradeCtx := suite.Kava.Grpc.CtxAtHeight(suite.UpgradeHeight - 1) +// afterUpgradeCtx := suite.Kava.Grpc.CtxAtHeight(suite.UpgradeHeight) - grpcClient := suite.Kava.Grpc +// grpcClient := suite.Kava.Grpc - paramsBefore, err := grpcClient.Query.Cdp.Params(beforeUpgradeCtx, &cdptypes.QueryParamsRequest{}) - suite.Require().NoError(err) - paramsAfter, err := grpcClient.Query.Cdp.Params(afterUpgradeCtx, &cdptypes.QueryParamsRequest{}) - suite.Require().NoError(err) +// paramsBefore, err := grpcClient.Query.Cdp.Params(beforeUpgradeCtx, &cdptypes.QueryParamsRequest{}) +// suite.Require().NoError(err) +// paramsAfter, err := grpcClient.Query.Cdp.Params(afterUpgradeCtx, &cdptypes.QueryParamsRequest{}) +// suite.Require().NoError(err) - expectedParams := paramsBefore.Params - expectedParams.LiquidationBlockInterval = int64(50) +// expectedParams := paramsBefore.Params +// expectedParams.LiquidationBlockInterval = int64(50) - suite.Require().Equal(expectedParams, paramsAfter.Params, - "expected cdp parameters to equal previous parameters with a liquidation block interval of 100") -} +// suite.Require().Equal(expectedParams, paramsAfter.Params, +// "expected cdp parameters to equal previous parameters with a liquidation block interval of 100") +// } func mustParseDuration(s string) *time.Duration { d, err := time.ParseDuration(s) diff --git a/tests/e2e/testutil/init_evm.go b/tests/e2e/testutil/init_evm.go index ed20e1a0..f13d1e4c 100644 --- a/tests/e2e/testutil/init_evm.go +++ b/tests/e2e/testutil/init_evm.go @@ -8,7 +8,6 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/0glabs/0g-chain/tests/e2e/contracts/greeter" - "github.com/0glabs/0g-chain/x/cdp/types" evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types" ) @@ -45,22 +44,22 @@ func (suite *E2eTestSuite) InitKavaEvmData() { } suite.Kava.RegisterErc20(suite.DeployedErc20.Address) - // expect the erc20's cosmos denom to be a supported cdp collateral type - cdpParams, err := suite.Kava.Grpc.Query.Cdp.Params(context.Background(), &types.QueryParamsRequest{}) - suite.Require().NoError(err) - found = false - for _, cp := range cdpParams.Params.CollateralParams { - if cp.Denom == suite.DeployedErc20.CosmosDenom { - found = true - suite.DeployedErc20.CdpCollateralType = cp.Type - } - } - if !found { - panic(fmt.Sprintf( - "erc20's cosmos denom %s must be valid cdp collateral type", - suite.DeployedErc20.CosmosDenom), - ) - } + // // expect the erc20's cosmos denom to be a supported cdp collateral type + // cdpParams, err := suite.Kava.Grpc.Query.Cdp.Params(context.Background(), &types.QueryParamsRequest{}) + // suite.Require().NoError(err) + // found = false + // for _, cp := range cdpParams.Params.CollateralParams { + // if cp.Denom == suite.DeployedErc20.CosmosDenom { + // found = true + // suite.DeployedErc20.CdpCollateralType = cp.Type + // } + // } + // if !found { + // panic(fmt.Sprintf( + // "erc20's cosmos denom %s must be valid cdp collateral type", + // suite.DeployedErc20.CosmosDenom), + // ) + // } // deploy an example contract greeterAddr, _, _, err := greeter.DeployGreeter( diff --git a/x/auction/abci.go b/x/auction/abci.go deleted file mode 100644 index 1756a83e..00000000 --- a/x/auction/abci.go +++ /dev/null @@ -1,23 +0,0 @@ -package auction - -import ( - "errors" - "time" - - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/auction/keeper" - "github.com/0glabs/0g-chain/x/auction/types" -) - -// BeginBlocker closes all expired auctions at the end of each block. It panics if -// there's an error other than ErrAuctionNotFound. -func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { - defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) - - err := k.CloseExpiredAuctions(ctx) - if err != nil && !errors.Is(err, types.ErrAuctionNotFound) { - panic(err) - } -} diff --git a/x/auction/abci_test.go b/x/auction/abci_test.go deleted file mode 100644 index 6083a440..00000000 --- a/x/auction/abci_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package auction_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/auction" - "github.com/0glabs/0g-chain/x/auction/testutil" - types "github.com/0glabs/0g-chain/x/auction/types" -) - -type abciTestSuite struct { - testutil.Suite -} - -func (suite *abciTestSuite) SetupTest() { - suite.Suite.SetupTest(4) -} - -func TestABCITestSuite(t *testing.T) { - suite.Run(t, new(abciTestSuite)) -} - -func (suite *abciTestSuite) TestKeeper_BeginBlocker() { - buyer := suite.Addrs[0] - returnAddrs := []sdk.AccAddress{suite.Addrs[1]} - returnWeights := []sdkmath.Int{sdkmath.NewInt(1)} - - suite.AddCoinsToNamedModule(suite.ModAcc.Name, cs(c("token1", 100), c("token2", 100), c("debt", 100))) - - // Start an auction and place a bid - auctionID, err := suite.Keeper.StartCollateralAuction(suite.Ctx, suite.ModAcc.Name, c("token1", 20), c("token2", 50), returnAddrs, returnWeights, c("debt", 40)) - suite.Require().NoError(err) - suite.Require().NoError(suite.Keeper.PlaceBid(suite.Ctx, auctionID, buyer, c("token2", 30))) - - // Run the beginblocker, simulating a block time 1ns before auction expiry - preExpiryTime := suite.Ctx.BlockTime().Add(types.DefaultForwardBidDuration - 1) - auction.BeginBlocker(suite.Ctx.WithBlockTime(preExpiryTime), suite.Keeper) - - // Check auction has not been closed yet - _, found := suite.Keeper.GetAuction(suite.Ctx, auctionID) - suite.True(found) - - // Run the endblocker, simulating a block time equal to auction expiry - expiryTime := suite.Ctx.BlockTime().Add(types.DefaultForwardBidDuration) - auction.BeginBlocker(suite.Ctx.WithBlockTime(expiryTime), suite.Keeper) - - // Check auction has been closed - _, found = suite.Keeper.GetAuction(suite.Ctx, auctionID) - suite.False(found) -} - -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } diff --git a/x/auction/client/cli/query.go b/x/auction/client/cli/query.go deleted file mode 100644 index 6a8e42bf..00000000 --- a/x/auction/client/cli/query.go +++ /dev/null @@ -1,212 +0,0 @@ -package cli - -import ( - "context" - "fmt" - "strconv" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/0glabs/0g-chain/x/auction/types" -) - -// GetQueryCmd returns the cli query commands for the auction module -func GetQueryCmd() *cobra.Command { - auctionQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: fmt.Sprintf("Querying commands for the %s module", types.ModuleName), - } - - cmds := []*cobra.Command{ - GetCmdQueryParams(), - GetCmdQueryAuction(), - GetCmdQueryAuctions(), - } - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - auctionQueryCmd.AddCommand(cmds...) - - return auctionQueryCmd -} - -// GetCmdQueryParams queries the issuance module parameters -func GetCmdQueryParams() *cobra.Command { - return &cobra.Command{ - Use: "params", - Short: fmt.Sprintf("get the %s module parameters", types.ModuleName), - Long: "Get the current auction module parameters.", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.Params(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - } -} - -// GetCmdQueryAuction queries one auction in the store -func GetCmdQueryAuction() *cobra.Command { - return &cobra.Command{ - Use: "auction [auction-id]", - Short: "get info about an auction", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - auctionID, err := strconv.Atoi(args[0]) - if err != nil { - return err - } - - params := types.QueryAuctionRequest{ - AuctionId: uint64(auctionID), - } - - res, err := queryClient.Auction(context.Background(), ¶ms) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -// Query auction flags -const ( - flagType = "type" - flagDenom = "denom" - flagPhase = "phase" - flagOwner = "owner" -) - -// GetCmdQueryAuctions queries the auctions in the store -func GetCmdQueryAuctions() *cobra.Command { - cmd := &cobra.Command{ - Use: "auctions", - Short: "query auctions with optional filters", - Long: "Query for all paginated auctions that match optional filters.", - Example: strings.Join([]string{ - fmt.Sprintf(" $ %s q %s auctions --type=(collateral|surplus|debt)", version.AppName, types.ModuleName), - fmt.Sprintf(" $ %s q %s auctions --owner=kava1hatdq32u5x4wnxrtv5wzjzmq49sxgjgsj0mffm", version.AppName, types.ModuleName), - fmt.Sprintf(" $ %s q %s auctions --denom=bnb", version.AppName, types.ModuleName), - fmt.Sprintf(" $ %s q %s auctions --phase=(forward|reverse)", version.AppName, types.ModuleName), - fmt.Sprintf(" $ %s q %s auctions --page=2 --limit=100", version.AppName, types.ModuleName), - }, "\n"), - RunE: func(cmd *cobra.Command, args []string) error { - auctionType, err := cmd.Flags().GetString(flagType) - if err != nil { - return err - } - owner, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - phase, err := cmd.Flags().GetString(flagPhase) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - if len(auctionType) != 0 { - auctionType = strings.ToLower(auctionType) - - if auctionType != types.CollateralAuctionType && - auctionType != types.SurplusAuctionType && - auctionType != types.DebtAuctionType { - return fmt.Errorf("invalid auction type %s", auctionType) - } - } - - if len(owner) != 0 { - if auctionType != types.CollateralAuctionType { - return fmt.Errorf("cannot apply owner flag to non-collateral auction type") - } - _, err := sdk.AccAddressFromBech32(owner) - if err != nil { - return fmt.Errorf("cannot parse address from auction owner %s", owner) - } - } - - if len(denom) != 0 { - err := sdk.ValidateDenom(denom) - if err != nil { - return err - } - } - - if len(phase) != 0 { - phase = strings.ToLower(phase) - - if len(auctionType) > 0 && auctionType != types.CollateralAuctionType { - return fmt.Errorf("cannot apply phase flag to non-collateral auction type") - } - if phase != types.ForwardAuctionPhase && phase != types.ReverseAuctionPhase { - return fmt.Errorf("invalid auction phase %s", phase) - } - } - - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - request := types.QueryAuctionsRequest{ - Type: auctionType, - Owner: owner, - Denom: denom, - Phase: phase, - Pagination: pageReq, - } - - res, err := queryClient.Auctions(context.Background(), &request) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddPaginationFlagsToCmd(cmd, "auctions") - - cmd.Flags().String(flagType, "", "(optional) filter by auction type, type: collateral, debt, surplus") - cmd.Flags().String(flagOwner, "", "(optional) filter by collateral auction owner") - cmd.Flags().String(flagDenom, "", "(optional) filter by auction denom") - cmd.Flags().String(flagPhase, "", "(optional) filter by collateral auction phase, phase: forward/reverse") - - return cmd -} diff --git a/x/auction/client/cli/tx.go b/x/auction/client/cli/tx.go deleted file mode 100644 index 1569919f..00000000 --- a/x/auction/client/cli/tx.go +++ /dev/null @@ -1,70 +0,0 @@ -package cli - -import ( - "fmt" - "strconv" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/0glabs/0g-chain/x/auction/types" -) - -// GetTxCmd returns the transaction cli commands for this module -func GetTxCmd() *cobra.Command { - txCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "transaction commands for the auction module", - } - - cmds := []*cobra.Command{ - GetCmdPlaceBid(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - txCmd.AddCommand(cmds...) - - return txCmd -} - -// GetCmdPlaceBid cli command for placing bids on auctions -func GetCmdPlaceBid() *cobra.Command { - return &cobra.Command{ - Use: "bid [auction-id] [amount]", - Short: "place a bid on an auction", - Long: "Place a bid on any type of auction, updating the latest bid amount to [amount]. Collateral auctions must be bid up to their maxbid before entering reverse phase.", - Example: fmt.Sprintf(" $ %s tx %s bid 34 1000usdx --from myKeyName", version.AppName, types.ModuleName), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - id, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return fmt.Errorf("auction-id '%s' not a valid uint", args[0]) - } - - amt, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - msg := types.NewMsgPlaceBid(id, clientCtx.GetFromAddress().String(), amt) - err = msg.ValidateBasic() - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} diff --git a/x/auction/genesis.go b/x/auction/genesis.go deleted file mode 100644 index 57bd0a64..00000000 --- a/x/auction/genesis.go +++ /dev/null @@ -1,74 +0,0 @@ -package auction - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/auction/keeper" - "github.com/0glabs/0g-chain/x/auction/types" -) - -// InitGenesis initializes the store state from a genesis state. -func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, bankKeeper types.BankKeeper, accountKeeper types.AccountKeeper, gs *types.GenesisState) { - if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) - } - - keeper.SetNextAuctionID(ctx, gs.NextAuctionId) - - keeper.SetParams(ctx, gs.Params) - - totalAuctionCoins := sdk.NewCoins() - - auctions, err := types.UnpackGenesisAuctions(gs.Auctions) - if err != nil { - panic(fmt.Sprintf("failed to unpack genesis auctions: %s", err)) - } - for _, a := range auctions { - keeper.SetAuction(ctx, a) - // find the total coins that should be present in the module account - totalAuctionCoins = totalAuctionCoins.Add(a.GetModuleAccountCoins()...) - } - - // check if the module account exists - moduleAcc := accountKeeper.GetModuleAccount(ctx, types.ModuleName) - if moduleAcc == nil { - panic(fmt.Sprintf("%s module account has not been set", types.ModuleName)) - } - - maccCoins := bankKeeper.GetAllBalances(ctx, moduleAcc.GetAddress()) - - // check module coins match auction coins - // Note: Other sdk modules do not check this, instead just using the existing module account coins, or if zero, setting them. - if !maccCoins.IsEqual(totalAuctionCoins) { - panic(fmt.Sprintf("total auction coins (%s) do not equal (%s) module account (%s) ", maccCoins, types.ModuleName, totalAuctionCoins)) - } -} - -// ExportGenesis returns a GenesisState for a given context and keeper. -func ExportGenesis(ctx sdk.Context, keeper keeper.Keeper) *types.GenesisState { - nextAuctionID, err := keeper.GetNextAuctionID(ctx) - if err != nil { - panic(err) - } - - params := keeper.GetParams(ctx) - - genAuctions := []types.GenesisAuction{} // return empty list instead of nil if no auctions - keeper.IterateAuctions(ctx, func(a types.Auction) bool { - ga, ok := a.(types.GenesisAuction) - if !ok { - panic("could not convert stored auction to GenesisAuction type") - } - genAuctions = append(genAuctions, ga) - return false - }) - - gs, err := types.NewGenesisState(nextAuctionID, params, genAuctions) - if err != nil { - panic(err) - } - - return gs -} diff --git a/x/auction/genesis_test.go b/x/auction/genesis_test.go deleted file mode 100644 index 09f24704..00000000 --- a/x/auction/genesis_test.go +++ /dev/null @@ -1,159 +0,0 @@ -package auction_test - -import ( - "sort" - "testing" - "time" - - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/auction" - "github.com/0glabs/0g-chain/x/auction/types" -) - -var ( - _, testAddrs = app.GeneratePrivKeyAddressPairs(2) - testTime = time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - testAuction = types.NewCollateralAuction( - "seller", - c("lotdenom", 10), - testTime, - c("biddenom", 1000), - types.WeightedAddresses{Addresses: testAddrs, Weights: []sdkmath.Int{sdk.OneInt(), sdk.OneInt()}}, - c("debt", 1000), - ).WithID(3).(types.GenesisAuction) -) - -func TestInitGenesis(t *testing.T) { - t.Run("valid", func(t *testing.T) { - // setup keepers - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - - // setup module account - modBaseAcc := authtypes.NewBaseAccount(authtypes.NewModuleAddress(types.ModuleName), nil, 0, 0) - modAcc := authtypes.NewModuleAccount(modBaseAcc, types.ModuleName, []string{authtypes.Minter, authtypes.Burner}...) - tApp.GetAccountKeeper().SetModuleAccount(ctx, modAcc) - tApp.GetBankKeeper().MintCoins(ctx, types.ModuleName, testAuction.GetModuleAccountCoins()) - - // set up auction genesis state with module account - auctionGS, err := types.NewGenesisState( - 10, - types.DefaultParams(), - []types.GenesisAuction{testAuction}, - ) - require.NoError(t, err) - - // run init - keeper := tApp.GetAuctionKeeper() - require.NotPanics(t, func() { - auction.InitGenesis(ctx, keeper, tApp.GetBankKeeper(), tApp.GetAccountKeeper(), auctionGS) - }) - - // check state is as expected - actualID, err := keeper.GetNextAuctionID(ctx) - require.NoError(t, err) - require.Equal(t, auctionGS.NextAuctionId, actualID) - - require.Equal(t, auctionGS.Params, keeper.GetParams(ctx)) - - genesisAuctions, err := types.UnpackGenesisAuctions(auctionGS.Auctions) - if err != nil { - panic(err) - } - - sort.Slice(genesisAuctions, func(i, j int) bool { - return genesisAuctions[i].GetID() > genesisAuctions[j].GetID() - }) - i := 0 - keeper.IterateAuctions(ctx, func(a types.Auction) bool { - require.Equal(t, genesisAuctions[i], a) - i++ - return false - }) - }) - t.Run("invalid (invalid nextAuctionID)", func(t *testing.T) { - // setup keepers - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - - // setup module account - modBaseAcc := authtypes.NewBaseAccount(authtypes.NewModuleAddress(types.ModuleName), nil, 0, 0) - modAcc := authtypes.NewModuleAccount(modBaseAcc, types.ModuleName, []string{authtypes.Minter, authtypes.Burner}...) - tApp.GetAccountKeeper().SetModuleAccount(ctx, modAcc) - tApp.GetBankKeeper().MintCoins(ctx, types.ModuleName, testAuction.GetModuleAccountCoins()) - - // create invalid genesis - auctionGS, err := types.NewGenesisState( - 0, // next id < testAuction ID - types.DefaultParams(), - []types.GenesisAuction{testAuction}, - ) - require.NoError(t, err) - - // check init fails - require.Panics(t, func() { - auction.InitGenesis(ctx, tApp.GetAuctionKeeper(), tApp.GetBankKeeper(), tApp.GetAccountKeeper(), auctionGS) - }) - }) - t.Run("invalid (missing mod account coins)", func(t *testing.T) { - // setup keepers - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - - // invalid as there is no module account setup - - // create invalid genesis - auctionGS, err := types.NewGenesisState( - 10, - types.DefaultParams(), - []types.GenesisAuction{testAuction}, - ) - require.NoError(t, err) - - // check init fails - require.Panics(t, func() { - auction.InitGenesis(ctx, tApp.GetAuctionKeeper(), tApp.GetBankKeeper(), tApp.GetAccountKeeper(), auctionGS) - }) - }) -} - -func TestExportGenesis(t *testing.T) { - t.Run("default", func(t *testing.T) { - // setup state - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - tApp.InitializeFromGenesisStates() - - // export - gs := auction.ExportGenesis(ctx, tApp.GetAuctionKeeper()) - - // check state matches - defaultGS := types.DefaultGenesisState() - require.Equal(t, defaultGS, gs) - }) - t.Run("one auction", func(t *testing.T) { - // setup state - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - tApp.InitializeFromGenesisStates() - tApp.GetAuctionKeeper().SetAuction(ctx, testAuction) - - // export - gs := auction.ExportGenesis(ctx, tApp.GetAuctionKeeper()) - - // check state matches - expectedGenesisState := types.DefaultGenesisState() - packedGenesisAuctions, err := types.PackGenesisAuctions([]types.GenesisAuction{testAuction}) - require.NoError(t, err) - - expectedGenesisState.Auctions = append(expectedGenesisState.Auctions, packedGenesisAuctions...) - require.Equal(t, expectedGenesisState, gs) - }) -} diff --git a/x/auction/keeper/auctions.go b/x/auction/keeper/auctions.go deleted file mode 100644 index e45b36be..00000000 --- a/x/auction/keeper/auctions.go +++ /dev/null @@ -1,583 +0,0 @@ -package keeper - -import ( - "errors" - "fmt" - "time" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - "github.com/0glabs/0g-chain/x/auction/types" -) - -// StartSurplusAuction starts a new surplus (forward) auction. -func (k Keeper) StartSurplusAuction(ctx sdk.Context, seller string, lot sdk.Coin, bidDenom string) (uint64, error) { - auction := types.NewSurplusAuction( - seller, - lot, - bidDenom, - types.DistantFuture, - ) - - // NOTE: for the duration of the auction the auction module account holds the lot - err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, seller, types.ModuleName, sdk.NewCoins(lot)) - if err != nil { - return 0, err - } - - auctionID, err := k.StoreNewAuction(ctx, &auction) - if err != nil { - return 0, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeAuctionStart, - sdk.NewAttribute(types.AttributeKeyAuctionID, fmt.Sprintf("%d", auctionID)), - sdk.NewAttribute(types.AttributeKeyAuctionType, auction.GetType()), - sdk.NewAttribute(types.AttributeKeyBid, auction.Bid.String()), - sdk.NewAttribute(types.AttributeKeyLot, auction.Lot.String()), - ), - ) - return auctionID, nil -} - -// StartDebtAuction starts a new debt (reverse) auction. -func (k Keeper) StartDebtAuction(ctx sdk.Context, buyer string, bid sdk.Coin, initialLot sdk.Coin, debt sdk.Coin) (uint64, error) { - auction := types.NewDebtAuction( - buyer, - bid, - initialLot, - types.DistantFuture, - debt, - ) - - // This auction type mints coins at close. Need to check module account has minting privileges to avoid potential err in endblocker. - macc := k.accountKeeper.GetModuleAccount(ctx, buyer) - if !macc.HasPermission(authtypes.Minter) { - panic(fmt.Errorf("module '%s' does not have '%s' permission", buyer, authtypes.Minter)) - } - - // NOTE: for the duration of the auction the auction module account holds the debt - err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, buyer, types.ModuleName, sdk.NewCoins(debt)) - if err != nil { - return 0, err - } - - auctionID, err := k.StoreNewAuction(ctx, &auction) - if err != nil { - return 0, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeAuctionStart, - sdk.NewAttribute(types.AttributeKeyAuctionID, fmt.Sprintf("%d", auctionID)), - sdk.NewAttribute(types.AttributeKeyAuctionType, auction.GetType()), - sdk.NewAttribute(types.AttributeKeyBid, auction.Bid.String()), - sdk.NewAttribute(types.AttributeKeyLot, auction.Lot.String()), - ), - ) - return auctionID, nil -} - -// 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 []sdkmath.Int, debt sdk.Coin, -) (uint64, error) { - weightedAddresses, err := types.NewWeightedAddresses(lotReturnAddrs, lotReturnWeights) - if err != nil { - return 0, err - } - auction := types.NewCollateralAuction( - seller, - lot, - types.DistantFuture, - maxBid, - weightedAddresses, - debt, - ) - - // NOTE: for the duration of the auction the auction module account holds the debt and the lot - err = k.bankKeeper.SendCoinsFromModuleToModule(ctx, seller, types.ModuleName, sdk.NewCoins(lot)) - if err != nil { - return 0, err - } - err = k.bankKeeper.SendCoinsFromModuleToModule(ctx, seller, types.ModuleName, sdk.NewCoins(debt)) - if err != nil { - return 0, err - } - - auctionID, err := k.StoreNewAuction(ctx, &auction) - if err != nil { - return 0, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeAuctionStart, - sdk.NewAttribute(types.AttributeKeyAuctionID, fmt.Sprintf("%d", auctionID)), - sdk.NewAttribute(types.AttributeKeyAuctionType, auction.GetType()), - sdk.NewAttribute(types.AttributeKeyBid, auction.Bid.String()), - sdk.NewAttribute(types.AttributeKeyLot, auction.Lot.String()), - sdk.NewAttribute(types.AttributeKeyMaxBid, auction.MaxBid.String()), - ), - ) - return auctionID, nil -} - -// PlaceBid places a bid on any auction. -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 errorsmod.Wrapf(types.ErrAuctionNotFound, "%d", auctionID) - } - - // validation common to all auctions - if ctx.BlockTime().After(auction.GetEndTime()) { - return errorsmod.Wrapf(types.ErrAuctionHasExpired, "%d", auctionID) - } - - // move coins and return updated auction - var ( - err error - updatedAuction types.Auction - ) - switch auctionType := auction.(type) { - case *types.SurplusAuction: - updatedAuction, err = k.PlaceBidSurplus(ctx, auctionType, bidder, newAmount) - case *types.DebtAuction: - updatedAuction, err = k.PlaceBidDebt(ctx, auctionType, bidder, newAmount) - case *types.CollateralAuction: - if !auctionType.IsReversePhase() { - updatedAuction, err = k.PlaceForwardBidCollateral(ctx, auctionType, bidder, newAmount) - } else { - updatedAuction, err = k.PlaceReverseBidCollateral(ctx, auctionType, bidder, newAmount) - } - default: - err = errorsmod.Wrap(types.ErrUnrecognizedAuctionType, auction.GetType()) - } - - if err != nil { - return err - } - - k.SetAuction(ctx, updatedAuction) - - return nil -} - -// PlaceBidSurplus places a forward bid on a surplus auction, moving coins and returning the updated auction. -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, 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( - sdkmath.NewInt(1), - sdk.NewDecFromInt(auction.Bid.Amount).Mul(k.GetParams(ctx).IncrementSurplus).RoundInt(), - ), - ) - if bid.Amount.LT(minNewBidAmt) { - return auction, errorsmod.Wrapf(types.ErrBidTooSmall, "%s < %s%s", bid, minNewBidAmt, auction.Bid.Denom) - } - - // New bidder pays back old bidder - // Catch edge cases of a bidder replacing their own bid, or the amount being zero (sending zero coins produces meaningless send events). - if !bidder.Equals(auction.Bidder) && !auction.Bid.IsZero() { // bidder isn't same as before AND previous auction bid must exist - err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, bidder, types.ModuleName, sdk.NewCoins(auction.Bid)) - if err != nil { - return auction, err - } - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, auction.Bidder, sdk.NewCoins(auction.Bid)) - if err != nil { - return auction, err - } - } - - err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, bidder, auction.Initiator, sdk.NewCoins(bid.Sub(auction.Bid))) - if err != nil { - return auction, err - } - - // Received bid amount is burned from the module account - err = k.bankKeeper.BurnCoins(ctx, auction.Initiator, sdk.NewCoins(bid.Sub(auction.Bid))) - if err != nil { - return auction, err - } - - // Update Auction - auction.Bidder = bidder - auction.Bid = bid - if !auction.HasReceivedBids { - auction.MaxEndTime = ctx.BlockTime().Add(k.GetParams(ctx).MaxAuctionDuration) // set maximum ending time on receipt of first bid - auction.HasReceivedBids = true - } - auction.EndTime = earliestTime(ctx.BlockTime().Add(k.GetParams(ctx).ForwardBidDuration), auction.MaxEndTime) // increment timeout, up to MaxEndTime - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeAuctionBid, - sdk.NewAttribute(types.AttributeKeyAuctionID, fmt.Sprintf("%d", auction.ID)), - sdk.NewAttribute(types.AttributeKeyBidder, auction.Bidder.String()), - sdk.NewAttribute(types.AttributeKeyBid, auction.Bid.String()), - sdk.NewAttribute(types.AttributeKeyEndTime, fmt.Sprintf("%d", auction.EndTime.Unix())), - ), - ) - - return auction, nil -} - -// PlaceForwardBidCollateral places a forward bid on a collateral auction, moving coins and returning the updated auction. -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, 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( - 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, errorsmod.Wrapf(types.ErrBidTooSmall, "%s < %s%s", bid, minNewBidAmt, auction.Bid.Denom) - } - if auction.MaxBid.IsLT(bid) { - return auction, errorsmod.Wrapf(types.ErrBidTooLarge, "%s > %s", bid, auction.MaxBid) - } - - // New bidder pays back old bidder - // Catch edge cases of a bidder replacing their own bid, and the amount being zero (sending zero coins produces meaningless send events). - if !bidder.Equals(auction.Bidder) && !auction.Bid.IsZero() { - err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, bidder, types.ModuleName, sdk.NewCoins(auction.Bid)) - if err != nil { - return auction, err - } - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, auction.Bidder, sdk.NewCoins(auction.Bid)) - if err != nil { - return auction, err - } - } - // Increase in bid sent to auction initiator - bidIncrement := bid.Sub(auction.Bid) - err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, bidder, auction.Initiator, sdk.NewCoins(bidIncrement)) - if err != nil { - return auction, err - } - // Debt coins are sent to liquidator (until there is no CorrespondingDebt left). Amount sent is equal to bidIncrement (or whatever is left if < bidIncrement). - if auction.CorrespondingDebt.IsPositive() { - - debtAmountToReturn := sdk.MinInt(bidIncrement.Amount, auction.CorrespondingDebt.Amount) - debtToReturn := sdk.NewCoin(auction.CorrespondingDebt.Denom, debtAmountToReturn) - - err = k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, auction.Initiator, sdk.NewCoins(debtToReturn)) - if err != nil { - return auction, err - } - auction.CorrespondingDebt = auction.CorrespondingDebt.Sub(debtToReturn) // debtToReturn will always be ≤ auction.CorrespondingDebt from the MinInt above - } - - // Update Auction - auction.Bidder = bidder - auction.Bid = bid - if !auction.HasReceivedBids { - auction.MaxEndTime = ctx.BlockTime().Add(k.GetParams(ctx).MaxAuctionDuration) // set maximum ending time on receipt of first bid - auction.HasReceivedBids = true - } - - // If this forward bid converts this to a reverse, increase timeout with ReverseBidDuration - if auction.IsReversePhase() { - auction.EndTime = earliestTime(ctx.BlockTime().Add(k.GetParams(ctx).ReverseBidDuration), auction.MaxEndTime) // increment timeout, up to MaxEndTime - } else { - auction.EndTime = earliestTime(ctx.BlockTime().Add(k.GetParams(ctx).ForwardBidDuration), auction.MaxEndTime) // increment timeout, up to MaxEndTime - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeAuctionBid, - sdk.NewAttribute(types.AttributeKeyAuctionID, fmt.Sprintf("%d", auction.ID)), - sdk.NewAttribute(types.AttributeKeyBidder, auction.Bidder.String()), - sdk.NewAttribute(types.AttributeKeyBid, auction.Bid.String()), - sdk.NewAttribute(types.AttributeKeyEndTime, fmt.Sprintf("%d", auction.EndTime.Unix())), - ), - ) - - return auction, nil -} - -// PlaceReverseBidCollateral places a reverse bid on a collateral auction, moving coins and returning the updated auction. -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, 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( - sdkmath.NewInt(1), - sdk.NewDecFromInt(auction.Lot.Amount).Mul(k.GetParams(ctx).IncrementCollateral).RoundInt(), - ), - ) - if lot.Amount.GT(maxNewLotAmt) { - return auction, errorsmod.Wrapf(types.ErrLotTooLarge, "%s > %s%s", lot, maxNewLotAmt, auction.Lot.Denom) - } - if lot.IsNegative() { - return auction, errorsmod.Wrapf(types.ErrLotTooSmall, "%s < 0%s", lot, auction.Lot.Denom) - } - - // New bidder pays back old bidder - // Catch edge cases of a bidder replacing their own bid - if !bidder.Equals(auction.Bidder) { - err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, bidder, types.ModuleName, sdk.NewCoins(auction.Bid)) - if err != nil { - return auction, err - } - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, auction.Bidder, sdk.NewCoins(auction.Bid)) - if err != nil { - return auction, err - } - } - - // Decrease in lot is sent to weighted addresses (normally the CDP depositors) - // Note: splitting an integer amount across weighted buckets results in small errors. - lotPayouts, err := splitCoinIntoWeightedBuckets(auction.Lot.Sub(lot), auction.LotReturns.Weights) - if err != nil { - return auction, err - } - for i, payout := range lotPayouts { - // if the payout amount is 0, don't send 0 coins - if !payout.IsPositive() { - continue - } - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, auction.LotReturns.Addresses[i], sdk.NewCoins(payout)) - if err != nil { - return auction, err - } - } - - // Update Auction - auction.Bidder = bidder - auction.Lot = lot - if !auction.HasReceivedBids { - auction.MaxEndTime = ctx.BlockTime().Add(k.GetParams(ctx).MaxAuctionDuration) // set maximum ending time on receipt of first bid - auction.HasReceivedBids = true - } - auction.EndTime = earliestTime(ctx.BlockTime().Add(k.GetParams(ctx).ReverseBidDuration), auction.MaxEndTime) // increment timeout, up to MaxEndTime - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeAuctionBid, - sdk.NewAttribute(types.AttributeKeyAuctionID, fmt.Sprintf("%d", auction.ID)), - sdk.NewAttribute(types.AttributeKeyBidder, auction.Bidder.String()), - sdk.NewAttribute(types.AttributeKeyLot, auction.Lot.String()), - sdk.NewAttribute(types.AttributeKeyEndTime, fmt.Sprintf("%d", auction.EndTime.Unix())), - ), - ) - - return auction, nil -} - -// PlaceBidDebt places a reverse bid on a debt auction, moving coins and returning the updated auction. -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, 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( - sdkmath.NewInt(1), - sdk.NewDecFromInt(auction.Lot.Amount).Mul(k.GetParams(ctx).IncrementDebt).RoundInt(), - ), - ) - if lot.Amount.GT(maxNewLotAmt) { - return auction, errorsmod.Wrapf(types.ErrLotTooLarge, "%s > %s%s", lot, maxNewLotAmt, auction.Lot.Denom) - } - if lot.IsNegative() { - return auction, errorsmod.Wrapf(types.ErrLotTooSmall, "%s ≤ %s%s", lot, sdk.ZeroInt(), auction.Lot.Denom) - } - - // New bidder pays back old bidder - // Catch edge cases of a bidder replacing their own bid - if !bidder.Equals(auction.Bidder) { - // Bidder sends coins to module - err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, bidder, types.ModuleName, sdk.NewCoins(auction.Bid)) - if err != nil { - return auction, err - } - // Coins are sent from module to old bidder - oldBidder := auction.Bidder - if oldBidder.Equals(authtypes.NewModuleAddress(auction.Initiator)) { // First bid on auction (where there is no previous bidder) - err = k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, auction.Initiator, sdk.NewCoins(auction.Bid)) - } else { // Second and later bids on auction (where previous bidder is a user account) - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, oldBidder, sdk.NewCoins(auction.Bid)) - } - if err != nil { - return auction, err - } - } - - // Debt coins are sent to liquidator the first time a bid is placed. Amount sent is equal to min of Bid and amount of debt. - if auction.Bidder.Equals(authtypes.NewModuleAddress(auction.Initiator)) { - // Handle debt coins for first bid - debtAmountToReturn := sdk.MinInt(auction.Bid.Amount, auction.CorrespondingDebt.Amount) - debtToReturn := sdk.NewCoin(auction.CorrespondingDebt.Denom, debtAmountToReturn) - - err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, auction.Initiator, sdk.NewCoins(debtToReturn)) - if err != nil { - return auction, err - } - auction.CorrespondingDebt = auction.CorrespondingDebt.Sub(debtToReturn) // debtToReturn will always be ≤ auction.CorrespondingDebt from the MinInt above - } - - // Update Auction - auction.Bidder = bidder - auction.Lot = lot - if !auction.HasReceivedBids { - auction.MaxEndTime = ctx.BlockTime().Add(k.GetParams(ctx).MaxAuctionDuration) // set maximum ending time on receipt of first bid - auction.HasReceivedBids = true - } - auction.EndTime = earliestTime(ctx.BlockTime().Add(k.GetParams(ctx).ForwardBidDuration), auction.MaxEndTime) // increment timeout, up to MaxEndTime - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeAuctionBid, - sdk.NewAttribute(types.AttributeKeyAuctionID, fmt.Sprintf("%d", auction.ID)), - sdk.NewAttribute(types.AttributeKeyBidder, auction.Bidder.String()), - sdk.NewAttribute(types.AttributeKeyLot, auction.Lot.String()), - sdk.NewAttribute(types.AttributeKeyEndTime, fmt.Sprintf("%d", auction.EndTime.Unix())), - ), - ) - - return auction, nil -} - -// CloseAuction closes an auction and distributes funds to the highest bidder. -func (k Keeper) CloseAuction(ctx sdk.Context, auctionID uint64) error { - auction, found := k.GetAuction(ctx, auctionID) - if !found { - return errorsmod.Wrapf(types.ErrAuctionNotFound, "%d", auctionID) - } - - if ctx.BlockTime().Before(auction.GetEndTime()) { - return errorsmod.Wrapf(types.ErrAuctionHasNotExpired, "block time %s, auction end time %s", ctx.BlockTime().UTC(), auction.GetEndTime().UTC()) - } - - // payout to the last bidder - var err error - switch auc := auction.(type) { - case *types.SurplusAuction: - err = k.PayoutSurplusAuction(ctx, auc) - case *types.DebtAuction: - err = k.PayoutDebtAuction(ctx, auc) - case *types.CollateralAuction: - err = k.PayoutCollateralAuction(ctx, auc) - default: - err = errorsmod.Wrap(types.ErrUnrecognizedAuctionType, auc.GetType()) - } - - if err != nil { - return err - } - - k.DeleteAuction(ctx, auctionID) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeAuctionClose, - sdk.NewAttribute(types.AttributeKeyAuctionID, fmt.Sprintf("%d", auctionID)), - sdk.NewAttribute(types.AttributeKeyCloseBlock, fmt.Sprintf("%d", ctx.BlockHeight())), - ), - ) - return nil -} - -// PayoutDebtAuction pays out the proceeds for a debt auction, first minting the coins. -func (k Keeper) PayoutDebtAuction(ctx sdk.Context, auction *types.DebtAuction) error { - // create the coins that are needed to pay off the debt - err := k.bankKeeper.MintCoins(ctx, auction.Initiator, sdk.NewCoins(auction.Lot)) - if err != nil { - panic(fmt.Errorf("could not mint coins: %w", err)) - } - // send the new coins from the initiator module to the bidder - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, auction.Initiator, auction.Bidder, sdk.NewCoins(auction.Lot)) - if err != nil { - return err - } - // if there is remaining debt, return it to the calling module to manage - if !auction.CorrespondingDebt.IsPositive() { - return nil - } - - return k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, auction.Initiator, sdk.NewCoins(auction.CorrespondingDebt)) -} - -// PayoutSurplusAuction pays out the proceeds for a surplus auction. -func (k Keeper) PayoutSurplusAuction(ctx sdk.Context, auction *types.SurplusAuction) error { - // Send the tokens from the auction module account where they are being managed to the bidder who won the auction - return k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, auction.Bidder, sdk.NewCoins(auction.Lot)) -} - -// PayoutCollateralAuction pays out the proceeds for a collateral auction. -func (k Keeper) PayoutCollateralAuction(ctx sdk.Context, auction *types.CollateralAuction) error { - // Send the tokens from the auction module account where they are being managed to the bidder who won the auction - err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, auction.Bidder, sdk.NewCoins(auction.Lot)) - if err != nil { - return err - } - - // if there is remaining debt after the auction, send it back to the initiating module for management - if !auction.CorrespondingDebt.IsPositive() { - return nil - } - - return k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, auction.Initiator, sdk.NewCoins(auction.CorrespondingDebt)) -} - -// CloseExpiredAuctions iterates over all the auctions stored by until the current -// block timestamp and that are past (or at) their ending times and closes them, -// paying out to the highest bidder. -func (k Keeper) CloseExpiredAuctions(ctx sdk.Context) error { - var err error - k.IterateAuctionsByTime(ctx, ctx.BlockTime(), func(id uint64) (stop bool) { - err = k.CloseAuction(ctx, id) - if err != nil && !errors.Is(err, types.ErrAuctionNotFound) { - // stop iteration - return true - } - // reset error in case the last element had an ErrAuctionNotFound - err = nil - return false - }) - - return err -} - -// earliestTime returns the earliest of two times. -func earliestTime(t1, t2 time.Time) time.Time { - if t1.Before(t2) { - return t1 - } - return t2 // also returned if times are equal -} - -// splitCoinIntoWeightedBuckets divides up some amount of coins according to some weights. -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 { - result[i] = sdk.NewCoin(coin.Denom, a) - } - return result, nil -} diff --git a/x/auction/keeper/auctions_test.go b/x/auction/keeper/auctions_test.go deleted file mode 100644 index a159f7b8..00000000 --- a/x/auction/keeper/auctions_test.go +++ /dev/null @@ -1,319 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - "github.com/0glabs/0g-chain/x/auction/testutil" - "github.com/0glabs/0g-chain/x/auction/types" -) - -type auctionTestSuite struct { - testutil.Suite -} - -func (suite *auctionTestSuite) SetupTest() { - suite.Suite.SetupTest(4) -} - -func TestAuctionTestSuite(t *testing.T) { - suite.Run(t, new(auctionTestSuite)) -} - -func (suite *auctionTestSuite) TestSurplusAuctionBasic() { - buyer := suite.Addrs[0] - - // TODO: use cdp.LiquidatorMacc once CDP module is available - // sellerModName := cdp.LiquidatorMacc - sellerAddr := authtypes.NewModuleAddress(suite.ModAcc.Name) - suite.AddCoinsToNamedModule(suite.ModAcc.Name, cs(c("token1", 100), c("token2", 100))) - - // Create an auction (lot: 20 token1, initialBid: 0 token2) - auctionID, err := suite.Keeper.StartSurplusAuction(suite.Ctx, suite.ModAcc.Name, c("token1", 20), "token2") // lobid denom - suite.NoError(err) - // Check seller's coins have decreased - suite.CheckAccountBalanceEqual(sellerAddr, cs(c("token1", 80), c("token2", 100))) - - // PlaceBid (bid: 10 token, lot: same as starting) - suite.NoError(suite.Keeper.PlaceBid(suite.Ctx, auctionID, buyer, c("token2", 10))) - // Check buyer's coins have decreased - suite.CheckAccountBalanceEqual(buyer, cs(c("token1", 100), c("token2", 90))) - // Check seller's coins have not increased (because proceeds are burned) - suite.CheckAccountBalanceEqual(sellerAddr, cs(c("token1", 80), c("token2", 100))) - - // increment bid same bidder - err = suite.Keeper.PlaceBid(suite.Ctx, auctionID, buyer, c("token2", 20)) - suite.NoError(err) - - // Close auction just at auction expiry time - suite.Ctx = suite.Ctx.WithBlockTime(suite.Ctx.BlockTime().Add(types.DefaultForwardBidDuration)) - suite.NoError(suite.Keeper.CloseAuction(suite.Ctx, auctionID)) - // Check buyer's coins increased - suite.CheckAccountBalanceEqual(buyer, cs(c("token1", 120), c("token2", 80))) -} - -func (suite *auctionTestSuite) TestDebtAuctionBasic() { - // Setup - seller := suite.Addrs[0] - suite.AddCoinsToNamedModule(suite.ModAcc.Name, cs(c("debt", 100))) - - // Start auction - auctionID, err := suite.Keeper.StartDebtAuction(suite.Ctx, suite.ModAcc.Name, c("token1", 20), c("token2", 99999), c("debt", 20)) - suite.NoError(err) - // Check buyer's coins have not decreased (except for debt), as lot is minted at the end - suite.CheckAccountBalanceEqual(suite.ModAcc.GetAddress(), cs(c("debt", 80))) - - // Place a bid - suite.NoError(suite.Keeper.PlaceBid(suite.Ctx, auctionID, seller, c("token2", 10))) - - // Check seller's coins have decreased - suite.CheckAccountBalanceEqual(seller, cs(c("token1", 80), c("token2", 100))) - // Check buyer's coins have increased - suite.CheckAccountBalanceEqual(suite.ModAcc.GetAddress(), cs(c("token1", 20), c("debt", 100))) - - // Close auction at just after auction expiry - ctx := suite.Ctx.WithBlockTime(suite.Ctx.BlockTime().Add(types.DefaultForwardBidDuration)) - suite.NoError(suite.Keeper.CloseAuction(ctx, auctionID)) - // Check seller's coins increased - suite.CheckAccountBalanceEqual(seller, cs(c("token1", 80), c("token2", 110))) -} - -func (suite *auctionTestSuite) TestDebtAuctionDebtRemaining() { - seller := suite.Addrs[0] - - buyerAddr := authtypes.NewModuleAddress(suite.ModAcc.Name) - suite.AddCoinsToNamedModule(suite.ModAcc.Name, cs(c("debt", 100))) - - // Start auction - auctionID, err := suite.Keeper.StartDebtAuction(suite.Ctx, suite.ModAcc.Name, c("token1", 10), c("token2", 99999), c("debt", 20)) - suite.NoError(err) - // Check buyer's coins have not decreased (except for debt), as lot is minted at the end - suite.CheckAccountBalanceEqual(buyerAddr, cs(c("debt", 80))) - - // Place a bid - suite.NoError(suite.Keeper.PlaceBid(suite.Ctx, auctionID, seller, c("token2", 10))) - // Check seller's coins have decreased - suite.CheckAccountBalanceEqual(seller, cs(c("token1", 90), c("token2", 100))) - // Check buyer's coins have increased - suite.CheckAccountBalanceEqual(buyerAddr, cs(c("token1", 10), c("debt", 90))) - - // Close auction at just after auction expiry - ctx := suite.Ctx.WithBlockTime(suite.Ctx.BlockTime().Add(types.DefaultForwardBidDuration)) - suite.NoError(suite.Keeper.CloseAuction(ctx, auctionID)) - // Check seller's coins increased - suite.CheckAccountBalanceEqual(seller, cs(c("token1", 90), c("token2", 110))) - // check that debt has increased due to corresponding debt being greater than bid - suite.CheckAccountBalanceEqual(buyerAddr, cs(c("token1", 10), c("debt", 100))) -} - -func (suite *auctionTestSuite) TestCollateralAuctionBasic() { - // Setup - buyer := suite.Addrs[0] - returnAddrs := suite.Addrs[1:] - returnWeights := is(30, 20, 10) - sellerModName := suite.ModAcc.Name - sellerAddr := suite.ModAcc.GetAddress() - suite.AddCoinsToNamedModule(sellerModName, cs(c("token1", 100), c("token2", 100), c("debt", 100))) - - // Start auction - auctionID, err := suite.Keeper.StartCollateralAuction(suite.Ctx, sellerModName, c("token1", 20), c("token2", 50), returnAddrs, returnWeights, c("debt", 40)) - suite.NoError(err) - // Check seller's coins have decreased - suite.CheckAccountBalanceEqual(sellerAddr, cs(c("token1", 80), c("token2", 100), c("debt", 60))) - - // Place a forward bid - suite.NoError(suite.Keeper.PlaceBid(suite.Ctx, auctionID, buyer, c("token2", 10))) - // Check bidder's coins have decreased - suite.CheckAccountBalanceEqual(buyer, cs(c("token1", 100), c("token2", 90))) - // Check seller's coins have increased - suite.CheckAccountBalanceEqual(sellerAddr, cs(c("token1", 80), c("token2", 110), c("debt", 70))) - // Check return addresses have not received coins - for _, ra := range suite.Addrs[1:] { - suite.CheckAccountBalanceEqual(ra, cs(c("token1", 100), c("token2", 100))) - } - - // Place a reverse bid - suite.NoError(suite.Keeper.PlaceBid(suite.Ctx, auctionID, buyer, c("token2", 50))) // first bid up to max bid to switch phases - suite.NoError(suite.Keeper.PlaceBid(suite.Ctx, auctionID, buyer, c("token1", 15))) - // Check bidder's coins have decreased - suite.CheckAccountBalanceEqual(buyer, cs(c("token1", 100), c("token2", 50))) - // Check seller's coins have increased - suite.CheckAccountBalanceEqual(sellerAddr, cs(c("token1", 80), c("token2", 150), c("debt", 100))) - // Check return addresses have received coins - suite.CheckAccountBalanceEqual(suite.Addrs[1], cs(c("token1", 102), c("token2", 100))) - suite.CheckAccountBalanceEqual(suite.Addrs[2], cs(c("token1", 102), c("token2", 100))) - suite.CheckAccountBalanceEqual(suite.Addrs[3], cs(c("token1", 101), c("token2", 100))) - - // Close auction at just after auction expiry - ctx := suite.Ctx.WithBlockTime(suite.Ctx.BlockTime().Add(types.DefaultReverseBidDuration)) - suite.NoError(suite.Keeper.CloseAuction(ctx, auctionID)) - // Check buyer's coins increased - suite.CheckAccountBalanceEqual(buyer, cs(c("token1", 115), c("token2", 50))) -} - -func (suite *auctionTestSuite) TestCollateralAuctionDebtRemaining() { - // Setup - buyer := suite.Addrs[0] - returnAddrs := suite.Addrs[1:] - returnWeights := is(30, 20, 10) - sellerModName := suite.ModAcc.Name - sellerAddr := suite.ModAcc.GetAddress() - suite.AddCoinsToNamedModule(sellerModName, cs(c("token1", 100), c("token2", 100), c("debt", 100))) - - // Start auction - auctionID, err := suite.Keeper.StartCollateralAuction(suite.Ctx, sellerModName, c("token1", 20), c("token2", 50), returnAddrs, returnWeights, c("debt", 40)) - suite.NoError(err) - // Check seller's coins have decreased - suite.CheckAccountBalanceEqual(sellerAddr, cs(c("token1", 80), c("token2", 100), c("debt", 60))) - - // Place a forward bid - suite.NoError(suite.Keeper.PlaceBid(suite.Ctx, auctionID, buyer, c("token2", 10))) - // Check bidder's coins have decreased - suite.CheckAccountBalanceEqual(buyer, cs(c("token1", 100), c("token2", 90))) - // Check seller's coins have increased - suite.CheckAccountBalanceEqual(sellerAddr, cs(c("token1", 80), c("token2", 110), c("debt", 70))) - // Check return addresses have not received coins - for _, ra := range suite.Addrs[1:] { - suite.CheckAccountBalanceEqual(ra, cs(c("token1", 100), c("token2", 100))) - } - ctx := suite.Ctx.WithBlockTime(suite.Ctx.BlockTime().Add(types.DefaultForwardBidDuration)) - suite.NoError(suite.Keeper.CloseAuction(ctx, auctionID)) - - // check that buyers coins have increased - suite.CheckAccountBalanceEqual(buyer, cs(c("token1", 120), c("token2", 90))) - // Check return addresses have not received coins - for _, ra := range suite.Addrs[1:] { - suite.CheckAccountBalanceEqual(ra, cs(c("token1", 100), c("token2", 100))) - } - // check that token2 has increased by 10, debt by 40, for a net debt increase of 30 debt - suite.CheckAccountBalanceEqual(sellerAddr, cs(c("token1", 80), c("token2", 110), c("debt", 100))) -} - -func (suite *auctionTestSuite) TestStartSurplusAuction() { - someTime := time.Date(1998, time.January, 1, 0, 0, 0, 0, time.UTC) - type args struct { - seller string - lot sdk.Coin - bidDenom string - } - testCases := []struct { - name string - blockTime time.Time - args args - expectPass bool - expPanic bool - }{ - { - "normal", - someTime, - args{suite.ModAcc.Name, c("stable", 10), "gov"}, - true, false, - }, - { - "no module account", - someTime, - args{"nonExistentModule", c("stable", 10), "gov"}, - false, true, - }, - { - "not enough coins", - someTime, - args{suite.ModAcc.Name, c("stable", 101), "gov"}, - false, false, - }, - { - "incorrect denom", - someTime, - args{suite.ModAcc.Name, c("notacoin", 10), "gov"}, - false, false, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - // setup - initialLiquidatorCoins := cs(c("stable", 100)) - suite.AddCoinsToNamedModule(suite.ModAcc.Name, initialLiquidatorCoins) - - // run function under test - var ( - id uint64 - err error - ) - if tc.expPanic { - suite.Panics(func() { - _, _ = suite.Keeper.StartSurplusAuction(suite.Ctx, tc.args.seller, tc.args.lot, tc.args.bidDenom) - }, tc.name) - } else { - id, err = suite.Keeper.StartSurplusAuction(suite.Ctx, tc.args.seller, tc.args.lot, tc.args.bidDenom) - } - - // check - liquidatorCoins := suite.BankKeeper.GetAllBalances(suite.Ctx, suite.ModAcc.GetAddress()) - actualAuc, found := suite.Keeper.GetAuction(suite.Ctx, id) - if tc.expectPass { - suite.NoError(err, tc.name) - // check coins moved - suite.Equal(initialLiquidatorCoins.Sub(tc.args.lot), liquidatorCoins, tc.name) - // check auction in store and is correct - suite.True(found, tc.name) - - surplusAuction := types.SurplusAuction{BaseAuction: types.BaseAuction{ - ID: id, - Initiator: tc.args.seller, - Lot: tc.args.lot, - Bidder: nil, - Bid: c(tc.args.bidDenom, 0), - HasReceivedBids: false, - EndTime: types.DistantFuture, - MaxEndTime: types.DistantFuture, - }} - suite.Equal(&surplusAuction, actualAuc, tc.name) - } else if !tc.expPanic && !tc.expectPass { - suite.Error(err, tc.name) - // check coins not moved - suite.Equal(initialLiquidatorCoins, liquidatorCoins, tc.name) - // check auction not in store - suite.False(found, tc.name) - } - }) - } -} - -func (suite *auctionTestSuite) TestCloseAuction() { - suite.AddCoinsToNamedModule(suite.ModAcc.Name, cs(c("token1", 100), c("token2", 100))) - - // Create an auction (lot: 20 token1, initialBid: 0 token2) - id, err := suite.Keeper.StartSurplusAuction(suite.Ctx, suite.ModAcc.Name, c("token1", 20), "token2") // lot, bid denom - suite.NoError(err) - - // Attempt to close the auction before EndTime - suite.Error(suite.Keeper.CloseAuction(suite.Ctx, id)) - - // Attempt to close auction that does not exist - suite.Error(suite.Keeper.CloseAuction(suite.Ctx, 999)) -} - -func (suite *auctionTestSuite) TestCloseExpiredAuctions() { - suite.AddCoinsToNamedModule(suite.ModAcc.Name, cs(c("token1", 100), c("token2", 100))) - - // Start auction 1 - _, err := suite.Keeper.StartSurplusAuction(suite.Ctx, suite.ModAcc.Name, c("token1", 20), "token2") // lot, bid denom - suite.NoError(err) - - // Start auction 2 - _, err = suite.Keeper.StartSurplusAuction(suite.Ctx, suite.ModAcc.Name, c("token1", 20), "token2") // lot, bid denom - suite.NoError(err) - - // Fast forward the block time - ctx := suite.Ctx.WithBlockTime(suite.Ctx.BlockTime().Add(types.DefaultMaxAuctionDuration).Add(1)) - - // Close expired auctions - err = suite.Keeper.CloseExpiredAuctions(ctx) - suite.NoError(err) -} diff --git a/x/auction/keeper/bidding_test.go b/x/auction/keeper/bidding_test.go deleted file mode 100644 index 3c0069d5..00000000 --- a/x/auction/keeper/bidding_test.go +++ /dev/null @@ -1,591 +0,0 @@ -package keeper_test - -import ( - "strings" - "testing" - "time" - - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/auction/types" -) - -type AuctionType int - -const ( - Invalid AuctionType = 0 - Surplus AuctionType = 1 - Debt AuctionType = 2 - Collateral AuctionType = 3 -) - -func TestAuctionBidding(t *testing.T) { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - someTime := time.Date(0o001, time.January, 1, 0, 0, 0, 0, time.UTC) - - _, addrs := app.GeneratePrivKeyAddressPairs(5) - buyer := addrs[0] - secondBuyer := addrs[1] - modName := "liquidator" - collateralAddrs := addrs[2:] - collateralWeights := is(30, 20, 10) - - initialBalance := cs(c("token1", 1000), c("token2", 1000)) - - type auctionArgs struct { - auctionType AuctionType - seller string - lot sdk.Coin - bid sdk.Coin - debt sdk.Coin - addresses []sdk.AccAddress - weights []sdkmath.Int - } - - type bidArgs struct { - bidder sdk.AccAddress - amount sdk.Coin - } - - tests := []struct { - name string - auctionArgs auctionArgs - setupBids []bidArgs - bidArgs bidArgs - expectedError error - expectedEndTime time.Time - expectedBidder sdk.AccAddress - expectedBid sdk.Coin - expectPass bool - expectPanic bool - }{ - { - "basic: auction doesn't exist", - auctionArgs{Surplus, "", c("token1", 1), c("token2", 1), sdk.Coin{}, []sdk.AccAddress{}, []sdkmath.Int{}}, - nil, - bidArgs{buyer, c("token2", 10)}, - types.ErrAuctionNotFound, - someTime.Add(types.DefaultForwardBidDuration), - buyer, - c("token2", 10), - false, - true, - }, - { - "basic: closed auction", - auctionArgs{Surplus, modName, c("token1", 100), c("token2", 10), sdk.Coin{}, []sdk.AccAddress{}, []sdkmath.Int{}}, - nil, - bidArgs{buyer, c("token2", 10)}, - types.ErrAuctionHasExpired, - types.DistantFuture, - nil, - c("token2", 0), - false, - false, - }, - { - // 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{}, []sdkmath.Int{}}, - nil, - bidArgs{buyer, c("token2", 10)}, - nil, - someTime.Add(types.DefaultForwardBidDuration), - buyer, - c("token2", 10), - true, - false, - }, - { - "surplus: second bidder", - 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, - someTime.Add(types.DefaultForwardBidDuration), - secondBuyer, - c("token2", 11), - true, - false, - }, - { - "surplus: invalid bid denom", - auctionArgs{Surplus, modName, c("token1", 100), c("token2", 10), sdk.Coin{}, []sdk.AccAddress{}, []sdkmath.Int{}}, - nil, - bidArgs{buyer, c("badtoken", 10)}, - types.ErrInvalidBidDenom, - types.DistantFuture, - nil, // surplus auctions are created with initial bidder as a nil address - c("token2", 0), - false, - false, - }, - { - "surplus: invalid bid (less than)", - 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, - someTime.Add(types.DefaultForwardBidDuration), - buyer, - c("token2", 100), - false, - false, - }, - { - "surplus: invalid bid (equal)", - 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, - types.DistantFuture, - nil, // surplus auctions are created with initial bidder as a nil address - c("token2", 0), - false, - false, - }, - { - "surplus: invalid bid (less than min increment)", - 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, - someTime.Add(types.DefaultForwardBidDuration), - buyer, - c("token2", 100), - false, - false, - }, - { - "debt: normal", - 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, - someTime.Add(types.DefaultForwardBidDuration), - buyer, - c("token2", 100), - true, - false, - }, - { - "debt: second bidder", - 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, - someTime.Add(types.DefaultForwardBidDuration), - secondBuyer, - c("token2", 100), - true, - false, - }, - { - "debt: invalid lot denom", - 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, - types.DistantFuture, - authtypes.NewModuleAddress(modName), - c("token2", 100), - false, - false, - }, - { - "debt: invalid lot size (larger)", - auctionArgs{Debt, modName, c("token1", 20), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdkmath.Int{}}, - nil, - bidArgs{buyer, c("token1", 21)}, - types.ErrLotTooLarge, - types.DistantFuture, - authtypes.NewModuleAddress(modName), - c("token2", 100), - false, - false, - }, - { - "debt: invalid lot size (equal)", - auctionArgs{Debt, modName, c("token1", 20), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdkmath.Int{}}, - nil, - bidArgs{buyer, c("token1", 20)}, - types.ErrLotTooLarge, - types.DistantFuture, - authtypes.NewModuleAddress(modName), - c("token2", 100), - false, - false, - }, - { - "debt: invalid lot size (larger than min increment)", - 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, - types.DistantFuture, - authtypes.NewModuleAddress(modName), - c("token2", 100), - false, false, - }, - { - "collateral [forward]: normal", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 100), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - nil, - bidArgs{buyer, c("token2", 10)}, - nil, - someTime.Add(types.DefaultForwardBidDuration), - buyer, - c("token2", 10), - true, - false, - }, - { - "collateral [forward]: second bidder", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 100), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 10)}}, - bidArgs{secondBuyer, c("token2", 11)}, - nil, - someTime.Add(types.DefaultForwardBidDuration), - secondBuyer, - c("token2", 11), - true, - false, - }, - { - "collateral [forward]: convert to reverse (reach maxBid)", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 100), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 10)}}, - bidArgs{secondBuyer, c("token2", 100)}, - nil, - someTime.Add(types.DefaultReverseBidDuration), - secondBuyer, - c("token2", 100), - true, - false, - }, - { - "collateral [forward]: invalid bid denom", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 100), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - nil, - bidArgs{buyer, c("badtoken", 10)}, - types.ErrInvalidBidDenom, - types.DistantFuture, - nil, - c("token2", 0), - false, - false, - }, - { - "collateral [forward]: invalid bid size (smaller)", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 100), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 10)}}, - bidArgs{buyer, c("token2", 9)}, - types.ErrBidTooSmall, - someTime.Add(types.DefaultForwardBidDuration), - buyer, - c("token2", 10), - false, - false, - }, - { - "collateral [forward]: invalid bid size (equal)", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 100), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - nil, - bidArgs{buyer, c("token2", 0)}, - types.ErrBidTooSmall, - types.DistantFuture, - nil, - c("token2", 0), - false, - false, - }, - { - "collateral [forward]: invalid bid size (less than min increment)", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 100), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 50)}}, - bidArgs{buyer, c("token2", 51)}, - types.ErrBidTooSmall, - someTime.Add(types.DefaultForwardBidDuration), - buyer, - c("token2", 50), - false, - false, - }, - { - "collateral [forward]: less than min increment but equal to maxBid", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 100), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 99)}}, - bidArgs{buyer, c("token2", 100)}, // min bid at default 5% is 104 - nil, - someTime.Add(types.DefaultReverseBidDuration), // Converts to a reverse bid when max reached - buyer, - c("token2", 100), - true, - false, - }, - { - "collateral [forward]: invalid bid size (greater than max)", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 100), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - nil, - bidArgs{buyer, c("token2", 101)}, - types.ErrBidTooLarge, - types.DistantFuture, - nil, - c("token2", 0), - false, - false, - }, - { - "collateral [forward]: bidder replaces previous bid with only funds for difference", - auctionArgs{Collateral, modName, c("token1", 1000), c("token2", 2000), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 900)}}, - bidArgs{buyer, c("token2", 1000)}, // buyer only has enough to cover the increase from previous bid - nil, - someTime.Add(types.DefaultForwardBidDuration), - buyer, - c("token2", 1000), - true, - false, - }, - { - "collateral [reverse]: normal", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 50), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 50)}}, // put auction into reverse phase - bidArgs{buyer, c("token1", 15)}, - nil, - someTime.Add(types.DefaultReverseBidDuration), - buyer, - c("token2", 50), - true, - false, - }, - { - "collateral [reverse]: second bidder", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 50), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 50)}, {buyer, c("token1", 15)}}, // put auction into reverse phase, and add a reverse phase bid - bidArgs{secondBuyer, c("token1", 14)}, - nil, - someTime.Add(types.DefaultReverseBidDuration), - secondBuyer, - c("token2", 50), - true, - false, - }, - { - "collateral [reverse]: invalid lot denom", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 50), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 50)}}, // put auction into reverse phase - bidArgs{buyer, c("badtoken", 15)}, - types.ErrInvalidLotDenom, - someTime.Add(types.DefaultReverseBidDuration), - buyer, - c("token2", 50), - false, - false, - }, - { - "collateral [reverse]: invalid lot size (greater)", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 50), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 50)}}, // put auction into reverse phase - bidArgs{buyer, c("token1", 21)}, - types.ErrLotTooLarge, - someTime.Add(types.DefaultReverseBidDuration), - buyer, - c("token2", 50), - false, - false, - }, - { - "collateral [reverse]: invalid lot size (equal)", - auctionArgs{Collateral, modName, c("token1", 20), c("token2", 50), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 50)}}, // put auction into reverse phase - bidArgs{buyer, c("token1", 20)}, - types.ErrLotTooLarge, - someTime.Add(types.DefaultReverseBidDuration), - buyer, - c("token2", 50), - false, - false, - }, - { - "collateral [reverse]: invalid lot size (larger than min increment)", - auctionArgs{Collateral, modName, c("token1", 60), c("token2", 50), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 50)}}, // put auction into reverse phase - bidArgs{buyer, c("token1", 58)}, // max lot at default 5% is 57 - types.ErrLotTooLarge, - someTime.Add(types.DefaultReverseBidDuration), - buyer, - c("token2", 50), - false, - false, - }, - { - "collateral [reverse]: bidder replaces previous bid without funds", - auctionArgs{Collateral, modName, c("token1", 1000), c("token2", 1000), c("debt", 50), collateralAddrs, collateralWeights}, // lot, max bid - []bidArgs{{buyer, c("token2", 1000)}}, - bidArgs{buyer, c("token1", 100)}, // buyer has already bid all of their token2 - nil, - someTime.Add(types.DefaultReverseBidDuration), - buyer, - c("token2", 1000), - true, - false, - }, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - // Setup test - tApp := app.NewTestApp() - - // Set up module account - modName := "liquidator" - modBaseAcc := authtypes.NewBaseAccount(authtypes.NewModuleAddress(modName), nil, 0, 0) - modAcc := authtypes.NewModuleAccount(modBaseAcc, modName, []string{authtypes.Minter, authtypes.Burner}...) - - // Set up normal accounts - addrs := []sdk.AccAddress{buyer, secondBuyer, collateralAddrs[0], collateralAddrs[1], collateralAddrs[2]} - - // Initialize app - authGS := app.NewFundedGenStateWithSameCoinsWithModuleAccount(tApp.AppCodec(), initialBalance, addrs, modAcc) - params := types.NewParams( - types.DefaultMaxAuctionDuration, - types.DefaultForwardBidDuration, - types.DefaultReverseBidDuration, - types.DefaultIncrement, - types.DefaultIncrement, - types.DefaultIncrement, - ) - - auctionGs, err := types.NewGenesisState(types.DefaultNextAuctionID, params, []types.GenesisAuction{}) - require.NoError(t, err) - - moduleGs := tApp.AppCodec().MustMarshalJSON(auctionGs) - gs := app.GenesisState{types.ModuleName: moduleGs} - tApp.InitializeFromGenesisStates(authGS, gs) - - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: someTime}) - keeper := tApp.GetAuctionKeeper() - bank := tApp.GetBankKeeper() - - err = tApp.FundModuleAccount(ctx, modName, cs(c("token1", 1000), c("token2", 1000), c("debt", 1000))) - require.NoError(t, err) - - // Start Auction - var id uint64 - switch tc.auctionArgs.auctionType { - case Surplus: - if tc.expectPanic { - require.Panics(t, func() { - id, err = keeper.StartSurplusAuction(ctx, tc.auctionArgs.seller, tc.auctionArgs.lot, tc.auctionArgs.bid.Denom) - }) - } else { - id, err = keeper.StartSurplusAuction(ctx, tc.auctionArgs.seller, tc.auctionArgs.lot, tc.auctionArgs.bid.Denom) - } - case Debt: - id, err = keeper.StartDebtAuction(ctx, tc.auctionArgs.seller, tc.auctionArgs.bid, tc.auctionArgs.lot, tc.auctionArgs.debt) - case Collateral: - id, err = keeper.StartCollateralAuction(ctx, tc.auctionArgs.seller, tc.auctionArgs.lot, tc.auctionArgs.bid, tc.auctionArgs.addresses, tc.auctionArgs.weights, tc.auctionArgs.debt) // seller, lot, maxBid, otherPerson - default: - t.Fail() - } - - require.NoError(t, err) - - // Place setup bids - for _, b := range tc.setupBids { - require.NoError(t, keeper.PlaceBid(ctx, id, b.bidder, b.amount)) - } - - // Close the auction early to test late bidding (if applicable) - if strings.Contains(tc.name, "closed") { - ctx = ctx.WithBlockTime(types.DistantFuture.Add(1)) - } - - // Store some state for use in checks - var oldBidder sdk.AccAddress - var oldBidderOldCoins sdk.Coins - - oldAuction, found := keeper.GetAuction(ctx, id) - if found { - oldBidder = oldAuction.GetBidder() - } - - if !oldBidder.Empty() { - oldBidderOldCoins = bank.GetAllBalances(ctx, oldBidder) - } - - newBidderOldCoins := bank.GetAllBalances(ctx, tc.bidArgs.bidder) - - // Place bid on auction - err = keeper.PlaceBid(ctx, id, tc.bidArgs.bidder, tc.bidArgs.amount) - - // Check success/failure - if tc.expectPass { - require.NoError(t, err) - // Check auction was found - newAuction, found := keeper.GetAuction(ctx, id) - require.True(t, found) - // Check auction values - require.Equal(t, modName, newAuction.GetInitiator()) - require.Equal(t, tc.expectedBidder, newAuction.GetBidder()) - require.Equal(t, tc.expectedBid, newAuction.GetBid()) - require.Equal(t, tc.expectedEndTime, newAuction.GetEndTime()) - - // Check coins have moved between bidder and previous bidder - bidAmt := tc.bidArgs.amount - switch tc.auctionArgs.auctionType { - case Debt: - bidAmt = oldAuction.GetBid() - case Collateral: - collatAuction, ok := oldAuction.(*types.CollateralAuction) - require.True(t, ok, tc.name) - if collatAuction.IsReversePhase() { - bidAmt = oldAuction.GetBid() - } - } - if oldBidder.Equals(tc.bidArgs.bidder) { // same bidder - require.Equal(t, newBidderOldCoins.Sub(bidAmt.Sub(oldAuction.GetBid())), bank.GetAllBalances(ctx, tc.bidArgs.bidder)) - } else { // different bidder - require.Equal(t, newBidderOldCoins.Sub(bidAmt), bank.GetAllBalances(ctx, tc.bidArgs.bidder)) // wrapping in cs() to avoid comparing nil and empty coins - - // handle checking debt coins for case debt auction has had no bids placed yet TODO make this less confusing - if oldBidder.Equals(authtypes.NewModuleAddress(oldAuction.GetInitiator())) { - require.Equal(t, oldBidderOldCoins.Add(oldAuction.GetBid()).Add(c("debt", oldAuction.GetBid().Amount.Int64())), bank.GetAllBalances(ctx, oldBidder)) - } else if oldBidder.Empty() { - require.Equal(t, oldBidderOldCoins.Add(oldAuction.GetBid()).Add(c("debt", oldAuction.GetBid().Amount.Int64())).Empty(), oldBidderOldCoins.Empty()) - } else { - require.Equal(t, cs(oldBidderOldCoins.Add(oldAuction.GetBid())...), bank.GetAllBalances(ctx, oldBidder)) - } - } - - } else { - // Check expected error code type - require.Error(t, err, "PlaceBid did not return an error") - require.ErrorIs(t, err, tc.expectedError) - - // Check auction values - newAuction, found := keeper.GetAuction(ctx, id) - if found { - require.Equal(t, modName, newAuction.GetInitiator()) - require.Equal(t, tc.expectedBidder, newAuction.GetBidder()) - require.Equal(t, tc.expectedBid, newAuction.GetBid()) - require.Equal(t, tc.expectedEndTime, newAuction.GetEndTime()) - } - - // Check coins have not moved - require.Equal(t, newBidderOldCoins, bank.GetAllBalances(ctx, tc.bidArgs.bidder)) - if !oldBidder.Empty() { - require.Equal(t, oldBidderOldCoins, bank.GetAllBalances(ctx, oldBidder)) - } - } - }) - } -} diff --git a/x/auction/keeper/grpc_query.go b/x/auction/keeper/grpc_query.go deleted file mode 100644 index e27502c7..00000000 --- a/x/auction/keeper/grpc_query.go +++ /dev/null @@ -1,145 +0,0 @@ -package keeper - -import ( - "context" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - - proto "github.com/cosmos/gogoproto/proto" - - "github.com/0glabs/0g-chain/x/auction/types" -) - -type queryServer struct { - keeper Keeper -} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(k Keeper) types.QueryServer { - return &queryServer{keeper: k} -} - -var _ types.QueryServer = queryServer{} - -// Params implements the gRPC service handler for querying x/auction parameters. -func (s queryServer) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - params := s.keeper.GetParams(sdkCtx) - - return &types.QueryParamsResponse{Params: params}, nil -} - -// Auction implements the Query/Auction gRPC method -func (s queryServer) Auction(c context.Context, req *types.QueryAuctionRequest) (*types.QueryAuctionResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - ctx := sdk.UnwrapSDKContext(c) - - auction, found := s.keeper.GetAuction(ctx, req.AuctionId) - if !found { - return &types.QueryAuctionResponse{}, nil - } - - msg, ok := auction.(proto.Message) - if !ok { - return nil, status.Errorf(codes.Internal, "can't protomarshal %T", msg) - } - - auctionAny, err := codectypes.NewAnyWithValue(msg) - if err != nil { - return nil, status.Errorf(codes.Internal, err.Error()) - } - - return &types.QueryAuctionResponse{ - Auction: auctionAny, - }, nil -} - -// Auctions implements the Query/Auctions gRPC method -func (s queryServer) Auctions(c context.Context, req *types.QueryAuctionsRequest) (*types.QueryAuctionsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - ctx := sdk.UnwrapSDKContext(c) - - var auctions []*codectypes.Any - auctionStore := prefix.NewStore(ctx.KVStore(s.keeper.storeKey), types.AuctionKeyPrefix) - - pageRes, err := query.FilteredPaginate(auctionStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { - result, err := s.keeper.UnmarshalAuction(value) - if err != nil { - return false, err - } - - // True if empty owner, otherwise check if auction contains owner - ownerIsMatch := req.Owner == "" - if req.Owner != "" { - if cAuc, ok := result.(*types.CollateralAuction); ok { - for _, addr := range cAuc.GetLotReturns().Addresses { - if addr.String() == req.Owner { - ownerIsMatch = true - break - } - } - } - } - - phaseIsMatch := req.Phase == "" || req.Phase == result.GetPhase() - typeIsMatch := req.Type == "" || req.Type == result.GetType() - denomIsMatch := req.Denom == "" || req.Denom == result.GetBid().Denom || req.Denom == result.GetLot().Denom - - if ownerIsMatch && phaseIsMatch && typeIsMatch && denomIsMatch { - if accumulate { - msg, ok := result.(proto.Message) - if !ok { - return false, status.Errorf(codes.Internal, "can't protomarshal %T", msg) - } - - auctionAny, err := codectypes.NewAnyWithValue(msg) - if err != nil { - return false, err - } - auctions = append(auctions, auctionAny) - } - - return true, nil - } - - return false, nil - }) - if err != nil { - return &types.QueryAuctionsResponse{}, err - } - - return &types.QueryAuctionsResponse{ - Auctions: auctions, - Pagination: pageRes, - }, nil -} - -// NextAuctionID implements the gRPC service handler for querying x/auction next auction ID. -func (s queryServer) NextAuctionID(ctx context.Context, req *types.QueryNextAuctionIDRequest) (*types.QueryNextAuctionIDResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - nextAuctionID, err := s.keeper.GetNextAuctionID(sdkCtx) - if err != nil { - return &types.QueryNextAuctionIDResponse{}, err - } - - return &types.QueryNextAuctionIDResponse{Id: nextAuctionID}, nil -} diff --git a/x/auction/keeper/grpc_query_test.go b/x/auction/keeper/grpc_query_test.go deleted file mode 100644 index b870753e..00000000 --- a/x/auction/keeper/grpc_query_test.go +++ /dev/null @@ -1,137 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/auction/keeper" - "github.com/0glabs/0g-chain/x/auction/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/stretchr/testify/require" -) - -func TestGrpcAuctionsFilter(t *testing.T) { - // setup - tApp := app.NewTestApp() - tApp.InitializeFromGenesisStates() - auctionsKeeper := tApp.GetAuctionKeeper() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - _, addrs := app.GeneratePrivKeyAddressPairs(2) - - auctions := []types.Auction{ - types.NewSurplusAuction( - "sellerMod", - c("swp", 12345678), - "usdx", - time.Date(1998, time.January, 1, 0, 0, 0, 0, time.UTC), - ).WithID(0), - types.NewDebtAuction( - "buyerMod", - c("hard", 12345678), - c("usdx", 12345678), - time.Date(1998, time.January, 1, 0, 0, 0, 0, time.UTC), - c("debt", 12345678), - ).WithID(1), - types.NewCollateralAuction( - "sellerMod", - c("ukava", 12345678), - time.Date(1998, time.January, 1, 0, 0, 0, 0, time.UTC), - c("usdx", 12345678), - types.WeightedAddresses{ - Addresses: addrs, - Weights: []sdkmath.Int{sdkmath.NewInt(100)}, - }, - c("debt", 12345678), - ).WithID(2), - types.NewCollateralAuction( - "sellerMod", - c("hard", 12345678), - time.Date(1998, time.January, 1, 0, 0, 0, 0, time.UTC), - c("usdx", 12345678), - types.WeightedAddresses{ - Addresses: addrs, - Weights: []sdkmath.Int{sdkmath.NewInt(100)}, - }, - c("debt", 12345678), - ).WithID(3), - } - for _, a := range auctions { - auctionsKeeper.SetAuction(ctx, a) - } - - qs := keeper.NewQueryServerImpl(auctionsKeeper) - - tests := []struct { - giveName string - giveRequest types.QueryAuctionsRequest - wantResponse []types.Auction - }{ - { - "empty request", - types.QueryAuctionsRequest{}, - auctions, - }, - { - "denom query swp", - types.QueryAuctionsRequest{ - Denom: "swp", - }, - auctions[0:1], - }, - { - "denom query usdx all", - types.QueryAuctionsRequest{ - Denom: "usdx", - }, - auctions, - }, - { - "owner", - types.QueryAuctionsRequest{ - Owner: addrs[0].String(), - }, - auctions[2:4], - }, - { - "owner and denom", - types.QueryAuctionsRequest{ - Owner: addrs[0].String(), - Denom: "hard", - }, - auctions[3:4], - }, - { - "owner, denom, type, phase", - types.QueryAuctionsRequest{ - Owner: addrs[0].String(), - Denom: "hard", - Type: types.CollateralAuctionType, - Phase: types.ForwardAuctionPhase, - }, - auctions[3:4], - }, - } - - for _, tc := range tests { - t.Run(tc.giveName, func(t *testing.T) { - res, err := qs.Auctions(sdk.WrapSDKContext(ctx), &tc.giveRequest) - require.NoError(t, err) - - var unpackedAuctions []types.Auction - - for _, anyAuction := range res.Auctions { - var auction types.Auction - err := tApp.AppCodec().UnpackAny(anyAuction, &auction) - require.NoError(t, err) - - unpackedAuctions = append(unpackedAuctions, auction) - } - - require.Equal(t, tc.wantResponse, unpackedAuctions) - }) - } -} diff --git a/x/auction/keeper/integration_test.go b/x/auction/keeper/integration_test.go deleted file mode 100644 index c808bcac..00000000 --- a/x/auction/keeper/integration_test.go +++ /dev/null @@ -1,15 +0,0 @@ -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 []sdkmath.Int) { - for _, n := range ns { - is = append(is, sdkmath.NewInt(n)) - } - return -} diff --git a/x/auction/keeper/invariants.go b/x/auction/keeper/invariants.go deleted file mode 100644 index f694c0be..00000000 --- a/x/auction/keeper/invariants.go +++ /dev/null @@ -1,132 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - "github.com/0glabs/0g-chain/x/auction/types" -) - -// RegisterInvariants registers all staking invariants -func RegisterInvariants(ir sdk.InvariantRegistry, k Keeper) { - ir.RegisterRoute(types.ModuleName, "module-account", - ModuleAccountInvariants(k)) - ir.RegisterRoute(types.ModuleName, "valid-auctions", - ValidAuctionInvariant(k)) - ir.RegisterRoute(types.ModuleName, "valid-index", - ValidIndexInvariant(k)) -} - -// ModuleAccountInvariants checks that the module account's coins matches those stored in auctions -func ModuleAccountInvariants(k Keeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - totalAuctionCoins := sdk.NewCoins() - k.IterateAuctions(ctx, func(auction types.Auction) bool { - a, ok := auction.(types.GenesisAuction) - if !ok { - panic("stored auction type does not fulfill GenesisAuction interface") - } - totalAuctionCoins = totalAuctionCoins.Add(a.GetModuleAccountCoins()...) - return false - }) - - moduleAccCoins := k.bankKeeper.GetAllBalances(ctx, authtypes.NewModuleAddress(types.ModuleName)) - broken := !moduleAccCoins.IsEqual(totalAuctionCoins) - - invariantMessage := sdk.FormatInvariant( - types.ModuleName, - "module account", - fmt.Sprintf( - "\texpected ModuleAccount coins: %s\n"+ - "\tactual ModuleAccount coins: %s\n", - totalAuctionCoins, moduleAccCoins), - ) - return invariantMessage, broken - } -} - -// ValidAuctionInvariant verifies that all auctions in the store are independently valid -func ValidAuctionInvariant(k Keeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - var validationErr error - var invalidAuction types.Auction - k.IterateAuctions(ctx, func(auction types.Auction) bool { - a, ok := auction.(types.GenesisAuction) - if !ok { - panic("stored auction type does not fulfill GenesisAuction interface") - } - - if err := a.Validate(); err != nil { - validationErr = err - invalidAuction = a - return true - } - return false - }) - - broken := validationErr != nil - invariantMessage := sdk.FormatInvariant( - types.ModuleName, - "valid auctions", - fmt.Sprintf( - "\tfound invalid auction, reason: %s\n"+ - "\tauction:\n\t%s\n", - validationErr, invalidAuction), - ) - return invariantMessage, broken - } -} - -// ValidIndexInvariant checks that all auctions in the store are also in the index and vice versa. -func ValidIndexInvariant(k Keeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - /* Method: - - check all the auction IDs in the index have a corresponding auction in the store - - index is now valid but there could be extra auction in the store - - check for these extra auctions by checking num items in the store equals that of index (store keys are always unique) - - doesn't check the IDs in the auction structs match the IDs in the keys - */ - - // Check all auction IDs in the index are in the auction store - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.AuctionKeyPrefix) - - indexIterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.AuctionByTimeKeyPrefix) - defer indexIterator.Close() - - var indexLength int - for ; indexIterator.Valid(); indexIterator.Next() { - indexLength++ - - idBytes := indexIterator.Value() - auctionBytes := store.Get(idBytes) - if auctionBytes == nil { - invariantMessage := sdk.FormatInvariant( - types.ModuleName, - "valid index", - fmt.Sprintf("\tauction with ID '%d' found in index but not in store", types.Uint64FromBytes(idBytes))) - return invariantMessage, true - } - } - - // Check length of auction store matches the length of the index - storeIterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.AuctionKeyPrefix) - defer storeIterator.Close() - var storeLength int - for ; storeIterator.Valid(); storeIterator.Next() { - storeLength++ - } - - if storeLength != indexLength { - invariantMessage := sdk.FormatInvariant( - types.ModuleName, - "valid index", - fmt.Sprintf("\tmismatched number of items in auction store (%d) and index (%d)", storeLength, indexLength)) - return invariantMessage, true - } - - return "", false - } -} diff --git a/x/auction/keeper/keeper.go b/x/auction/keeper/keeper.go deleted file mode 100644 index 1e792c1f..00000000 --- a/x/auction/keeper/keeper.go +++ /dev/null @@ -1,217 +0,0 @@ -package keeper - -import ( - "fmt" - "time" - - "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" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - - "github.com/cometbft/cometbft/libs/log" - - "github.com/0glabs/0g-chain/x/auction/types" -) - -type Keeper struct { - storeKey storetypes.StoreKey - cdc codec.Codec - paramSubspace paramtypes.Subspace - bankKeeper types.BankKeeper - accountKeeper types.AccountKeeper -} - -// NewKeeper returns a new auction keeper. -func NewKeeper(cdc codec.Codec, storeKey storetypes.StoreKey, paramstore paramtypes.Subspace, - bankKeeper types.BankKeeper, accountKeeper types.AccountKeeper, -) Keeper { - if !paramstore.HasKeyTable() { - paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) - } - - return Keeper{ - storeKey: storeKey, - cdc: cdc, - paramSubspace: paramstore, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - } -} - -// MustUnmarshalAuction attempts to decode and return an Auction object from -// raw encoded bytes. It panics on error. -func (k Keeper) MustUnmarshalAuction(bz []byte) types.Auction { - auction, err := k.UnmarshalAuction(bz) - if err != nil { - panic(fmt.Errorf("failed to decode auction: %w", err)) - } - - return auction -} - -// MustMarshalAuction attempts to encode an Auction object and returns the -// raw encoded bytes. It panics on error. -func (k Keeper) MustMarshalAuction(auction types.Auction) []byte { - bz, err := k.MarshalAuction(auction) - if err != nil { - panic(fmt.Errorf("failed to encode auction: %w", err)) - } - - return bz -} - -// MarshalAuction protobuf serializes an Auction interface -func (k Keeper) MarshalAuction(auctionI types.Auction) ([]byte, error) { - return k.cdc.MarshalInterface(auctionI) -} - -// UnmarshalAuction returns an Auction interface from raw encoded auction -// bytes of a Proto-based Auction type -func (k Keeper) UnmarshalAuction(bz []byte) (types.Auction, error) { - var evi types.Auction - return evi, k.cdc.UnmarshalInterface(bz, &evi) -} - -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) -} - -// SetNextAuctionID stores an ID to be used for the next created auction -func (k Keeper) SetNextAuctionID(ctx sdk.Context, id uint64) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.NextAuctionIDKey) - store.Set(types.NextAuctionIDKey, types.Uint64ToBytes(id)) -} - -// GetNextAuctionID reads the next available global ID from store -func (k Keeper) GetNextAuctionID(ctx sdk.Context) (uint64, error) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.NextAuctionIDKey) - bz := store.Get(types.NextAuctionIDKey) - if bz == nil { - return 0, types.ErrInvalidInitialAuctionID - } - return types.Uint64FromBytes(bz), nil -} - -// IncrementNextAuctionID increments the next auction ID in the store by 1. -func (k Keeper) IncrementNextAuctionID(ctx sdk.Context) error { - id, err := k.GetNextAuctionID(ctx) - if err != nil { - return err - } - k.SetNextAuctionID(ctx, id+1) - return nil -} - -// StoreNewAuction stores an auction, adding a new ID -func (k Keeper) StoreNewAuction(ctx sdk.Context, auction types.Auction) (uint64, error) { - newAuctionID, err := k.GetNextAuctionID(ctx) - if err != nil { - return 0, err - } - - auction = auction.WithID(newAuctionID) - k.SetAuction(ctx, auction) - - err = k.IncrementNextAuctionID(ctx) - if err != nil { - return 0, err - } - return newAuctionID, nil -} - -// SetAuction puts the auction into the store, and updates any indexes. -func (k Keeper) SetAuction(ctx sdk.Context, auction types.Auction) { - // remove the auction from the byTime index if it is already in there - existingAuction, found := k.GetAuction(ctx, auction.GetID()) - if found { - k.removeFromByTimeIndex(ctx, existingAuction.GetEndTime(), existingAuction.GetID()) - } - - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.AuctionKeyPrefix) - - store.Set(types.GetAuctionKey(auction.GetID()), k.MustMarshalAuction(auction)) - k.InsertIntoByTimeIndex(ctx, auction.GetEndTime(), auction.GetID()) -} - -// GetAuction gets an auction from the store. -func (k Keeper) GetAuction(ctx sdk.Context, auctionID uint64) (types.Auction, bool) { - var auction types.Auction - - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.AuctionKeyPrefix) - bz := store.Get(types.GetAuctionKey(auctionID)) - if bz == nil { - return auction, false - } - - return k.MustUnmarshalAuction(bz), true -} - -// DeleteAuction removes an auction from the store, and any indexes. -func (k Keeper) DeleteAuction(ctx sdk.Context, auctionID uint64) { - auction, found := k.GetAuction(ctx, auctionID) - if found { - k.removeFromByTimeIndex(ctx, auction.GetEndTime(), auctionID) - } - - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.AuctionKeyPrefix) - store.Delete(types.GetAuctionKey(auctionID)) -} - -// InsertIntoByTimeIndex adds an auction ID and end time into the byTime index. -func (k Keeper) InsertIntoByTimeIndex(ctx sdk.Context, endTime time.Time, auctionID uint64) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.AuctionByTimeKeyPrefix) - store.Set(types.GetAuctionByTimeKey(endTime, auctionID), types.Uint64ToBytes(auctionID)) -} - -// removeFromByTimeIndex removes an auction ID and end time from the byTime index. -func (k Keeper) removeFromByTimeIndex(ctx sdk.Context, endTime time.Time, auctionID uint64) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.AuctionByTimeKeyPrefix) - store.Delete(types.GetAuctionByTimeKey(endTime, auctionID)) -} - -// IterateAuctionByTime provides an iterator over auctions ordered by auction.EndTime. -// For each auction cb will be callled. If cb returns true the iterator will close and stop. -func (k Keeper) IterateAuctionsByTime(ctx sdk.Context, inclusiveCutoffTime time.Time, cb func(auctionID uint64) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.AuctionByTimeKeyPrefix) - iterator := store.Iterator( - nil, // start at the very start of the prefix store - sdk.PrefixEndBytes(sdk.FormatTimeBytes(inclusiveCutoffTime)), // include any keys with times equal to inclusiveCutoffTime - ) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - - auctionID := types.Uint64FromBytes(iterator.Value()) - - if cb(auctionID) { - break - } - } -} - -// IterateAuctions provides an iterator over all stored auctions. -// For each auction, cb will be called. If cb returns true, the iterator will close and stop. -func (k Keeper) IterateAuctions(ctx sdk.Context, cb func(auction types.Auction) (stop bool)) { - iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.AuctionKeyPrefix) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - auction := k.MustUnmarshalAuction(iterator.Value()) - - if cb(auction) { - break - } - } -} - -// GetAllAuctions returns all auctions from the store -func (k Keeper) GetAllAuctions(ctx sdk.Context) (auctions []types.Auction) { - k.IterateAuctions(ctx, func(auction types.Auction) bool { - auctions = append(auctions, auction) - return false - }) - return -} diff --git a/x/auction/keeper/keeper_test.go b/x/auction/keeper/keeper_test.go deleted file mode 100644 index 4c7d5c39..00000000 --- a/x/auction/keeper/keeper_test.go +++ /dev/null @@ -1,135 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/auction/types" -) - -func SetGetDeleteAuction(t *testing.T) { - // setup keeper, create auction - tApp := app.NewTestApp() - keeper := tApp.GetAuctionKeeper() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - - someTime := time.Date(43, time.January, 1, 0, 0, 0, 0, time.UTC) // need to specify UTC as tz info is lost on unmarshal - var id uint64 = 5 - auction := types.NewSurplusAuction("some_module", c("usdx", 100), "kava", someTime).WithID(id) - - // write and read from store - keeper.SetAuction(ctx, auction) - readAuction, found := keeper.GetAuction(ctx, id) - - // check before and after match - require.True(t, found) - require.Equal(t, auction, readAuction) - // check auction is in the index - keeper.IterateAuctionsByTime(ctx, auction.GetEndTime(), func(readID uint64) bool { - require.Equal(t, auction.GetID(), readID) - return false - }) - - // delete auction - keeper.DeleteAuction(ctx, id) - - // check auction does not exist - _, found = keeper.GetAuction(ctx, id) - require.False(t, found) - // check auction not in index - keeper.IterateAuctionsByTime(ctx, time.Unix(999999999, 0), func(readID uint64) bool { - require.Fail(t, "index should be empty", " found auction ID '%s", readID) - return false - }) -} - -func TestIncrementNextAuctionID(t *testing.T) { - // setup keeper - tApp := app.NewTestApp() - keeper := tApp.GetAuctionKeeper() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - - // store id - var id uint64 = 123456 - keeper.SetNextAuctionID(ctx, id) - - require.NoError(t, keeper.IncrementNextAuctionID(ctx)) - - // check id was incremented - readID, err := keeper.GetNextAuctionID(ctx) - require.NoError(t, err) - require.Equal(t, id+1, readID) -} - -func TestIterateAuctions(t *testing.T) { - // setup - tApp := app.NewTestApp() - tApp.InitializeFromGenesisStates() - keeper := tApp.GetAuctionKeeper() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - - auctions := []types.Auction{ - types.NewSurplusAuction("sellerMod", c("denom", 12345678), "anotherdenom", time.Date(1998, time.January, 1, 0, 0, 0, 0, time.UTC)).WithID(0), - types.NewDebtAuction("buyerMod", c("denom", 12345678), c("anotherdenom", 12345678), time.Date(1998, time.January, 1, 0, 0, 0, 0, time.UTC), c("debt", 12345678)).WithID(1), - types.NewCollateralAuction("sellerMod", c("denom", 12345678), time.Date(1998, time.January, 1, 0, 0, 0, 0, time.UTC), c("anotherdenom", 12345678), types.WeightedAddresses{}, c("debt", 12345678)).WithID(2), - } - for _, a := range auctions { - keeper.SetAuction(ctx, a) - } - - // run - var readAuctions []types.Auction - keeper.IterateAuctions(ctx, func(a types.Auction) bool { - readAuctions = append(readAuctions, a) - return false - }) - - // check - require.Equal(t, auctions, readAuctions) -} - -func TestIterateAuctionsByTime(t *testing.T) { - // setup keeper - tApp := app.NewTestApp() - keeper := tApp.GetAuctionKeeper() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - - // setup byTime index - byTimeIndex := []struct { - endTime time.Time - auctionID uint64 - }{ - {time.Date(0, time.January, 1, 0, 0, 0, 0, time.UTC), 9999}, // distant past - {time.Date(1998, time.January, 1, 11, 59, 59, 999999999, time.UTC), 1}, // just before cutoff - {time.Date(1998, time.January, 1, 11, 59, 59, 999999999, time.UTC), 2}, // - {time.Date(1998, time.January, 1, 12, 0, 0, 0, time.UTC), 3}, // equal to cutoff - {time.Date(1998, time.January, 1, 12, 0, 0, 0, time.UTC), 4}, // - {time.Date(1998, time.January, 1, 12, 0, 0, 1, time.UTC), 5}, // just after cutoff - {time.Date(1998, time.January, 1, 12, 0, 0, 1, time.UTC), 6}, // - {time.Date(9999, time.January, 1, 0, 0, 0, 0, time.UTC), 0}, // distant future - } - for _, v := range byTimeIndex { - keeper.InsertIntoByTimeIndex(ctx, v.endTime, v.auctionID) - } - - // read out values from index up to a cutoff time and check they are as expected - cutoffTime := time.Date(1998, time.January, 1, 12, 0, 0, 0, time.UTC) - var expectedIndex []uint64 - for _, v := range byTimeIndex { - if v.endTime.Before(cutoffTime) || v.endTime.Equal(cutoffTime) { // endTime ≤ cutoffTime - expectedIndex = append(expectedIndex, v.auctionID) - } - } - var readIndex []uint64 - keeper.IterateAuctionsByTime(ctx, cutoffTime, func(id uint64) bool { - readIndex = append(readIndex, id) - return false - }) - - require.Equal(t, expectedIndex, readIndex) -} diff --git a/x/auction/keeper/math.go b/x/auction/keeper/math.go deleted file mode 100644 index 032da042..00000000 --- a/x/auction/keeper/math.go +++ /dev/null @@ -1,81 +0,0 @@ -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 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") - } - if len(buckets) < 1 { - panic("no buckets") - } - for _, bucket := range buckets { - if bucket.IsNegative() { - panic("negative bucket") - } - } - - // 1) Split the amount by weights, recording whole number part and remainder - - totalWeights := totalInts(buckets...) - if !totalWeights.IsPositive() { - panic("total weights must sum to > 0") - } - - quotients := make([]quoRem, len(buckets)) - for i := range buckets { - // amount * ( weight/total_weight ) - q := amount.Mul(buckets[i]).Quo(totalWeights) - r := amount.Mul(buckets[i]).Mod(totalWeights) - quotients[i] = quoRem{index: i, quo: q, rem: r} - } - - // 2) Calculate total left over from remainders, and apportion it to buckets with the highest remainder (to minimize error) - - // sort by decreasing remainder order - sort.Slice(quotients, func(i, j int) bool { - return quotients[i].rem.GT(quotients[j].rem) - }) - - // calculate total left over from remainders - allocated := sdk.ZeroInt() - for _, qr := range quotients { - allocated = allocated.Add(qr.quo) - } - leftToAllocate := amount.Sub(allocated) - - // apportion according to largest remainder - results := make([]sdkmath.Int, len(quotients)) - for _, qr := range quotients { - results[qr.index] = qr.quo - if !leftToAllocate.IsZero() { - results[qr.index] = results[qr.index].Add(sdk.OneInt()) - leftToAllocate = leftToAllocate.Sub(sdk.OneInt()) - } - } - return results -} - -type quoRem struct { - index int - quo sdkmath.Int - rem sdkmath.Int -} - -// totalInts adds together sdk.Ints -func totalInts(is ...sdkmath.Int) sdkmath.Int { - total := sdk.ZeroInt() - for _, i := range is { - total = total.Add(i) - } - return total -} diff --git a/x/auction/keeper/math_test.go b/x/auction/keeper/math_test.go deleted file mode 100644 index c83094c9..00000000 --- a/x/auction/keeper/math_test.go +++ /dev/null @@ -1,115 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" -) - -func TestSplitIntIntoWeightedBuckets(t *testing.T) { - testCases := []struct { - name string - amount sdkmath.Int - buckets []sdkmath.Int - want []sdkmath.Int - expectPanic bool - }{ - { - name: "0split0", - amount: i(0), - buckets: is(0), - expectPanic: true, - }, - { - name: "5splitnil", - amount: i(5), - buckets: is(), - expectPanic: true, - }, - { - name: "-2split1,1", - amount: i(-2), - buckets: is(1, 1), - expectPanic: true, - }, - { - name: "2split1,-1", - amount: i(2), - buckets: is(1, -1), - expectPanic: true, - }, - { - name: "0split0,0,0,1", - amount: i(0), - buckets: is(0, 0, 0, 1), - want: is(0, 0, 0, 0), - }, - { - name: "2split1,1", - amount: i(2), - buckets: is(1, 1), - want: is(1, 1), - }, - { - name: "100split1,9", - amount: i(100), - buckets: is(1, 9), - want: is(10, 90), - }, - { - name: "100split9,1", - amount: i(100), - buckets: is(9, 1), - want: is(90, 10), - }, - { - name: "7split1,2", - amount: i(7), - buckets: is(1, 2), - want: is(2, 5), - }, - { - name: "17split1,1,1", - amount: i(17), - buckets: is(1, 1, 1), - want: is(6, 6, 5), - }, - { - name: "10split1000000,1", - amount: i(10), - buckets: is(1000000, 1), - want: is(10, 0), - }, - { - name: "334733353split730777,31547", - amount: i(334733353), - buckets: is(730777, 31547), - want: is(320881194, 13852159), - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - var got []sdkmath.Int - run := func() { - got = splitIntIntoWeightedBuckets(tc.amount, tc.buckets) - } - if tc.expectPanic { - require.Panics(t, run) - } else { - require.NotPanics(t, run) - } - - require.Equal(t, tc.want, got) - }) - } -} - -func i(n int64) sdkmath.Int { return sdkmath.NewInt(n) } -func is(ns ...int64) (is []sdkmath.Int) { - for _, n := range ns { - is = append(is, sdkmath.NewInt(n)) - } - return -} diff --git a/x/auction/keeper/msg_server.go b/x/auction/keeper/msg_server.go deleted file mode 100644 index 6acbd34b..00000000 --- a/x/auction/keeper/msg_server.go +++ /dev/null @@ -1,43 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/auction/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the auction MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -func (k msgServer) PlaceBid(goCtx context.Context, msg *types.MsgPlaceBid) (*types.MsgPlaceBidResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - bidder, err := sdk.AccAddressFromBech32(msg.Bidder) - if err != nil { - return nil, err - } - - err = k.keeper.PlaceBid(ctx, msg.AuctionId, bidder, msg.Amount) - if err != nil { - return nil, err - } - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Bidder), - ), - ) - return &types.MsgPlaceBidResponse{}, nil -} diff --git a/x/auction/keeper/params.go b/x/auction/keeper/params.go deleted file mode 100644 index 9341e3bc..00000000 --- a/x/auction/keeper/params.go +++ /dev/null @@ -1,16 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/auction/types" -) - -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSubspace.SetParamSet(ctx, ¶ms) -} - -func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { - k.paramSubspace.GetParamSet(ctx, ¶ms) - return -} diff --git a/x/auction/legacy/v0_16/codec.go b/x/auction/legacy/v0_16/codec.go deleted file mode 100644 index cb993158..00000000 --- a/x/auction/legacy/v0_16/codec.go +++ /dev/null @@ -1,16 +0,0 @@ -package types - -import ( - v017auction "github.com/0glabs/0g-chain/x/auction/types" - types "github.com/cosmos/cosmos-sdk/codec/types" -) - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterInterface( - "kava.auction.v1beta1.GenesisAuction", - (*v017auction.GenesisAuction)(nil), - &v017auction.SurplusAuction{}, - &v017auction.DebtAuction{}, - &v017auction.CollateralAuction{}, - ) -} diff --git a/x/auction/legacy/v0_16/genesis.pb.go b/x/auction/legacy/v0_16/genesis.pb.go deleted file mode 100644 index 9971f9b5..00000000 --- a/x/auction/legacy/v0_16/genesis.pb.go +++ /dev/null @@ -1,761 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/auction/v1beta1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/codec/types" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - github_com_gogo_protobuf_types "github.com/gogo/protobuf/types" - _ "google.golang.org/protobuf/types/known/durationpb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// GenesisState defines the auction module's genesis state. -type GenesisState struct { - NextAuctionId uint64 `protobuf:"varint,1,opt,name=next_auction_id,json=nextAuctionId,proto3" json:"next_auction_id,omitempty"` - Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"` - // Genesis auctions - Auctions []*types.Any `protobuf:"bytes,3,rep,name=auctions,proto3" json:"auctions,omitempty"` -} - -func (m *GenesisState) Reset() { *m = GenesisState{} } -func (m *GenesisState) String() string { return proto.CompactTextString(m) } -func (*GenesisState) ProtoMessage() {} -func (*GenesisState) Descriptor() ([]byte, []int) { - return fileDescriptor_d0e5cb58293042f7, []int{0} -} -func (m *GenesisState) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisState) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisState.Merge(m, src) -} -func (m *GenesisState) XXX_Size() int { - return m.Size() -} -func (m *GenesisState) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisState.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisState proto.InternalMessageInfo - -// Params defines the parameters for the issuance module. -type Params struct { - MaxAuctionDuration time.Duration `protobuf:"bytes,1,opt,name=max_auction_duration,json=maxAuctionDuration,proto3,stdduration" json:"max_auction_duration"` - BidDuration time.Duration `protobuf:"bytes,2,opt,name=bid_duration,json=bidDuration,proto3,stdduration" json:"bid_duration"` - IncrementSurplus github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=increment_surplus,json=incrementSurplus,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"increment_surplus"` - IncrementDebt github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=increment_debt,json=incrementDebt,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"increment_debt"` - IncrementCollateral github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=increment_collateral,json=incrementCollateral,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"increment_collateral"` -} - -func (m *Params) Reset() { *m = Params{} } -func (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_d0e5cb58293042f7, []int{1} -} -func (m *Params) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Params.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Params) XXX_Merge(src proto.Message) { - xxx_messageInfo_Params.Merge(m, src) -} -func (m *Params) XXX_Size() int { - return m.Size() -} -func (m *Params) XXX_DiscardUnknown() { - xxx_messageInfo_Params.DiscardUnknown(m) -} - -var xxx_messageInfo_Params proto.InternalMessageInfo - -var fileDescriptor_d0e5cb58293042f7 = []byte{ - // 466 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x93, 0x31, 0x6f, 0xd3, 0x40, - 0x14, 0xc7, 0x7d, 0x4d, 0x88, 0xaa, 0x4b, 0x5a, 0xe0, 0xf0, 0xe0, 0x56, 0xc8, 0x89, 0x32, 0x54, - 0x61, 0xc8, 0x59, 0x0d, 0x1b, 0x5b, 0x4d, 0x44, 0xc5, 0x86, 0x5c, 0x75, 0x81, 0x21, 0xba, 0xb3, - 0x0f, 0x63, 0xd5, 0xf6, 0x45, 0xbe, 0x73, 0x95, 0x7c, 0x0b, 0x46, 0x3e, 0x08, 0x03, 0x13, 0x73, - 0xc4, 0xd4, 0x11, 0x31, 0x14, 0x48, 0xbe, 0x08, 0xf2, 0xdd, 0xe5, 0x82, 0x80, 0x01, 0x75, 0xca, - 0xdd, 0x7b, 0xff, 0xff, 0xef, 0xfd, 0x9f, 0x2e, 0x86, 0xc3, 0x2b, 0x72, 0x4d, 0x02, 0x52, 0xc7, - 0x32, 0xe3, 0x65, 0x70, 0x7d, 0x4a, 0x99, 0x24, 0xa7, 0x41, 0xca, 0x4a, 0x26, 0x32, 0x81, 0xe7, - 0x15, 0x97, 0x1c, 0xb9, 0x8d, 0x06, 0x1b, 0x0d, 0x36, 0x9a, 0x63, 0x37, 0xe5, 0x29, 0x57, 0x82, - 0xa0, 0x39, 0x69, 0xed, 0xf1, 0x51, 0xca, 0x79, 0x9a, 0xb3, 0x40, 0xdd, 0x68, 0xfd, 0x36, 0x20, - 0xe5, 0x72, 0xdb, 0x8a, 0xb9, 0x28, 0xb8, 0x98, 0x69, 0x8f, 0xbe, 0x98, 0x96, 0xff, 0xa7, 0x2b, - 0xa9, 0x2b, 0xa2, 0xa6, 0xa9, 0xca, 0xf0, 0x13, 0x80, 0xbd, 0x73, 0x9d, 0xe9, 0x42, 0x12, 0xc9, - 0xd0, 0x09, 0xbc, 0x5f, 0xb2, 0x85, 0x9c, 0x99, 0x50, 0xb3, 0x2c, 0xf1, 0xc0, 0x00, 0x8c, 0xda, - 0xd1, 0x41, 0x53, 0x3e, 0xd3, 0xd5, 0x97, 0x09, 0x7a, 0x06, 0x3b, 0x73, 0x52, 0x91, 0x42, 0x78, - 0x7b, 0x03, 0x30, 0xea, 0x4e, 0x1e, 0xe3, 0x7f, 0xed, 0x82, 0x5f, 0x29, 0x4d, 0xd8, 0x5e, 0xdd, - 0xf6, 0x9d, 0xc8, 0x38, 0xd0, 0x14, 0xee, 0x1b, 0x9d, 0xf0, 0x5a, 0x83, 0xd6, 0xa8, 0x3b, 0x71, - 0xb1, 0xce, 0x89, 0xb7, 0x39, 0xf1, 0x59, 0xb9, 0x0c, 0xd1, 0x97, 0x8f, 0xe3, 0x43, 0x93, 0xce, - 0x4c, 0x8e, 0xac, 0x73, 0xf8, 0xb9, 0x05, 0x3b, 0x1a, 0x8f, 0x2e, 0xa1, 0x5b, 0x90, 0x85, 0xcd, - 0xbc, 0xdd, 0x51, 0x25, 0xef, 0x4e, 0x8e, 0xfe, 0x82, 0x4f, 0x8d, 0x20, 0xdc, 0x6f, 0x72, 0x7d, - 0xf8, 0xde, 0x07, 0x11, 0x2a, 0xc8, 0xc2, 0xcc, 0xd8, 0x76, 0xd1, 0x0b, 0xd8, 0xa3, 0x59, 0xb2, - 0xc3, 0xed, 0xfd, 0x3f, 0xae, 0x4b, 0xb3, 0xc4, 0x72, 0xde, 0xc0, 0x87, 0x59, 0x19, 0x57, 0xac, - 0x60, 0xa5, 0x9c, 0x89, 0xba, 0x9a, 0xe7, 0x75, 0xb3, 0x38, 0x18, 0xf5, 0x42, 0xdc, 0x38, 0xbe, - 0xdd, 0xf6, 0x4f, 0xd2, 0x4c, 0xbe, 0xab, 0x29, 0x8e, 0x79, 0x61, 0x1e, 0xd0, 0xfc, 0x8c, 0x45, - 0x72, 0x15, 0xc8, 0xe5, 0x9c, 0x09, 0x3c, 0x65, 0x71, 0xf4, 0xc0, 0x82, 0x2e, 0x34, 0x07, 0x5d, - 0xc2, 0xc3, 0x1d, 0x3c, 0x61, 0x54, 0x7a, 0xed, 0x3b, 0x91, 0x0f, 0x2c, 0x65, 0xca, 0xa8, 0x44, - 0x04, 0xba, 0x3b, 0x6c, 0xcc, 0xf3, 0x9c, 0x48, 0x56, 0x91, 0xdc, 0xbb, 0x77, 0x27, 0xf8, 0x23, - 0xcb, 0x7a, 0x6e, 0x51, 0xe1, 0xf9, 0xea, 0xa7, 0xef, 0xac, 0xd6, 0x3e, 0xb8, 0x59, 0xfb, 0xe0, - 0xc7, 0xda, 0x07, 0xef, 0x37, 0xbe, 0x73, 0xb3, 0xf1, 0x9d, 0xaf, 0x1b, 0xdf, 0x79, 0xfd, 0xe4, - 0x37, 0x74, 0xf3, 0xd7, 0x1a, 0xe7, 0x84, 0x0a, 0x75, 0x0a, 0x16, 0xf6, 0xb3, 0x52, 0x13, 0x68, - 0x47, 0xbd, 0xc4, 0xd3, 0x5f, 0x01, 0x00, 0x00, 0xff, 0xff, 0xa5, 0x20, 0xff, 0x87, 0x73, 0x03, - 0x00, 0x00, -} - -func (m *GenesisState) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Auctions) > 0 { - for iNdEx := len(m.Auctions) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Auctions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.NextAuctionId != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.NextAuctionId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *Params) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Params) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.IncrementCollateral.Size() - i -= size - if _, err := m.IncrementCollateral.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.IncrementDebt.Size() - i -= size - if _, err := m.IncrementDebt.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.IncrementSurplus.Size() - i -= size - if _, err := m.IncrementSurplus.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - n2, err2 := github_com_gogo_protobuf_types.StdDurationMarshalTo(m.BidDuration, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdDuration(m.BidDuration):]) - if err2 != nil { - return 0, err2 - } - i -= n2 - i = encodeVarintGenesis(dAtA, i, uint64(n2)) - i-- - dAtA[i] = 0x12 - n3, err3 := github_com_gogo_protobuf_types.StdDurationMarshalTo(m.MaxAuctionDuration, dAtA[i-github_com_gogo_protobuf_types.SizeOfStdDuration(m.MaxAuctionDuration):]) - if err3 != nil { - return 0, err3 - } - i -= n3 - i = encodeVarintGenesis(dAtA, i, uint64(n3)) - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *GenesisState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.NextAuctionId != 0 { - n += 1 + sovGenesis(uint64(m.NextAuctionId)) - } - l = m.Params.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.Auctions) > 0 { - for _, e := range m.Auctions { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = github_com_gogo_protobuf_types.SizeOfStdDuration(m.MaxAuctionDuration) - n += 1 + l + sovGenesis(uint64(l)) - l = github_com_gogo_protobuf_types.SizeOfStdDuration(m.BidDuration) - n += 1 + l + sovGenesis(uint64(l)) - l = m.IncrementSurplus.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.IncrementDebt.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.IncrementCollateral.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *GenesisState) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field NextAuctionId", wireType) - } - m.NextAuctionId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.NextAuctionId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Auctions", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Auctions = append(m.Auctions, &types.Any{}) - if err := m.Auctions[len(m.Auctions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Params) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Params: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaxAuctionDuration", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_gogo_protobuf_types.StdDurationUnmarshal(&m.MaxAuctionDuration, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BidDuration", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_gogo_protobuf_types.StdDurationUnmarshal(&m.BidDuration, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IncrementSurplus", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IncrementSurplus.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IncrementDebt", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IncrementDebt.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IncrementCollateral", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IncrementCollateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/auction/legacy/v0_16/testdata/v15-auction.json b/x/auction/legacy/v0_16/testdata/v15-auction.json deleted file mode 100644 index c8b24f95..00000000 --- a/x/auction/legacy/v0_16/testdata/v15-auction.json +++ /dev/null @@ -1,91 +0,0 @@ -{ - "auctions": [ - { - "type": "auction/CollateralAuction", - "value": { - "base_auction": { - "bid": { - "amount": "0", - "denom": "bnb" - }, - "bidder": "", - "end_time": "9000-01-01T00:00:00Z", - "has_received_bids": false, - "id": "3795", - "initiator": "hard", - "lot": { - "amount": "1", - "denom": "bnb" - }, - "max_end_time": "9000-01-01T00:00:00Z" - }, - "corresponding_debt": { - "amount": "0", - "denom": "debt" - }, - "lot_returns": { - "addresses": ["kava1eevfnzkf2mt6feyttyzh6ektclauq7zlayefwf"], - "weights": ["100"] - }, - "max_bid": { - "amount": "1", - "denom": "bnb" - } - } - }, - { - "type": "auction/SurplusAuction", - "value": { - "base_auction": { - "bid": { - "amount": "0", - "denom": "bnb" - }, - "bidder": "", - "end_time": "9000-01-01T00:00:00Z", - "has_received_bids": false, - "id": "3796", - "initiator": "hard", - "lot": { - "amount": "1", - "denom": "bnb" - }, - "max_end_time": "9000-01-01T00:00:00Z" - } - } - }, - { - "type": "auction/DebtAuction", - "value": { - "base_auction": { - "bid": { - "amount": "0", - "denom": "bnb" - }, - "bidder": "", - "end_time": "9000-01-01T00:00:00Z", - "has_received_bids": false, - "id": "3895", - "initiator": "hard", - "lot": { - "amount": "1", - "denom": "bnb" - }, - "max_end_time": "9000-01-01T00:00:00Z" - }, - "corresponding_debt": { - "amount": "0", - "denom": "debt" - } - } - } - ], - "next_auction_id": "12", - "params": { - "bid_duration": "600000000000", - "increment_collateral": "0.010000000000000000", - "increment_debt": "0.010000000000000000", - "increment_surplus": "0.010000000000000000", - "max_auction_duration": "172800000000000" - } -} diff --git a/x/auction/legacy/v0_16/testdata/v16-auction.json b/x/auction/legacy/v0_16/testdata/v16-auction.json deleted file mode 100644 index 17299cd3..00000000 --- a/x/auction/legacy/v0_16/testdata/v16-auction.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "next_auction_id": "12", - "params": { - "max_auction_duration": "172800s", - "bid_duration": "600s", - "increment_surplus": "0.010000000000000000", - "increment_debt": "0.010000000000000000", - "increment_collateral": "0.010000000000000000" - }, - "auctions": [ - { - "@type": "/kava.auction.v1beta1.CollateralAuction", - "base_auction": { - "id": "3795", - "initiator": "hard", - "lot": { "denom": "bnb", "amount": "1" }, - "bidder": "", - "bid": { "denom": "bnb", "amount": "0" }, - "has_received_bids": false, - "end_time": "9000-01-01T00:00:00Z", - "max_end_time": "9000-01-01T00:00:00Z" - }, - "corresponding_debt": { "denom": "debt", "amount": "0" }, - "max_bid": { "denom": "bnb", "amount": "1" }, - "lot_returns": { - "addresses": ["kava1eevfnzkf2mt6feyttyzh6ektclauq7zlayefwf"], - "weights": ["100"] - } - }, - { - "@type": "/kava.auction.v1beta1.SurplusAuction", - "base_auction": { - "id": "3796", - "initiator": "hard", - "lot": { "denom": "bnb", "amount": "1" }, - "bidder": "", - "bid": { "denom": "bnb", "amount": "0" }, - "has_received_bids": false, - "end_time": "9000-01-01T00:00:00Z", - "max_end_time": "9000-01-01T00:00:00Z" - } - }, - { - "@type": "/kava.auction.v1beta1.DebtAuction", - "base_auction": { - "id": "3895", - "initiator": "hard", - "lot": { "denom": "bnb", "amount": "1" }, - "bidder": "", - "bid": { "denom": "bnb", "amount": "0" }, - "has_received_bids": false, - "end_time": "9000-01-01T00:00:00Z", - "max_end_time": "9000-01-01T00:00:00Z" - }, - "corresponding_debt": { "denom": "debt", "amount": "0" } - } - ] -} diff --git a/x/auction/legacy/v0_17/migrate.go b/x/auction/legacy/v0_17/migrate.go deleted file mode 100644 index fb547c95..00000000 --- a/x/auction/legacy/v0_17/migrate.go +++ /dev/null @@ -1,25 +0,0 @@ -package v0_17 - -import ( - v016auction "github.com/0glabs/0g-chain/x/auction/legacy/v0_16" - v017auction "github.com/0glabs/0g-chain/x/auction/types" -) - -func Migrate(oldState v016auction.GenesisState) *v017auction.GenesisState { - return &v017auction.GenesisState{ - NextAuctionId: oldState.NextAuctionId, - Params: migrateParams(oldState.Params), - Auctions: oldState.Auctions, - } -} - -func migrateParams(params v016auction.Params) v017auction.Params { - return v017auction.Params{ - MaxAuctionDuration: params.MaxAuctionDuration, - ForwardBidDuration: v017auction.DefaultForwardBidDuration, - ReverseBidDuration: v017auction.DefaultReverseBidDuration, - IncrementSurplus: params.IncrementSurplus, - IncrementDebt: params.IncrementDebt, - IncrementCollateral: params.IncrementCollateral, - } -} diff --git a/x/auction/module.go b/x/auction/module.go deleted file mode 100644 index 68dbaaad..00000000 --- a/x/auction/module.go +++ /dev/null @@ -1,139 +0,0 @@ -package auction - -import ( - "context" - "encoding/json" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/0glabs/0g-chain/x/auction/client/cli" - "github.com/0glabs/0g-chain/x/auction/keeper" - "github.com/0glabs/0g-chain/x/auction/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic implements the sdk.AppModuleBasic interface. -type AppModuleBasic struct{} - -// Name returns the module name. -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - err := cdc.UnmarshalJSON(bz, &gs) - if err != nil { - return err - } - return gs.Validate() -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the gov module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) -} - -// GetTxCmd returns the root tx command for the swap module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the swap module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -//____________________________________________________________________________ - -// AppModule implements the sdk.AppModule interface. -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, accountKeeper types.AccountKeeper, bankKeeper types.BankKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - } -} - -// Name module name -func (AppModule) Name() string { - return types.ModuleName -} - -// RegisterInvariants register module invariants -func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return 1 -} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) -} - -// InitGenesis module init-genesis -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { - var genState types.GenesisState - cdc.MustUnmarshalJSON(gs, &genState) - InitGenesis(ctx, am.keeper, am.bankKeeper, am.accountKeeper, &genState) - - return []abci.ValidatorUpdate{} -} - -// ExportGenesis module export genesis -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(gs) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { - BeginBlocker(ctx, am.keeper) -} - -// EndBlock module end-block -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/auction/spec/01_concepts.md b/x/auction/spec/01_concepts.md deleted file mode 100644 index 9c47f348..00000000 --- a/x/auction/spec/01_concepts.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# Concepts - -Auctions are broken down into three distinct types, which correspond to three specific functionalities within the CDP system. - -* **Surplus Auction:** An auction in which a fixed lot of coins (c1) is sold for increasing amounts of other coins (c2). Bidders increment the amount of c2 they are willing to pay for the lot of c1. After the completion of a surplus auction, the winning bid of c2 is burned, and the bidder receives the lot of c1. As a concrete example, surplus auction are used to sell a fixed amount of USDX stable coins in exchange for increasing bids of KAVA governance tokens. The governance tokens are then burned and the winner receives USDX. -* **Debt Auction:** An auction in which a fixed amount of coins (c1) is bid for a decreasing lot of other coins (c2). Bidders decrement the lot of c2 they are willing to receive for the fixed amount of c1. As a concrete example, debt auctions are used to raise a certain amount of USDX stable coins in exchange for decreasing lots of KAVA governance tokens. The USDX tokens are used to recapitalize the cdp system and the winner receives KAVA. -* **Surplus Reverse Auction:** Are two phase auction is which a fixed lot of coins (c1) is sold for increasing amounts of other coins (c2). Bidders increment the amount of c2 until a specific `maxBid` is reached. Once `maxBid` is reached, a fixed amount of c2 is bid for a decreasing lot of c1. In the second phase, bidders decrement the lot of c1 they are willing to receive for a fixed amount of c2. As a concrete example, collateral auctions are used to sell collateral (ATOM, for example) for up to a `maxBid` amount of USDX. The USDX tokens are used to recapitalize the cdp system and the winner receives the specified lot of ATOM. In the event that the winning lot is smaller than the total lot, the excess ATOM is ratably returned to the original owners of the liquidated CDPs that were collateralized with that ATOM. - -Auctions are always initiated by another module, and not directly by users. Auctions start with an expiry, the time at which the auction is guaranteed to end, even if there have been no bidders. After each bid, the auction is extended by a specific amount of time, `BidDuration`. In the case that increasing the auction time by `BidDuration` would cause the auction to go past its expiry, the expiry is chosen as the ending time. diff --git a/x/auction/spec/02_state.md b/x/auction/spec/02_state.md deleted file mode 100644 index 335866e7..00000000 --- a/x/auction/spec/02_state.md +++ /dev/null @@ -1,82 +0,0 @@ - - -# State - -## Parameters and genesis state - -`parameters` define the rules according to which auctions are run. There is only one active parameter set at any given time. Updates to the parameter set can be made via on-chain parameter update proposals. - -```go -// Params governance parameters for auction module -type Params struct { - MaxAuctionDuration time.Duration `json:"max_auction_duration" yaml:"max_auction_duration"` // max length of auction - MaxBidDuration time.Duration `json:"max_bid_duration" yaml:"max_bid_duration"` // additional time added to the auction end time after each bid, capped by the expiry. - IncrementSurplus sdk.Dec `json:"increment_surplus" yaml:"increment_surplus"` // percentage change (of auc.Bid) required for a new bid on a surplus auction - IncrementDebt sdk.Dec `json:"increment_debt" yaml:"increment_debt"` // percentage change (of auc.Lot) required for a new bid on a debt auction - IncrementCollateral sdk.Dec `json:"increment_collateral" yaml:"increment_collateral"` // percentage change (of auc.Bid or auc.Lot) required for a new bid on a collateral auction -} -``` - -`GenesisState` defines the state that must be persisted when the blockchain stops/restarts in order for normal function of the auction module to resume. - -```go -// GenesisState - auction state that must be provided at genesis -type GenesisState struct { - NextAuctionID uint64 `json:"next_auction_id" yaml:"next_auction_id"` // auctionID that will be used for the next created auction - Params Params `json:"auction_params" yaml:"auction_params"` // auction params - Auctions Auctions `json:"genesis_auctions" yaml:"genesis_auctions"` // auctions currently in the store -} -``` - -## Base types - -```go -// Auction is an interface to several types of auction. -type Auction interface { - GetID() uint64 - WithID(uint64) Auction - GetEndTime() time.Time -} - -// BaseAuction is a common type shared by all Auctions. -type BaseAuction struct { - ID uint64 - Initiator string // Module name that starts the auction. Pays out Lot. - Lot sdk.Coin // Coins that will paid out by Initiator to the winning bidder. - Bidder sdk.AccAddress // Latest bidder. Receiver of Lot. - Bid sdk.Coin // Coins paid into the auction the bidder. - EndTime time.Time // Current auction closing time. Triggers at the end of the block with time ≥ EndTime. - MaxEndTime time.Time // Maximum closing time. Auctions can close before this but never after. -} - -// SurplusAuction is a forward auction that burns what it receives from bids. -// It is normally used to sell off excess pegged asset acquired by the CDP system. -type SurplusAuction struct { - BaseAuction -} - -// DebtAuction is a reverse auction that mints what it pays out. -// It is normally used to acquire pegged asset to cover the CDP system's debts that were not covered by selling collateral. -type DebtAuction struct { - BaseAuction -} - -// WeightedAddresses is a type for storing some addresses and associated weights. -type WeightedAddresses struct { - Addresses []sdk.AccAddress - Weights []sdkmath.Int -} - -// CollateralAuction is a two phase auction. -// Initially, in forward auction phase, bids can be placed up to a max bid. -// Then it switches to a reverse auction phase, where the initial amount up for auction is bid down. -// Unsold Lot is sent to LotReturns, being divided among the addresses by weight. -// Collateral auctions are normally used to sell off collateral seized from CDPs. -type CollateralAuction struct { - BaseAuction - MaxBid sdk.Coin - LotReturns WeightedAddresses -} -``` diff --git a/x/auction/spec/03_messages.md b/x/auction/spec/03_messages.md deleted file mode 100644 index 92fff7a5..00000000 --- a/x/auction/spec/03_messages.md +++ /dev/null @@ -1,36 +0,0 @@ - - -# Messages - -## Bidding - -Users can bid on auctions using the `MsgPlaceBid` message type. All auction types can be bid on using the same message type. - -```go -// MsgPlaceBid is the message type used to place a bid on any type of auction. -type MsgPlaceBid struct { - AuctionID uint64 - Bidder sdk.AccAddress - Amount sdk.Coin -} -``` - -**State Modifications:** - -* Update bidder if different than previous bidder -* For Surplus auctions: - * Update Bid to msg.Amount - * Return bid coins to previous bidder - * Burn coins equal to the increment in the bid (CurrentBid - PreviousBid) -* For Debt auctions: - * Update Lot amount to msg.Amount - * Return bid coins to previous bidder -* For Collateral auctions: - * Return bid coins to previous bidder - * If in forward phase: - * Update Bid amount to msg.Amount - * If in reverse phase: - * Update Lot amount to msg.Amount -* Extend auction by `BidDuration`, up to `MaxEndTime` diff --git a/x/auction/spec/04_events.md b/x/auction/spec/04_events.md deleted file mode 100644 index 36992c04..00000000 --- a/x/auction/spec/04_events.md +++ /dev/null @@ -1,38 +0,0 @@ - - -# Events - -The `x/auction` module emits the following events: - -## Triggered By Other Modules - -| Type | Attribute Key | Attribute Value | -|---------------|---------------|-------------------| -| auction_start | auction_id | `{auction ID}` | -| auction_start | auction_type | `{auction type}` | -| auction_start | lot | `{coin amount}` | -| auction_start | bid | `{coin amount}` | -| auction_start | max_bid | `{coin amount}` | - -## Handlers - -### MsgPlaceBid - -| Type | Attribute Key | Attribute Value | -|-------------|---------------|----------------------| -| auction_bid | auction_id | `{auction ID}` | -| auction_bid | bidder | `{latest bidder}` | -| auction_bid | bid | `{coin amount}` | -| auction_bid | lot | `{coin amount}` | -| auction_bid | end_time | `{auction end time}` | -| message | module | auction | -| message | sender | `{sender address}` | - -## BeginBlock - -| Type | Attribute Key | Attribute Value | -|---------------|---------------|-------------------| -| auction_close | auction_id | `{auction ID}` | -| auction_close | close_block | `{block height}` | diff --git a/x/auction/spec/05_params.md b/x/auction/spec/05_params.md deleted file mode 100644 index 88960f9c..00000000 --- a/x/auction/spec/05_params.md +++ /dev/null @@ -1,15 +0,0 @@ - - -# Parameters - -The auction module contains the following parameters: - -| Key | Type | Example | Description | -|---------------------|------------------------|------------------------|---------------------------------------------------------------------------------------| -| MaxAuctionDuration | string (time.Duration) | "48h0m0s" | | -| BidDuration | string (time.Duration) | "3h0m0s" | | -| IncrementSurplus | string (dec) | "0.050000000000000000" | percentage change in bid required for a new bid on a surplus auction | -| IncrementDebt | string (dec) | "0.050000000000000000" | percentage change in lot required for a new bid on a debt auction | -| IncrementCollateral | string (dec) | "0.050000000000000000" | percentage change in either bid or lot required for a new bid on a collateral auction | diff --git a/x/auction/spec/06_begin_block.md b/x/auction/spec/06_begin_block.md deleted file mode 100644 index 64c6a6a0..00000000 --- a/x/auction/spec/06_begin_block.md +++ /dev/null @@ -1,22 +0,0 @@ - - -# Begin Block - -At the start of each block, auctions that have reached `EndTime` are closed. The logic to close auctions is as follows: - -```go -var expiredAuctions []uint64 - k.IterateAuctionsByTime(ctx, ctx.BlockTime(), func(id uint64) bool { - expiredAuctions = append(expiredAuctions, id) - return false - }) - - for _, id := range expiredAuctions { - err := k.CloseAuction(ctx, id) - if err != nil { - panic(err) - } - } -``` diff --git a/x/auction/spec/README.md b/x/auction/spec/README.md deleted file mode 100644 index 5ba72788..00000000 --- a/x/auction/spec/README.md +++ /dev/null @@ -1,20 +0,0 @@ - - -# `auction` - - -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** -5. **[Params](05_params.md)** -6. **[BeginBlock](06_begin_block.md)** - -## Abstract - -`x/auction` is an implementation of a Cosmos SDK Module that handles the creation, bidding, and payout of 3 distinct auction types. All auction types implement the `Auction` interface. Each auction type is used at different points during the normal functioning of the CDP system. diff --git a/x/auction/testutil/suite.go b/x/auction/testutil/suite.go deleted file mode 100644 index 2e44e3a1..00000000 --- a/x/auction/testutil/suite.go +++ /dev/null @@ -1,92 +0,0 @@ -package testutil - -import ( - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/auction/keeper" - "github.com/0glabs/0g-chain/x/auction/types" -) - -// Suite implements a test suite for the kavadist module integration tests -type Suite struct { - suite.Suite - - Keeper keeper.Keeper - BankKeeper bankkeeper.Keeper - AccountKeeper authkeeper.AccountKeeper - App app.TestApp - Ctx sdk.Context - Addrs []sdk.AccAddress - ModAcc *authtypes.ModuleAccount -} - -// SetupTest instantiates a new app, keepers, and sets suite state -func (suite *Suite) SetupTest(numAddrs int) { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - tApp := app.NewTestApp() - - _, addrs := app.GeneratePrivKeyAddressPairs(numAddrs) - - // Fund liquidator module account - coins := sdk.NewCoins( - sdk.NewCoin("token1", sdkmath.NewInt(100)), - sdk.NewCoin("token2", sdkmath.NewInt(100)), - ) - - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - modName := "liquidator" - modBaseAcc := authtypes.NewBaseAccount(authtypes.NewModuleAddress(modName), nil, 0, 0) - modAcc := authtypes.NewModuleAccount(modBaseAcc, modName, []string{authtypes.Minter, authtypes.Burner}...) - suite.ModAcc = modAcc - - authGS := app.NewFundedGenStateWithSameCoinsWithModuleAccount(tApp.AppCodec(), coins, addrs, modAcc) - - params := types.NewParams( - types.DefaultMaxAuctionDuration, - types.DefaultForwardBidDuration, - types.DefaultReverseBidDuration, - types.DefaultIncrement, - types.DefaultIncrement, - types.DefaultIncrement, - ) - - auctionGs, err := types.NewGenesisState(types.DefaultNextAuctionID, params, []types.GenesisAuction{}) - suite.Require().NoError(err) - - moduleGs := tApp.AppCodec().MustMarshalJSON(auctionGs) - gs := app.GenesisState{types.ModuleName: moduleGs} - tApp.InitializeFromGenesisStates(authGS, gs) - - suite.App = tApp - suite.Ctx = ctx - suite.Addrs = addrs - suite.Keeper = tApp.GetAuctionKeeper() - suite.BankKeeper = tApp.GetBankKeeper() - suite.AccountKeeper = tApp.GetAccountKeeper() -} - -// AddCoinsToModule adds coins to a named module account -func (suite *Suite) AddCoinsToNamedModule(moduleName string, amount sdk.Coins) { - // Does not use suite.BankKeeper.MintCoins as module account would not have permission to mint - err := suite.App.FundModuleAccount(suite.Ctx, moduleName, amount) - suite.Require().NoError(err) -} - -// CheckAccountBalanceEqual asserts that -func (suite *Suite) CheckAccountBalanceEqual(owner sdk.AccAddress, expectedCoins sdk.Coins) { - balances := suite.BankKeeper.GetAllBalances(suite.Ctx, owner) - suite.Equal(expectedCoins, balances) -} diff --git a/x/auction/types/auction.pb.go b/x/auction/types/auction.pb.go deleted file mode 100644 index 70d13504..00000000 --- a/x/auction/types/auction.pb.go +++ /dev/null @@ -1,1551 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/auction/v1beta1/auction.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// BaseAuction defines common attributes of all auctions -type BaseAuction struct { - ID uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` - Initiator string `protobuf:"bytes,2,opt,name=initiator,proto3" json:"initiator,omitempty"` - Lot types.Coin `protobuf:"bytes,3,opt,name=lot,proto3" json:"lot"` - Bidder github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,4,opt,name=bidder,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"bidder,omitempty"` - Bid types.Coin `protobuf:"bytes,5,opt,name=bid,proto3" json:"bid"` - HasReceivedBids bool `protobuf:"varint,6,opt,name=has_received_bids,json=hasReceivedBids,proto3" json:"has_received_bids,omitempty"` - EndTime time.Time `protobuf:"bytes,7,opt,name=end_time,json=endTime,proto3,stdtime" json:"end_time"` - MaxEndTime time.Time `protobuf:"bytes,8,opt,name=max_end_time,json=maxEndTime,proto3,stdtime" json:"max_end_time"` -} - -func (m *BaseAuction) Reset() { *m = BaseAuction{} } -func (m *BaseAuction) String() string { return proto.CompactTextString(m) } -func (*BaseAuction) ProtoMessage() {} -func (*BaseAuction) Descriptor() ([]byte, []int) { - return fileDescriptor_b9b5dac2c776ef9e, []int{0} -} -func (m *BaseAuction) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *BaseAuction) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_BaseAuction.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *BaseAuction) XXX_Merge(src proto.Message) { - xxx_messageInfo_BaseAuction.Merge(m, src) -} -func (m *BaseAuction) XXX_Size() int { - return m.Size() -} -func (m *BaseAuction) XXX_DiscardUnknown() { - xxx_messageInfo_BaseAuction.DiscardUnknown(m) -} - -var xxx_messageInfo_BaseAuction proto.InternalMessageInfo - -// SurplusAuction is a forward auction that burns what it receives from bids. -// It is normally used to sell off excess pegged asset acquired by the CDP system. -type SurplusAuction struct { - BaseAuction `protobuf:"bytes,1,opt,name=base_auction,json=baseAuction,proto3,embedded=base_auction" json:"base_auction"` -} - -func (m *SurplusAuction) Reset() { *m = SurplusAuction{} } -func (m *SurplusAuction) String() string { return proto.CompactTextString(m) } -func (*SurplusAuction) ProtoMessage() {} -func (*SurplusAuction) Descriptor() ([]byte, []int) { - return fileDescriptor_b9b5dac2c776ef9e, []int{1} -} -func (m *SurplusAuction) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *SurplusAuction) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SurplusAuction.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *SurplusAuction) XXX_Merge(src proto.Message) { - xxx_messageInfo_SurplusAuction.Merge(m, src) -} -func (m *SurplusAuction) XXX_Size() int { - return m.Size() -} -func (m *SurplusAuction) XXX_DiscardUnknown() { - xxx_messageInfo_SurplusAuction.DiscardUnknown(m) -} - -var xxx_messageInfo_SurplusAuction proto.InternalMessageInfo - -// DebtAuction is a reverse auction that mints what it pays out. -// It is normally used to acquire pegged asset to cover the CDP system's debts that were not covered by selling -// collateral. -type DebtAuction struct { - BaseAuction `protobuf:"bytes,1,opt,name=base_auction,json=baseAuction,proto3,embedded=base_auction" json:"base_auction"` - CorrespondingDebt types.Coin `protobuf:"bytes,2,opt,name=corresponding_debt,json=correspondingDebt,proto3" json:"corresponding_debt"` -} - -func (m *DebtAuction) Reset() { *m = DebtAuction{} } -func (m *DebtAuction) String() string { return proto.CompactTextString(m) } -func (*DebtAuction) ProtoMessage() {} -func (*DebtAuction) Descriptor() ([]byte, []int) { - return fileDescriptor_b9b5dac2c776ef9e, []int{2} -} -func (m *DebtAuction) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DebtAuction) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DebtAuction.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *DebtAuction) XXX_Merge(src proto.Message) { - xxx_messageInfo_DebtAuction.Merge(m, src) -} -func (m *DebtAuction) XXX_Size() int { - return m.Size() -} -func (m *DebtAuction) XXX_DiscardUnknown() { - xxx_messageInfo_DebtAuction.DiscardUnknown(m) -} - -var xxx_messageInfo_DebtAuction proto.InternalMessageInfo - -// CollateralAuction is a two phase auction. -// Initially, in forward auction phase, bids can be placed up to a max bid. -// Then it switches to a reverse auction phase, where the initial amount up for auction is bid down. -// Unsold Lot is sent to LotReturns, being divided among the addresses by weight. -// Collateral auctions are normally used to sell off collateral seized from CDPs. -type CollateralAuction struct { - BaseAuction `protobuf:"bytes,1,opt,name=base_auction,json=baseAuction,proto3,embedded=base_auction" json:"base_auction"` - CorrespondingDebt types.Coin `protobuf:"bytes,2,opt,name=corresponding_debt,json=correspondingDebt,proto3" json:"corresponding_debt"` - MaxBid types.Coin `protobuf:"bytes,3,opt,name=max_bid,json=maxBid,proto3" json:"max_bid"` - LotReturns WeightedAddresses `protobuf:"bytes,4,opt,name=lot_returns,json=lotReturns,proto3" json:"lot_returns"` -} - -func (m *CollateralAuction) Reset() { *m = CollateralAuction{} } -func (m *CollateralAuction) String() string { return proto.CompactTextString(m) } -func (*CollateralAuction) ProtoMessage() {} -func (*CollateralAuction) Descriptor() ([]byte, []int) { - return fileDescriptor_b9b5dac2c776ef9e, []int{3} -} -func (m *CollateralAuction) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CollateralAuction) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CollateralAuction.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CollateralAuction) XXX_Merge(src proto.Message) { - xxx_messageInfo_CollateralAuction.Merge(m, src) -} -func (m *CollateralAuction) XXX_Size() int { - return m.Size() -} -func (m *CollateralAuction) XXX_DiscardUnknown() { - xxx_messageInfo_CollateralAuction.DiscardUnknown(m) -} - -var xxx_messageInfo_CollateralAuction proto.InternalMessageInfo - -// WeightedAddresses is a type for storing some addresses and associated weights. -type WeightedAddresses struct { - Addresses []github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,rep,name=addresses,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"addresses,omitempty"` - Weights []github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,rep,name=weights,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"weights"` -} - -func (m *WeightedAddresses) Reset() { *m = WeightedAddresses{} } -func (m *WeightedAddresses) String() string { return proto.CompactTextString(m) } -func (*WeightedAddresses) ProtoMessage() {} -func (*WeightedAddresses) Descriptor() ([]byte, []int) { - return fileDescriptor_b9b5dac2c776ef9e, []int{4} -} -func (m *WeightedAddresses) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *WeightedAddresses) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_WeightedAddresses.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *WeightedAddresses) XXX_Merge(src proto.Message) { - xxx_messageInfo_WeightedAddresses.Merge(m, src) -} -func (m *WeightedAddresses) XXX_Size() int { - return m.Size() -} -func (m *WeightedAddresses) XXX_DiscardUnknown() { - xxx_messageInfo_WeightedAddresses.DiscardUnknown(m) -} - -var xxx_messageInfo_WeightedAddresses proto.InternalMessageInfo - -func init() { - proto.RegisterType((*BaseAuction)(nil), "kava.auction.v1beta1.BaseAuction") - proto.RegisterType((*SurplusAuction)(nil), "kava.auction.v1beta1.SurplusAuction") - proto.RegisterType((*DebtAuction)(nil), "kava.auction.v1beta1.DebtAuction") - proto.RegisterType((*CollateralAuction)(nil), "kava.auction.v1beta1.CollateralAuction") - proto.RegisterType((*WeightedAddresses)(nil), "kava.auction.v1beta1.WeightedAddresses") -} - -func init() { - proto.RegisterFile("kava/auction/v1beta1/auction.proto", fileDescriptor_b9b5dac2c776ef9e) -} - -var fileDescriptor_b9b5dac2c776ef9e = []byte{ - // 662 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x54, 0xcd, 0x6e, 0xd3, 0x4a, - 0x14, 0xce, 0x24, 0xbd, 0x49, 0x3a, 0xae, 0xee, 0x55, 0xe6, 0x56, 0x57, 0x6e, 0x75, 0x65, 0x87, - 0x2e, 0x20, 0xaa, 0x14, 0xbb, 0x2d, 0x1b, 0xc4, 0x06, 0xd5, 0x2d, 0xa8, 0xdd, 0x74, 0x61, 0x90, - 0x90, 0xd8, 0x98, 0xb1, 0x67, 0xea, 0x8c, 0x6a, 0x7b, 0x22, 0xcf, 0xa4, 0xa4, 0x6f, 0xd1, 0x87, - 0xe9, 0x8a, 0x3d, 0x52, 0x55, 0x09, 0xa9, 0x62, 0x85, 0x58, 0x04, 0x48, 0xdf, 0x82, 0x15, 0x1a, - 0x7b, 0xdc, 0x36, 0xa2, 0x8b, 0x20, 0xc1, 0x82, 0x55, 0x72, 0xbe, 0x39, 0xe7, 0xfb, 0xce, 0xaf, - 0xe1, 0xda, 0x11, 0x3e, 0xc6, 0x2e, 0x1e, 0x45, 0x92, 0xf1, 0xcc, 0x3d, 0xde, 0x0c, 0xa9, 0xc4, - 0x9b, 0x95, 0xed, 0x0c, 0x73, 0x2e, 0x39, 0x5a, 0x56, 0x3e, 0x4e, 0x85, 0x69, 0x9f, 0x55, 0x2b, - 0xe2, 0x22, 0xe5, 0xc2, 0x0d, 0xb1, 0xa0, 0xd7, 0x81, 0x11, 0x67, 0x3a, 0x6a, 0x75, 0xa5, 0x7c, - 0x0f, 0x0a, 0xcb, 0x2d, 0x0d, 0xfd, 0xb4, 0x1c, 0xf3, 0x98, 0x97, 0xb8, 0xfa, 0xa7, 0x51, 0x3b, - 0xe6, 0x3c, 0x4e, 0xa8, 0x5b, 0x58, 0xe1, 0xe8, 0xd0, 0x95, 0x2c, 0xa5, 0x42, 0xe2, 0x74, 0x58, - 0x3a, 0xac, 0xbd, 0x6f, 0x40, 0xc3, 0xc3, 0x82, 0x6e, 0x97, 0x99, 0xa0, 0xff, 0x60, 0x9d, 0x11, - 0x13, 0x74, 0x41, 0x6f, 0xc1, 0x6b, 0x4e, 0x27, 0x76, 0x7d, 0x7f, 0xd7, 0xaf, 0x33, 0x82, 0xfe, - 0x87, 0x8b, 0x2c, 0x63, 0x92, 0x61, 0xc9, 0x73, 0xb3, 0xde, 0x05, 0xbd, 0x45, 0xff, 0x06, 0x40, - 0x9b, 0xb0, 0x91, 0x70, 0x69, 0x36, 0xba, 0xa0, 0x67, 0x6c, 0xad, 0x38, 0x3a, 0x31, 0x55, 0x45, - 0x55, 0x9a, 0xb3, 0xc3, 0x59, 0xe6, 0x2d, 0x9c, 0x4f, 0xec, 0x9a, 0xaf, 0x7c, 0xd1, 0x6b, 0xd8, - 0x0c, 0x19, 0x21, 0x34, 0x37, 0x17, 0xba, 0xa0, 0xb7, 0xe4, 0xed, 0x7d, 0x9b, 0xd8, 0xfd, 0x98, - 0xc9, 0xc1, 0x28, 0x74, 0x22, 0x9e, 0xea, 0xe2, 0xf4, 0x4f, 0x5f, 0x90, 0x23, 0x57, 0x9e, 0x0c, - 0xa9, 0x70, 0xb6, 0xa3, 0x68, 0x9b, 0x90, 0x9c, 0x0a, 0xf1, 0xe1, 0xac, 0xff, 0xaf, 0x56, 0xd2, - 0x88, 0x77, 0x22, 0xa9, 0xf0, 0x35, 0xaf, 0x4a, 0x2a, 0x64, 0xc4, 0xfc, 0x6b, 0xce, 0xa4, 0x42, - 0x46, 0xd0, 0x3a, 0xec, 0x0c, 0xb0, 0x08, 0x72, 0x1a, 0x51, 0x76, 0x4c, 0x49, 0x10, 0x32, 0x22, - 0xcc, 0x66, 0x17, 0xf4, 0xda, 0xfe, 0x3f, 0x03, 0x2c, 0x7c, 0x8d, 0x7b, 0x8c, 0x08, 0xf4, 0x04, - 0xb6, 0x69, 0x46, 0x02, 0xd5, 0x50, 0xb3, 0x55, 0x68, 0xac, 0x3a, 0x65, 0xb7, 0x9d, 0xaa, 0xdb, - 0xce, 0x8b, 0xaa, 0xdb, 0x5e, 0x5b, 0x89, 0x9c, 0x7e, 0xb6, 0x81, 0xdf, 0xa2, 0x19, 0x51, 0x38, - 0x7a, 0x06, 0x97, 0x52, 0x3c, 0x0e, 0xae, 0x49, 0xda, 0x3f, 0x41, 0x02, 0x53, 0x3c, 0x7e, 0x5a, - 0xf2, 0x3c, 0x36, 0x2e, 0xce, 0xfa, 0x2d, 0x3d, 0xbf, 0xb5, 0x14, 0xfe, 0xfd, 0x7c, 0x94, 0x0f, - 0x93, 0x91, 0xa8, 0x26, 0x7a, 0x00, 0x97, 0x54, 0xcd, 0x81, 0xde, 0xb5, 0x62, 0xb6, 0xc6, 0xd6, - 0x3d, 0xe7, 0xae, 0x05, 0x74, 0x6e, 0xad, 0x42, 0xa9, 0x76, 0x39, 0xb1, 0x81, 0x6f, 0x84, 0x37, - 0xf0, 0xac, 0xdc, 0x5b, 0x00, 0x8d, 0x5d, 0x1a, 0xca, 0xdf, 0x24, 0x86, 0x0e, 0x20, 0x8a, 0x78, - 0x9e, 0x53, 0x31, 0xe4, 0x19, 0x61, 0x59, 0x1c, 0x10, 0x1a, 0xca, 0x62, 0xff, 0xe6, 0x18, 0x69, - 0x67, 0x26, 0x54, 0xa5, 0x39, 0x9b, 0xfc, 0x45, 0x1d, 0x76, 0x76, 0x78, 0x92, 0x60, 0x49, 0x73, - 0x9c, 0xfc, 0x21, 0x25, 0xa0, 0x47, 0xb0, 0xa5, 0xd6, 0x46, 0xad, 0xf6, 0x9c, 0xf7, 0xd6, 0x4c, - 0xf1, 0xd8, 0x63, 0x04, 0x1d, 0x40, 0x23, 0xe1, 0x32, 0xc8, 0xa9, 0x1c, 0xe5, 0x99, 0x28, 0xee, - 0xce, 0xd8, 0x7a, 0x70, 0x77, 0x61, 0x2f, 0x29, 0x8b, 0x07, 0x92, 0x12, 0x7d, 0x59, 0x54, 0x68, - 0x2e, 0x98, 0x70, 0xe9, 0x97, 0x04, 0xb3, 0xcd, 0x7c, 0x07, 0x60, 0xe7, 0x87, 0x20, 0x74, 0x08, - 0x17, 0x71, 0x65, 0x98, 0xa0, 0xdb, 0xf8, 0xa5, 0x87, 0x7e, 0x43, 0x8d, 0xf6, 0x60, 0xeb, 0x4d, - 0x21, 0x2e, 0xcc, 0x7a, 0xa1, 0xe2, 0xa8, 0x6c, 0x3f, 0x4d, 0xec, 0xfb, 0x73, 0x28, 0xed, 0x67, - 0xd2, 0xaf, 0xc2, 0xbd, 0xbd, 0xf3, 0xaf, 0x56, 0xed, 0x7c, 0x6a, 0x81, 0xcb, 0xa9, 0x05, 0xbe, - 0x4c, 0x2d, 0x70, 0x7a, 0x65, 0xd5, 0x2e, 0xaf, 0xac, 0xda, 0xc7, 0x2b, 0xab, 0xf6, 0x6a, 0xfd, - 0x16, 0xdd, 0x46, 0x9c, 0xe0, 0x50, 0xb8, 0x1b, 0x71, 0x3f, 0x1a, 0x60, 0x96, 0xb9, 0xe3, 0xeb, - 0x4f, 0x7e, 0x41, 0x1b, 0x36, 0x8b, 0x0b, 0x7e, 0xf8, 0x3d, 0x00, 0x00, 0xff, 0xff, 0x61, 0xc3, - 0xa5, 0x61, 0x0f, 0x06, 0x00, 0x00, -} - -func (m *BaseAuction) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *BaseAuction) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *BaseAuction) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - n1, err1 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.MaxEndTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.MaxEndTime):]) - if err1 != nil { - return 0, err1 - } - i -= n1 - i = encodeVarintAuction(dAtA, i, uint64(n1)) - i-- - dAtA[i] = 0x42 - n2, err2 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.EndTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.EndTime):]) - if err2 != nil { - return 0, err2 - } - i -= n2 - i = encodeVarintAuction(dAtA, i, uint64(n2)) - i-- - dAtA[i] = 0x3a - if m.HasReceivedBids { - i-- - if m.HasReceivedBids { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x30 - } - { - size, err := m.Bid.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - if len(m.Bidder) > 0 { - i -= len(m.Bidder) - copy(dAtA[i:], m.Bidder) - i = encodeVarintAuction(dAtA, i, uint64(len(m.Bidder))) - i-- - dAtA[i] = 0x22 - } - { - size, err := m.Lot.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Initiator) > 0 { - i -= len(m.Initiator) - copy(dAtA[i:], m.Initiator) - i = encodeVarintAuction(dAtA, i, uint64(len(m.Initiator))) - i-- - dAtA[i] = 0x12 - } - if m.ID != 0 { - i = encodeVarintAuction(dAtA, i, uint64(m.ID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *SurplusAuction) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *SurplusAuction) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SurplusAuction) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.BaseAuction.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *DebtAuction) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *DebtAuction) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DebtAuction) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.CorrespondingDebt.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.BaseAuction.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *CollateralAuction) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CollateralAuction) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CollateralAuction) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.LotReturns.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.MaxBid.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.CorrespondingDebt.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.BaseAuction.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *WeightedAddresses) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *WeightedAddresses) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *WeightedAddresses) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Weights) > 0 { - for iNdEx := len(m.Weights) - 1; iNdEx >= 0; iNdEx-- { - { - size := m.Weights[iNdEx].Size() - i -= size - if _, err := m.Weights[iNdEx].MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintAuction(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Addresses) > 0 { - for iNdEx := len(m.Addresses) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Addresses[iNdEx]) - copy(dAtA[i:], m.Addresses[iNdEx]) - i = encodeVarintAuction(dAtA, i, uint64(len(m.Addresses[iNdEx]))) - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintAuction(dAtA []byte, offset int, v uint64) int { - offset -= sovAuction(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *BaseAuction) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.ID != 0 { - n += 1 + sovAuction(uint64(m.ID)) - } - l = len(m.Initiator) - if l > 0 { - n += 1 + l + sovAuction(uint64(l)) - } - l = m.Lot.Size() - n += 1 + l + sovAuction(uint64(l)) - l = len(m.Bidder) - if l > 0 { - n += 1 + l + sovAuction(uint64(l)) - } - l = m.Bid.Size() - n += 1 + l + sovAuction(uint64(l)) - if m.HasReceivedBids { - n += 2 - } - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.EndTime) - n += 1 + l + sovAuction(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.MaxEndTime) - n += 1 + l + sovAuction(uint64(l)) - return n -} - -func (m *SurplusAuction) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseAuction.Size() - n += 1 + l + sovAuction(uint64(l)) - return n -} - -func (m *DebtAuction) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseAuction.Size() - n += 1 + l + sovAuction(uint64(l)) - l = m.CorrespondingDebt.Size() - n += 1 + l + sovAuction(uint64(l)) - return n -} - -func (m *CollateralAuction) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseAuction.Size() - n += 1 + l + sovAuction(uint64(l)) - l = m.CorrespondingDebt.Size() - n += 1 + l + sovAuction(uint64(l)) - l = m.MaxBid.Size() - n += 1 + l + sovAuction(uint64(l)) - l = m.LotReturns.Size() - n += 1 + l + sovAuction(uint64(l)) - return n -} - -func (m *WeightedAddresses) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Addresses) > 0 { - for _, b := range m.Addresses { - l = len(b) - n += 1 + l + sovAuction(uint64(l)) - } - } - if len(m.Weights) > 0 { - for _, e := range m.Weights { - l = e.Size() - n += 1 + l + sovAuction(uint64(l)) - } - } - return n -} - -func sovAuction(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozAuction(x uint64) (n int) { - return sovAuction(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *BaseAuction) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: BaseAuction: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BaseAuction: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - m.ID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Initiator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Initiator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Lot", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Lot.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Bidder", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Bidder = append(m.Bidder[:0], dAtA[iNdEx:postIndex]...) - if m.Bidder == nil { - m.Bidder = []byte{} - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Bid", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Bid.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field HasReceivedBids", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.HasReceivedBids = bool(v != 0) - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field EndTime", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.EndTime, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaxEndTime", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.MaxEndTime, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuction(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuction - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *SurplusAuction) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: SurplusAuction: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SurplusAuction: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseAuction", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseAuction.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuction(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuction - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DebtAuction) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DebtAuction: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DebtAuction: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseAuction", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseAuction.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CorrespondingDebt", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.CorrespondingDebt.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuction(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuction - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CollateralAuction) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CollateralAuction: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CollateralAuction: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseAuction", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseAuction.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CorrespondingDebt", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.CorrespondingDebt.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaxBid", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MaxBid.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LotReturns", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.LotReturns.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuction(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuction - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *WeightedAddresses) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: WeightedAddresses: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: WeightedAddresses: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Addresses", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Addresses = append(m.Addresses, make([]byte, postIndex-iNdEx)) - copy(m.Addresses[len(m.Addresses)-1], dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Weights", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuction - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthAuction - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthAuction - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var v github_com_cosmos_cosmos_sdk_types.Int - m.Weights = append(m.Weights, v) - if err := m.Weights[len(m.Weights)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuction(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuction - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipAuction(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAuction - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAuction - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAuction - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthAuction - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupAuction - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthAuction - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthAuction = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowAuction = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupAuction = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/auction/types/auctions.go b/x/auction/types/auctions.go deleted file mode 100644 index 73fcb9cf..00000000 --- a/x/auction/types/auctions.go +++ /dev/null @@ -1,291 +0,0 @@ -package types - -import ( - "errors" - "fmt" - "strings" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/gogoproto/proto" -) - -const ( - CollateralAuctionType = "collateral" - SurplusAuctionType = "surplus" - DebtAuctionType = "debt" - ForwardAuctionPhase = "forward" - ReverseAuctionPhase = "reverse" -) - -// DistantFuture is a very large time value to use as initial the ending time for auctions. -// It is not set to the max time supported. This can cause problems with time comparisons, see https://stackoverflow.com/a/32620397. -// Also amino panics when encoding times ≥ the start of year 10000. -var DistantFuture = time.Date(9000, 1, 1, 0, 0, 0, 0, time.UTC) - -var ( - _ Auction = &SurplusAuction{} - _ GenesisAuction = &SurplusAuction{} - _ Auction = &DebtAuction{} - _ GenesisAuction = &DebtAuction{} - _ Auction = &CollateralAuction{} - _ GenesisAuction = &CollateralAuction{} -) - -// --------------- Shared auction functionality --------------- - -// Auction is an interface for handling common actions on auctions. -type Auction interface { - proto.Message - - GetID() uint64 - WithID(uint64) Auction - - GetInitiator() string - GetLot() sdk.Coin - GetBidder() sdk.AccAddress - GetBid() sdk.Coin - GetEndTime() time.Time - GetMaxEndTime() time.Time - - GetType() string - GetPhase() string -} - -// --------------- BaseAuction --------------- - -func (a BaseAuction) GetID() uint64 { return a.ID } - -func (a BaseAuction) GetBid() sdk.Coin { return a.Bid } - -func (a BaseAuction) GetLot() sdk.Coin { return a.Lot } - -func (a BaseAuction) GetBidder() sdk.AccAddress { return a.Bidder } - -func (a BaseAuction) GetInitiator() string { return a.Initiator } - -func (a BaseAuction) GetEndTime() time.Time { return a.EndTime } - -func (a BaseAuction) GetMaxEndTime() time.Time { return a.MaxEndTime } - -// ValidateAuction verifies that the auction end time is before max end time -func ValidateAuction(a Auction) error { - // ID can be 0 for surplus, debt and collateral auctions - if strings.TrimSpace(a.GetInitiator()) == "" { - return errors.New("auction initiator cannot be blank") - } - if !a.GetLot().IsValid() { - return fmt.Errorf("invalid lot: %s", a.GetLot()) - } - if !a.GetBid().IsValid() { - return fmt.Errorf("invalid bid: %s", a.GetBid()) - } - if a.GetEndTime().Unix() <= 0 || a.GetMaxEndTime().Unix() <= 0 { - return errors.New("end time cannot be zero") - } - if a.GetEndTime().After(a.GetMaxEndTime()) { - return fmt.Errorf("MaxEndTime < EndTime (%s < %s)", a.GetMaxEndTime(), a.GetEndTime()) - } - return nil -} - -// --------------- SurplusAuction --------------- - -// NewSurplusAuction returns a new surplus auction. -func NewSurplusAuction(seller string, lot sdk.Coin, bidDenom string, endTime time.Time) SurplusAuction { - auction := SurplusAuction{ - BaseAuction: BaseAuction{ - // No Id - Initiator: seller, - Lot: lot, - Bidder: nil, - Bid: sdk.NewInt64Coin(bidDenom, 0), - HasReceivedBids: false, // new auctions don't have any bids - EndTime: endTime, - MaxEndTime: endTime, - }, - } - return auction -} - -func (a SurplusAuction) WithID(id uint64) Auction { - a.ID = id - return Auction(&a) -} - -// GetPhase returns the direction of a surplus auction, which never changes. -func (a SurplusAuction) GetPhase() string { return ForwardAuctionPhase } - -// GetType returns the auction type. Used to identify auctions in event attributes. -func (a SurplusAuction) GetType() string { return SurplusAuctionType } - -// GetModuleAccountCoins returns the total number of coins held in the module account for this auction. -// It is used in genesis initialize the module account correctly. -func (a SurplusAuction) GetModuleAccountCoins() sdk.Coins { - // a.Bid is paid out on bids, so is never stored in the module account - return sdk.NewCoins(a.Lot) -} - -func (a SurplusAuction) Validate() error { - return ValidateAuction(&a) -} - -// --------------- DebtAuction --------------- - -// NewDebtAuction returns a new debt auction. -func NewDebtAuction(buyerModAccName string, bid sdk.Coin, initialLot sdk.Coin, endTime time.Time, debt sdk.Coin) DebtAuction { - // Note: Bidder is set to the initiator's module account address instead of module name. (when the first bid is placed, it is paid out to the initiator) - // Setting to the module account address bypasses calling supply.SendCoinsFromModuleToModule, instead calls SendCoinsFromModuleToAccount. - // This isn't a problem currently, but if additional logic/validation was added for sending to coins to Module Accounts, it would be bypassed. - auction := DebtAuction{ - BaseAuction: BaseAuction{ - // no ID - Initiator: buyerModAccName, - Lot: initialLot, - Bidder: authtypes.NewModuleAddress(buyerModAccName), // send proceeds from the first bid to the buyer. - Bid: bid, // amount that the buyer is buying - doesn't change over course of auction - HasReceivedBids: false, // new auctions don't have any bids - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: debt, - } - return auction -} - -func (a DebtAuction) WithID(id uint64) Auction { - a.ID = id - return Auction(&a) -} - -// GetPhase returns the direction of a debt auction, which never changes. -func (a DebtAuction) GetPhase() string { return ReverseAuctionPhase } - -// GetType returns the auction type. Used to identify auctions in event attributes. -func (a DebtAuction) GetType() string { return DebtAuctionType } - -// GetModuleAccountCoins returns the total number of coins held in the module account for this auction. -// It is used in genesis initialize the module account correctly. -func (a DebtAuction) GetModuleAccountCoins() sdk.Coins { - // a.Lot is minted at auction close, so is never stored in the module account - // a.Bid is paid out on bids, so is never stored in the module account - return sdk.NewCoins(a.CorrespondingDebt) -} - -// Validate validates the DebtAuction fields values. -func (a DebtAuction) Validate() error { - if !a.CorrespondingDebt.IsValid() { - return fmt.Errorf("invalid corresponding debt: %s", a.CorrespondingDebt) - } - return ValidateAuction(&a) -} - -// --------------- CollateralAuction --------------- - -// NewCollateralAuction returns a new collateral auction. -func NewCollateralAuction(seller string, lot sdk.Coin, endTime time.Time, maxBid sdk.Coin, lotReturns WeightedAddresses, debt sdk.Coin) CollateralAuction { - auction := CollateralAuction{ - BaseAuction: BaseAuction{ - // no ID - Initiator: seller, - Lot: lot, - Bidder: nil, - Bid: sdk.NewInt64Coin(maxBid.Denom, 0), - HasReceivedBids: false, // new auctions don't have any bids - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: debt, - MaxBid: maxBid, - LotReturns: lotReturns, - } - return auction -} - -func (a CollateralAuction) WithID(id uint64) Auction { - a.ID = id - return Auction(&a) -} - -// GetType returns the auction type. Used to identify auctions in event attributes. -func (a CollateralAuction) GetType() string { return CollateralAuctionType } - -// IsReversePhase returns whether the auction has switched over to reverse phase or not. -// CollateralAuctions initially start in forward phase. -func (a CollateralAuction) IsReversePhase() bool { - return a.Bid.IsEqual(a.MaxBid) -} - -// GetPhase returns the direction of a collateral auction. -func (a CollateralAuction) GetPhase() string { - if a.IsReversePhase() { - return ReverseAuctionPhase - } - return ForwardAuctionPhase -} - -// GetLotReturns returns the auction's lot returns as weighted addresses -func (a CollateralAuction) GetLotReturns() WeightedAddresses { return a.LotReturns } - -// GetModuleAccountCoins returns the total number of coins held in the module account for this auction. -// It is used in genesis initialize the module account correctly. -func (a CollateralAuction) GetModuleAccountCoins() sdk.Coins { - // a.Bid is paid out on bids, so is never stored in the module account - return sdk.NewCoins(a.Lot).Add(sdk.NewCoins(a.CorrespondingDebt)...) -} - -// Validate validates the CollateralAuction fields values. -func (a CollateralAuction) Validate() error { - if !a.CorrespondingDebt.IsValid() { - return fmt.Errorf("invalid corresponding debt: %s", a.CorrespondingDebt) - } - if !a.MaxBid.IsValid() { - return fmt.Errorf("invalid max bid: %s", a.MaxBid) - } - if err := a.LotReturns.Validate(); err != nil { - return fmt.Errorf("invalid lot returns: %w", err) - } - return ValidateAuction(&a) -} - -// NewWeightedAddresses returns a new list addresses with weights. -func NewWeightedAddresses(addrs []sdk.AccAddress, weights []sdkmath.Int) (WeightedAddresses, error) { - wa := WeightedAddresses{ - Addresses: addrs, - Weights: weights, - } - if err := wa.Validate(); err != nil { - return WeightedAddresses{}, err - } - return wa, nil -} - -// Validate checks for that the weights are not negative, not all zero, and the lengths match. -func (wa WeightedAddresses) Validate() error { - if len(wa.Weights) < 1 { - return fmt.Errorf("must be at least 1 weighted address") - } - - if len(wa.Addresses) != len(wa.Weights) { - return fmt.Errorf("number of addresses doesn't match number of weights, %d ≠ %d", len(wa.Addresses), len(wa.Weights)) - } - - totalWeight := sdk.ZeroInt() - for i := range wa.Addresses { - if wa.Addresses[i].Empty() { - return fmt.Errorf("address %d cannot be empty", i) - } - if wa.Weights[i].IsNegative() { - return fmt.Errorf("weight %d contains a negative amount: %s", i, wa.Weights[i]) - } - totalWeight = totalWeight.Add(wa.Weights[i]) - } - - if !totalWeight.IsPositive() { - return fmt.Errorf("total weight must be positive") - } - - return nil -} diff --git a/x/auction/types/auctions_test.go b/x/auction/types/auctions_test.go deleted file mode 100644 index 86efb9cd..00000000 --- a/x/auction/types/auctions_test.go +++ /dev/null @@ -1,356 +0,0 @@ -package types - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - TestInitiatorModuleName = "liquidator" - TestLotDenom = "usdx" - TestLotAmount = 100 - TestBidDenom = "kava" - TestBidAmount = 20 - TestDebtDenom = "debt" - TestDebtAmount1 = 20 - TestDebtAmount2 = 15 - TestExtraEndTime = 10000 - TestAuctionID = 9999123 - testAccAddress1 = "kava1qcfdf69js922qrdr4yaww3ax7gjml6pd39p8lj" - testAccAddress2 = "kava1pdfav2cjhry9k79nu6r8kgknnjtq6a7rcr0qlr" -) - -func init() { - sdk.GetConfig().SetBech32PrefixForAccount("kava", "kava"+sdk.PrefixPublic) -} - -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) sdkmath.Int { return sdkmath.NewInt(n) } -func is(ns ...int64) (is []sdkmath.Int) { - for _, n := range ns { - is = append(is, sdkmath.NewInt(n)) - } - return -} - -func TestNewWeightedAddresses(t *testing.T) { - addr1, err := sdk.AccAddressFromBech32(testAccAddress1) - require.NoError(t, err) - - addr2, err := sdk.AccAddressFromBech32(testAccAddress2) - require.NoError(t, err) - - tests := []struct { - name string - addresses []sdk.AccAddress - weights []sdkmath.Int - expPass bool - }{ - { - "normal", - []sdk.AccAddress{addr1, addr2}, - []sdkmath.Int{sdkmath.NewInt(6), sdkmath.NewInt(8)}, - true, - }, - { - "empty address", - []sdk.AccAddress{nil, nil}, - []sdkmath.Int{sdkmath.NewInt(6), sdkmath.NewInt(8)}, - false, - }, - { - "mismatched", - []sdk.AccAddress{addr1, addr2}, - []sdkmath.Int{sdkmath.NewInt(6)}, - false, - }, - { - "negative weight", - []sdk.AccAddress{addr1, addr2}, - is(6, -8), - false, - }, - { - "zero weight", - []sdk.AccAddress{addr1, addr2}, - is(0, 0), - false, - }, - } - - // Run NewWeightedAdresses tests - for _, tc := range tests { - // Attempt to instantiate new WeightedAddresses - weightedAddresses, err := NewWeightedAddresses(tc.addresses, tc.weights) - - if tc.expPass { - require.NoError(t, err) - require.Equal(t, tc.addresses, weightedAddresses.Addresses) - require.Equal(t, tc.weights, weightedAddresses.Weights) - } else { - require.Error(t, err) - } - } -} - -func TestDebtAuctionValidate(t *testing.T) { - addr1, err := sdk.AccAddressFromBech32(testAccAddress1) - require.NoError(t, err) - - now := time.Now() - - tests := []struct { - msg string - auction DebtAuction - expPass bool - }{ - { - "valid auction", - DebtAuction{ - BaseAuction: BaseAuction{ - ID: 1, - Initiator: testAccAddress1, - Lot: c("kava", 1), - Bidder: addr1, - Bid: c("kava", 1), - EndTime: now, - MaxEndTime: now, - HasReceivedBids: true, - }, - CorrespondingDebt: c("kava", 1), - }, - true, - }, - { - "invalid corresponding debt", - DebtAuction{ - BaseAuction: BaseAuction{ - ID: 1, - Initiator: testAccAddress1, - Lot: c("kava", 1), - Bidder: addr1, - Bid: c("kava", 1), - EndTime: now, - MaxEndTime: now, - HasReceivedBids: true, - }, - CorrespondingDebt: sdk.Coin{Denom: "", Amount: sdkmath.NewInt(1)}, - }, - false, - }, - } - - for _, tc := range tests { - - err := tc.auction.Validate() - - if tc.expPass { - require.NoError(t, err, tc.msg) - } else { - require.Error(t, err, tc.msg) - } - } -} - -func TestCollateralAuctionValidate(t *testing.T) { - addr1, err := sdk.AccAddressFromBech32(testAccAddress1) - require.NoError(t, err) - - now := time.Now() - - tests := []struct { - msg string - auction CollateralAuction - expPass bool - }{ - { - "valid auction", - CollateralAuction{ - BaseAuction: BaseAuction{ - ID: 1, - Initiator: testAccAddress1, - Lot: c("kava", 1), - Bidder: addr1, - Bid: c("kava", 1), - EndTime: now, - MaxEndTime: now, - HasReceivedBids: true, - }, - CorrespondingDebt: c("kava", 1), - MaxBid: c("kava", 1), - LotReturns: WeightedAddresses{ - Addresses: []sdk.AccAddress{addr1}, - Weights: []sdkmath.Int{sdkmath.NewInt(1)}, - }, - }, - true, - }, - { - "invalid corresponding debt", - CollateralAuction{ - BaseAuction: BaseAuction{ - ID: 1, - Initiator: testAccAddress1, - Lot: c("kava", 1), - Bidder: addr1, - Bid: c("kava", 1), - EndTime: now, - MaxEndTime: now, - HasReceivedBids: true, - }, - CorrespondingDebt: sdk.Coin{Denom: "DENOM", Amount: sdkmath.NewInt(1)}, - }, - false, - }, - { - "invalid max bid", - CollateralAuction{ - BaseAuction: BaseAuction{ - ID: 1, - Initiator: testAccAddress1, - Lot: c("kava", 1), - Bidder: addr1, - Bid: c("kava", 1), - EndTime: now, - MaxEndTime: now, - HasReceivedBids: true, - }, - CorrespondingDebt: c("kava", 1), - MaxBid: sdk.Coin{Denom: "DENOM", Amount: sdkmath.NewInt(1)}, - }, - false, - }, - { - "invalid lot returns", - CollateralAuction{ - BaseAuction: BaseAuction{ - ID: 1, - Initiator: testAccAddress1, - Lot: c("kava", 1), - Bidder: addr1, - Bid: c("kava", 1), - EndTime: now, - MaxEndTime: now, - HasReceivedBids: true, - }, - CorrespondingDebt: c("kava", 1), - MaxBid: c("kava", 1), - LotReturns: WeightedAddresses{ - Addresses: []sdk.AccAddress{nil}, - Weights: []sdkmath.Int{sdkmath.NewInt(1)}, - }, - }, - false, - }, - } - - for _, tc := range tests { - - err := tc.auction.Validate() - - if tc.expPass { - require.NoError(t, err, tc.msg) - } else { - require.Error(t, err, tc.msg) - } - } -} - -func TestBaseAuctionGetters(t *testing.T) { - endTime := time.Now().Add(TestExtraEndTime) - - // Create a new BaseAuction (via SurplusAuction) - auction := NewSurplusAuction( - TestInitiatorModuleName, - c(TestLotDenom, TestLotAmount), - TestBidDenom, endTime, - ) - - auctionID := auction.GetID() - auctionBid := auction.GetBid() - auctionLot := auction.GetLot() - auctionEndTime := auction.GetEndTime() - - require.Equal(t, auction.ID, auctionID) - require.Equal(t, auction.Bid, auctionBid) - require.Equal(t, auction.Lot, auctionLot) - require.Equal(t, auction.EndTime, auctionEndTime) -} - -func TestNewSurplusAuction(t *testing.T) { - endTime := time.Now().Add(TestExtraEndTime) - - // Create a new SurplusAuction - surplusAuction := NewSurplusAuction( - TestInitiatorModuleName, - c(TestLotDenom, TestLotAmount), - TestBidDenom, endTime, - ) - - require.Equal(t, surplusAuction.Initiator, TestInitiatorModuleName) - require.Equal(t, surplusAuction.Lot, c(TestLotDenom, TestLotAmount)) - require.Equal(t, surplusAuction.Bid, c(TestBidDenom, 0)) - require.Equal(t, surplusAuction.EndTime, endTime) - require.Equal(t, surplusAuction.MaxEndTime, endTime) -} - -func TestNewDebtAuction(t *testing.T) { - endTime := time.Now().Add(TestExtraEndTime) - - // Create a new DebtAuction - debtAuction := NewDebtAuction( - TestInitiatorModuleName, - c(TestBidDenom, TestBidAmount), - c(TestLotDenom, TestLotAmount), - endTime, - c(TestDebtDenom, TestDebtAmount1), - ) - - require.Equal(t, debtAuction.Initiator, TestInitiatorModuleName) - require.Equal(t, debtAuction.Lot, c(TestLotDenom, TestLotAmount)) - require.Equal(t, debtAuction.Bid, c(TestBidDenom, TestBidAmount)) - require.Equal(t, debtAuction.EndTime, endTime) - require.Equal(t, debtAuction.MaxEndTime, endTime) - require.Equal(t, debtAuction.CorrespondingDebt, c(TestDebtDenom, TestDebtAmount1)) -} - -func TestNewCollateralAuction(t *testing.T) { - // Set up WeightedAddresses - addresses := []sdk.AccAddress{ - sdk.AccAddress([]byte(testAccAddress1)), - sdk.AccAddress([]byte(testAccAddress2)), - } - - weights := []sdkmath.Int{ - sdkmath.NewInt(6), - sdkmath.NewInt(8), - } - - weightedAddresses, _ := NewWeightedAddresses(addresses, weights) - - endTime := time.Now().Add(TestExtraEndTime) - - collateralAuction := NewCollateralAuction( - TestInitiatorModuleName, - c(TestLotDenom, TestLotAmount), - endTime, - c(TestBidDenom, TestBidAmount), - weightedAddresses, - c(TestDebtDenom, TestDebtAmount2), - ) - - require.Equal(t, collateralAuction.Initiator, TestInitiatorModuleName) - require.Equal(t, collateralAuction.Lot, c(TestLotDenom, TestLotAmount)) - require.Equal(t, collateralAuction.Bid, c(TestBidDenom, 0)) - require.Equal(t, collateralAuction.EndTime, endTime) - require.Equal(t, collateralAuction.MaxEndTime, endTime) - require.Equal(t, collateralAuction.MaxBid, c(TestBidDenom, TestBidAmount)) - require.Equal(t, collateralAuction.LotReturns, weightedAddresses) - require.Equal(t, collateralAuction.CorrespondingDebt, c(TestDebtDenom, TestDebtAmount2)) -} diff --git a/x/auction/types/codec.go b/x/auction/types/codec.go deleted file mode 100644 index 3e33b9ca..00000000 --- a/x/auction/types/codec.go +++ /dev/null @@ -1,65 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the -// governance module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgPlaceBid{}, "auction/MsgPlaceBid", nil) - - cdc.RegisterInterface((*GenesisAuction)(nil), nil) - cdc.RegisterInterface((*Auction)(nil), nil) - cdc.RegisterConcrete(&SurplusAuction{}, "auction/SurplusAuction", nil) - cdc.RegisterConcrete(&DebtAuction{}, "auction/DebtAuction", nil) - cdc.RegisterConcrete(&CollateralAuction{}, "auction/CollateralAuction", nil) -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgPlaceBid{}, - ) - - registry.RegisterInterface( - "kava.auction.v1beta1.Auction", - (*Auction)(nil), - &SurplusAuction{}, - &DebtAuction{}, - &CollateralAuction{}, - ) - - registry.RegisterInterface( - "kava.auction.v1beta1.GenesisAuction", - (*GenesisAuction)(nil), - &SurplusAuction{}, - &DebtAuction{}, - &CollateralAuction{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - - // ModuleCdc is an amino codec instance with this module's types registered. - // - // Deprecated: The codec used for serialization should be provided to this module and - // defined at the application level. - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/auction/types/errors.go b/x/auction/types/errors.go deleted file mode 100644 index 4a37f798..00000000 --- a/x/auction/types/errors.go +++ /dev/null @@ -1,30 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -// DONTCOVER - -var ( - // ErrInvalidInitialAuctionID error for when the 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 = errorsmod.Register(ModuleName, 3, "unrecognized auction type") - // ErrAuctionNotFound error for when an auction is 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 = 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 = errorsmod.Register(ModuleName, 6, "auction has closed") - // ErrInvalidBidDenom error for when 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 = 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 = 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 = errorsmod.Register(ModuleName, 10, "bid is greater than auction's max bid") - // ErrLotTooSmall error for when lot is less than zero - 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 = errorsmod.Register(ModuleName, 12, "lot is greater than auction's max new lot amount") -) diff --git a/x/auction/types/events.go b/x/auction/types/events.go deleted file mode 100644 index b9389945..00000000 --- a/x/auction/types/events.go +++ /dev/null @@ -1,18 +0,0 @@ -package types - -// Events for the module -const ( - EventTypeAuctionStart = "auction_start" - EventTypeAuctionBid = "auction_bid" - EventTypeAuctionClose = "auction_close" - - AttributeValueCategory = ModuleName - AttributeKeyAuctionID = "auction_id" - AttributeKeyAuctionType = "auction_type" - AttributeKeyBidder = "bidder" - AttributeKeyLot = "lot" - AttributeKeyMaxBid = "max_bid" - AttributeKeyBid = "bid" - AttributeKeyEndTime = "end_time" - AttributeKeyCloseBlock = "close_block" -) diff --git a/x/auction/types/expected_keepers.go b/x/auction/types/expected_keepers.go deleted file mode 100644 index b7d65ea4..00000000 --- a/x/auction/types/expected_keepers.go +++ /dev/null @@ -1,22 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// AccountKeeper expected interface for the account keeper (noalias) -type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI - GetModuleAccount(ctx sdk.Context, name string) types.ModuleAccountI -} - -// BankKeeper defines the expected interface needed to send coins -type BankKeeper interface { - SendCoinsFromModuleToModule(ctx sdk.Context, sender, recipient string, amt sdk.Coins) error - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - BurnCoins(ctx sdk.Context, name string, amt sdk.Coins) error - MintCoins(ctx sdk.Context, name string, amt sdk.Coins) error - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins -} diff --git a/x/auction/types/genesis.go b/x/auction/types/genesis.go deleted file mode 100644 index a513054a..00000000 --- a/x/auction/types/genesis.go +++ /dev/null @@ -1,127 +0,0 @@ -package types - -import ( - "fmt" - - types "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// DefaultNextAuctionID is the starting point for auction IDs. -const DefaultNextAuctionID uint64 = 1 - -// GenesisAuction extends the auction interface to add functionality -// needed for initializing auctions from genesis. -type GenesisAuction interface { - Auction - GetModuleAccountCoins() sdk.Coins - Validate() error -} - -// PackGenesisAuctions converts a GenesisAuction slice to Any slice -func PackGenesisAuctions(ga []GenesisAuction) ([]*types.Any, error) { - gaAny := make([]*types.Any, len(ga)) - for i, genesisAuction := range ga { - any, err := types.NewAnyWithValue(genesisAuction) - if err != nil { - return nil, err - } - gaAny[i] = any - } - - return gaAny, nil -} - -func mustPackGenesisAuctions(ga []GenesisAuction) []*types.Any { - anys, err := PackGenesisAuctions(ga) - if err != nil { - panic(err) - } - return anys -} - -// UnpackGenesisAuctions converts Any slice to GenesisAuctions slice -func UnpackGenesisAuctions(genesisAuctionsAny []*types.Any) ([]GenesisAuction, error) { - genesisAuctions := make([]GenesisAuction, len(genesisAuctionsAny)) - for i, any := range genesisAuctionsAny { - genesisAuction, ok := any.GetCachedValue().(GenesisAuction) - if !ok { - return nil, fmt.Errorf("expected genesis auction") - } - genesisAuctions[i] = genesisAuction - } - - return genesisAuctions, nil -} - -// Ensure this type will unpack contained interface types correctly when it is unmarshalled. -var _ types.UnpackInterfacesMessage = &GenesisState{} - -// NewGenesisState returns a new genesis state object for auctions module. -func NewGenesisState(nextID uint64, ap Params, ga []GenesisAuction) (*GenesisState, error) { - packedGA, err := PackGenesisAuctions(ga) - if err != nil { - return &GenesisState{}, err - } - - return &GenesisState{ - NextAuctionId: nextID, - Params: ap, - Auctions: packedGA, - }, nil -} - -// DefaultGenesisState returns the default genesis state for auction module. -func DefaultGenesisState() *GenesisState { - genesis, err := NewGenesisState( - DefaultNextAuctionID, - DefaultParams(), - []GenesisAuction{}, - ) - if err != nil { - panic(fmt.Sprintf("could not create default genesis state: %v", err)) - } - return genesis -} - -// Validate validates genesis inputs. It returns error if validation of any input fails. -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - - auctions, err := UnpackGenesisAuctions(gs.Auctions) - if err != nil { - return err - } - - ids := map[uint64]bool{} - for _, a := range auctions { - - if err := a.Validate(); err != nil { - return fmt.Errorf("found invalid auction: %w", err) - } - - if ids[a.GetID()] { - return fmt.Errorf("found duplicate auction ID (%d)", a.GetID()) - } - ids[a.GetID()] = true - - if a.GetID() >= gs.NextAuctionId { - return fmt.Errorf("found auction ID ≥ the nextAuctionID (%d ≥ %d)", a.GetID(), gs.NextAuctionId) - } - } - return nil -} - -// UnpackInterfaces hooks into unmarshalling to unpack any interface types contained within the GenesisState. -func (gs GenesisState) UnpackInterfaces(unpacker types.AnyUnpacker) error { - for _, any := range gs.Auctions { - var auction GenesisAuction - err := unpacker.UnpackAny(any, &auction) - if err != nil { - return err - } - } - return nil -} diff --git a/x/auction/types/genesis.pb.go b/x/auction/types/genesis.pb.go deleted file mode 100644 index 87627e3e..00000000 --- a/x/auction/types/genesis.pb.go +++ /dev/null @@ -1,816 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/auction/v1beta1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/codec/types" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/durationpb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// GenesisState defines the auction module's genesis state. -type GenesisState struct { - NextAuctionId uint64 `protobuf:"varint,1,opt,name=next_auction_id,json=nextAuctionId,proto3" json:"next_auction_id,omitempty"` - Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"` - // Genesis auctions - Auctions []*types.Any `protobuf:"bytes,3,rep,name=auctions,proto3" json:"auctions,omitempty"` -} - -func (m *GenesisState) Reset() { *m = GenesisState{} } -func (m *GenesisState) String() string { return proto.CompactTextString(m) } -func (*GenesisState) ProtoMessage() {} -func (*GenesisState) Descriptor() ([]byte, []int) { - return fileDescriptor_d0e5cb58293042f7, []int{0} -} -func (m *GenesisState) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisState) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisState.Merge(m, src) -} -func (m *GenesisState) XXX_Size() int { - return m.Size() -} -func (m *GenesisState) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisState.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisState proto.InternalMessageInfo - -// Params defines the parameters for the issuance module. -type Params struct { - MaxAuctionDuration time.Duration `protobuf:"bytes,1,opt,name=max_auction_duration,json=maxAuctionDuration,proto3,stdduration" json:"max_auction_duration"` - ForwardBidDuration time.Duration `protobuf:"bytes,6,opt,name=forward_bid_duration,json=forwardBidDuration,proto3,stdduration" json:"forward_bid_duration"` - ReverseBidDuration time.Duration `protobuf:"bytes,7,opt,name=reverse_bid_duration,json=reverseBidDuration,proto3,stdduration" json:"reverse_bid_duration"` - IncrementSurplus github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=increment_surplus,json=incrementSurplus,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"increment_surplus"` - IncrementDebt github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=increment_debt,json=incrementDebt,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"increment_debt"` - IncrementCollateral github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=increment_collateral,json=incrementCollateral,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"increment_collateral"` -} - -func (m *Params) Reset() { *m = Params{} } -func (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_d0e5cb58293042f7, []int{1} -} -func (m *Params) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Params.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Params) XXX_Merge(src proto.Message) { - xxx_messageInfo_Params.Merge(m, src) -} -func (m *Params) XXX_Size() int { - return m.Size() -} -func (m *Params) XXX_DiscardUnknown() { - xxx_messageInfo_Params.DiscardUnknown(m) -} - -var xxx_messageInfo_Params proto.InternalMessageInfo - -func init() { - proto.RegisterType((*GenesisState)(nil), "kava.auction.v1beta1.GenesisState") - proto.RegisterType((*Params)(nil), "kava.auction.v1beta1.Params") -} - -func init() { - proto.RegisterFile("kava/auction/v1beta1/genesis.proto", fileDescriptor_d0e5cb58293042f7) -} - -var fileDescriptor_d0e5cb58293042f7 = []byte{ - // 501 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x93, 0xbd, 0x6e, 0xdb, 0x30, - 0x14, 0x85, 0xa5, 0x44, 0x75, 0x0d, 0xda, 0x49, 0x53, 0x56, 0x83, 0x1c, 0x14, 0xb2, 0xe1, 0x21, - 0x30, 0x0a, 0x98, 0x4c, 0xdc, 0xad, 0x5b, 0x54, 0x03, 0xfd, 0x99, 0x0a, 0x05, 0x59, 0xda, 0x41, - 0xa0, 0x24, 0x46, 0x11, 0x22, 0x89, 0x06, 0x49, 0xb9, 0xf6, 0x5b, 0x74, 0xec, 0x83, 0x74, 0xc8, - 0x23, 0x18, 0x9d, 0x32, 0x16, 0x1d, 0xd2, 0xd6, 0x7e, 0x91, 0x42, 0x12, 0x2d, 0xbb, 0x3f, 0x4b, - 0x32, 0x49, 0xbc, 0xf7, 0xdc, 0xef, 0x1c, 0x52, 0x22, 0xe8, 0x5f, 0x91, 0x29, 0xc1, 0x24, 0x0f, - 0x64, 0xcc, 0x32, 0x3c, 0x3d, 0xf1, 0xa9, 0x24, 0x27, 0x38, 0xa2, 0x19, 0x15, 0xb1, 0x40, 0x13, - 0xce, 0x24, 0x83, 0x66, 0xa1, 0x41, 0x4a, 0x83, 0x94, 0xe6, 0xb0, 0x13, 0x30, 0x91, 0x32, 0xe1, - 0x95, 0x1a, 0x5c, 0x2d, 0xaa, 0x81, 0x43, 0x33, 0x62, 0x11, 0xab, 0xea, 0xc5, 0x9b, 0xaa, 0x76, - 0x22, 0xc6, 0xa2, 0x84, 0xe2, 0x72, 0xe5, 0xe7, 0x17, 0x98, 0x64, 0x73, 0xd5, 0xb2, 0xff, 0x6e, - 0x85, 0x39, 0x27, 0xa5, 0x5b, 0x59, 0xe9, 0x5f, 0xeb, 0xa0, 0xfd, 0xaa, 0xca, 0x74, 0x26, 0x89, - 0xa4, 0xf0, 0x08, 0x3c, 0xca, 0xe8, 0x4c, 0x7a, 0x2a, 0x94, 0x17, 0x87, 0x96, 0xde, 0xd3, 0x07, - 0x86, 0xbb, 0x57, 0x94, 0x4f, 0xab, 0xea, 0x9b, 0x10, 0xbe, 0x00, 0x8d, 0x09, 0xe1, 0x24, 0x15, - 0xd6, 0x4e, 0x4f, 0x1f, 0xb4, 0x46, 0x4f, 0xd1, 0xff, 0xf6, 0x82, 0xde, 0x95, 0x1a, 0xc7, 0x58, - 0xdc, 0x76, 0x35, 0x57, 0x4d, 0xc0, 0x31, 0x68, 0x2a, 0x9d, 0xb0, 0x76, 0x7b, 0xbb, 0x83, 0xd6, - 0xc8, 0x44, 0x55, 0x4e, 0xb4, 0xce, 0x89, 0x4e, 0xb3, 0xb9, 0x03, 0xbf, 0x7e, 0x19, 0xee, 0xab, - 0x74, 0xca, 0xd9, 0xad, 0x27, 0xfb, 0xd7, 0x06, 0x68, 0x54, 0x78, 0x78, 0x0e, 0xcc, 0x94, 0xcc, - 0xea, 0xcc, 0xeb, 0x3d, 0x96, 0xc9, 0x5b, 0xa3, 0xce, 0x3f, 0xf0, 0xb1, 0x12, 0x38, 0xcd, 0x22, - 0xd7, 0xe7, 0x1f, 0x5d, 0xdd, 0x85, 0x29, 0x99, 0x29, 0x8f, 0x75, 0xb7, 0xc0, 0x5e, 0x30, 0xfe, - 0x91, 0xf0, 0xd0, 0xf3, 0xe3, 0x70, 0x83, 0x6d, 0xdc, 0x01, 0xab, 0x00, 0x4e, 0x1c, 0x6e, 0x63, - 0x39, 0x9d, 0x52, 0x2e, 0xe8, 0x9f, 0xd8, 0x87, 0x77, 0xc0, 0x2a, 0xc0, 0x36, 0xf6, 0x03, 0x78, - 0x1c, 0x67, 0x01, 0xa7, 0x29, 0xcd, 0xa4, 0x27, 0x72, 0x3e, 0x49, 0xf2, 0xe2, 0x78, 0xf5, 0x41, - 0xdb, 0x41, 0xc5, 0xe0, 0xf7, 0xdb, 0xee, 0x51, 0x14, 0xcb, 0xcb, 0xdc, 0x47, 0x01, 0x4b, 0xd5, - 0x7f, 0xa5, 0x1e, 0x43, 0x11, 0x5e, 0x61, 0x39, 0x9f, 0x50, 0x81, 0xc6, 0x34, 0x70, 0x0f, 0x6a, - 0xd0, 0x59, 0xc5, 0x81, 0xe7, 0x60, 0x7f, 0x03, 0x0f, 0xa9, 0x2f, 0x2d, 0xe3, 0x5e, 0xe4, 0xbd, - 0x9a, 0x32, 0xa6, 0xbe, 0x84, 0x04, 0x98, 0x1b, 0x6c, 0xc0, 0x92, 0x84, 0x48, 0xca, 0x49, 0x62, - 0x3d, 0xb8, 0x17, 0xfc, 0x49, 0xcd, 0x7a, 0x59, 0xa3, 0xde, 0x1a, 0xcd, 0x9d, 0x83, 0x5d, 0xb7, - 0xbd, 0x7d, 0xd2, 0xce, 0xeb, 0xc5, 0x2f, 0x5b, 0x5b, 0x2c, 0x6d, 0xfd, 0x66, 0x69, 0xeb, 0x3f, - 0x97, 0xb6, 0xfe, 0x69, 0x65, 0x6b, 0x37, 0x2b, 0x5b, 0xfb, 0xb6, 0xb2, 0xb5, 0xf7, 0xcf, 0xb6, - 0xec, 0x8e, 0xa3, 0x84, 0xf8, 0x02, 0x1f, 0x47, 0xc3, 0xe0, 0x92, 0xc4, 0x19, 0x9e, 0xd5, 0x37, - 0xba, 0xb4, 0xf5, 0x1b, 0xe5, 0x57, 0x7a, 0xfe, 0x3b, 0x00, 0x00, 0xff, 0xff, 0xf6, 0x35, 0x98, - 0x5b, 0xee, 0x03, 0x00, 0x00, -} - -func (m *GenesisState) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Auctions) > 0 { - for iNdEx := len(m.Auctions) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Auctions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.NextAuctionId != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.NextAuctionId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *Params) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Params) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - n2, err2 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.ReverseBidDuration, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.ReverseBidDuration):]) - if err2 != nil { - return 0, err2 - } - i -= n2 - i = encodeVarintGenesis(dAtA, i, uint64(n2)) - i-- - dAtA[i] = 0x3a - n3, err3 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.ForwardBidDuration, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.ForwardBidDuration):]) - if err3 != nil { - return 0, err3 - } - i -= n3 - i = encodeVarintGenesis(dAtA, i, uint64(n3)) - i-- - dAtA[i] = 0x32 - { - size := m.IncrementCollateral.Size() - i -= size - if _, err := m.IncrementCollateral.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.IncrementDebt.Size() - i -= size - if _, err := m.IncrementDebt.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.IncrementSurplus.Size() - i -= size - if _, err := m.IncrementSurplus.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - n4, err4 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.MaxAuctionDuration, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.MaxAuctionDuration):]) - if err4 != nil { - return 0, err4 - } - i -= n4 - i = encodeVarintGenesis(dAtA, i, uint64(n4)) - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *GenesisState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.NextAuctionId != 0 { - n += 1 + sovGenesis(uint64(m.NextAuctionId)) - } - l = m.Params.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.Auctions) > 0 { - for _, e := range m.Auctions { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.MaxAuctionDuration) - n += 1 + l + sovGenesis(uint64(l)) - l = m.IncrementSurplus.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.IncrementDebt.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.IncrementCollateral.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.ForwardBidDuration) - n += 1 + l + sovGenesis(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.ReverseBidDuration) - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *GenesisState) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field NextAuctionId", wireType) - } - m.NextAuctionId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.NextAuctionId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Auctions", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Auctions = append(m.Auctions, &types.Any{}) - if err := m.Auctions[len(m.Auctions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Params) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Params: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaxAuctionDuration", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.MaxAuctionDuration, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IncrementSurplus", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IncrementSurplus.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IncrementDebt", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IncrementDebt.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IncrementCollateral", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IncrementCollateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ForwardBidDuration", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.ForwardBidDuration, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ReverseBidDuration", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.ReverseBidDuration, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/auction/types/genesis_test.go b/x/auction/types/genesis_test.go deleted file mode 100644 index 5ab0c182..00000000 --- a/x/auction/types/genesis_test.go +++ /dev/null @@ -1,159 +0,0 @@ -package types - -import ( - "testing" - time "time" - - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var testCoin = sdk.NewInt64Coin("test", 20) - -func newTestModuleCodec() codec.Codec { - interfaceRegistry := codectypes.NewInterfaceRegistry() - RegisterInterfaces(interfaceRegistry) - return codec.NewProtoCodec(interfaceRegistry) -} - -func TestGenesisState_Validate(t *testing.T) { - arbitraryTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - validAuction := &CollateralAuction{ - BaseAuction: BaseAuction{ - ID: 10, - Initiator: "seller mod account", - Lot: sdk.NewInt64Coin("btc", 1e8), - Bidder: sdk.AccAddress("test bidder"), - Bid: sdk.NewInt64Coin("usdx", 5), - HasReceivedBids: true, - EndTime: arbitraryTime, - MaxEndTime: arbitraryTime.Add(time.Hour), - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 1e9), - MaxBid: sdk.NewInt64Coin("usdx", 5e4), - LotReturns: WeightedAddresses{ - Addresses: []sdk.AccAddress{sdk.AccAddress("test return address")}, - Weights: []sdkmath.Int{sdk.OneInt()}, - }, - } - - testCases := []struct { - name string - genesis *GenesisState - expectPass bool - }{ - { - "valid default genesis", - DefaultGenesisState(), - true, - }, - { - "invalid next ID", - &GenesisState{ - validAuction.ID - 1, - DefaultParams(), - mustPackGenesisAuctions( - []GenesisAuction{ - validAuction, - }, - ), - }, - false, - }, - { - "invalid auctions with repeated ID", - &GenesisState{ - validAuction.ID + 1, - DefaultParams(), - mustPackGenesisAuctions( - []GenesisAuction{ - validAuction, - validAuction, - }, - ), - }, - false, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.genesis.Validate() - if tc.expectPass { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } -} - -func TestGenesisState_UnmarshalAnys(t *testing.T) { - cdc := newTestModuleCodec() - - arbitraryTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - - auctions := []GenesisAuction{ - &CollateralAuction{ - BaseAuction: BaseAuction{ - ID: 1, - Initiator: "seller mod account", - Lot: sdk.NewInt64Coin("btc", 1e8), - Bidder: sdk.AccAddress("test bidder"), - Bid: sdk.NewInt64Coin("usdx", 5), - HasReceivedBids: true, - EndTime: arbitraryTime, - MaxEndTime: arbitraryTime.Add(time.Hour), - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 1e9), - MaxBid: sdk.NewInt64Coin("usdx", 5e4), - LotReturns: WeightedAddresses{}, - }, - &DebtAuction{ - BaseAuction: BaseAuction{ - ID: 2, - Initiator: "mod account", - Lot: sdk.NewInt64Coin("ukava", 1e9), - Bidder: sdk.AccAddress("test bidder"), - Bid: sdk.NewInt64Coin("usdx", 5), - HasReceivedBids: true, - EndTime: arbitraryTime, - MaxEndTime: arbitraryTime.Add(time.Hour), - }, - CorrespondingDebt: testCoin, - }, - &SurplusAuction{ - BaseAuction: BaseAuction{ - ID: 3, - Initiator: "seller mod account", - Lot: sdk.NewInt64Coin("usdx", 1e9), - Bidder: sdk.AccAddress("test bidder"), - Bid: sdk.NewInt64Coin("ukava", 5), - HasReceivedBids: true, - EndTime: arbitraryTime, - MaxEndTime: arbitraryTime.Add(time.Hour), - }, - }, - } - genesis, err := NewGenesisState( - DefaultNextAuctionID, - DefaultParams(), - auctions, - ) - require.NoError(t, err) - - bz, err := cdc.MarshalJSON(genesis) - require.NoError(t, err) - - var unmarshalledGenesis GenesisState - cdc.UnmarshalJSON(bz, &unmarshalledGenesis) - - // Check the interface values are correct after unmarshalling. - unmarshalledAuctions, err := UnpackGenesisAuctions(unmarshalledGenesis.Auctions) - require.NoError(t, err) - require.Equal(t, auctions, unmarshalledAuctions) -} diff --git a/x/auction/types/keys.go b/x/auction/types/keys.go deleted file mode 100644 index 6709bbd1..00000000 --- a/x/auction/types/keys.go +++ /dev/null @@ -1,52 +0,0 @@ -package types - -import ( - "encoding/binary" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // ModuleName The name that will be used throughout the module - ModuleName = "auction" - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey Top level router key - RouterKey = ModuleName - - // DefaultParamspace default name for parameter store - DefaultParamspace = ModuleName -) - -// Key prefixes -var ( - AuctionKeyPrefix = []byte{0x00} // prefix for keys that store auctions - AuctionByTimeKeyPrefix = []byte{0x01} // prefix for keys that are part of the auctionsByTime index - - NextAuctionIDKey = []byte{0x02} // key for the next auction id -) - -// GetAuctionKey returns the bytes of an auction key -func GetAuctionKey(auctionID uint64) []byte { - return Uint64ToBytes(auctionID) -} - -// GetAuctionByTimeKey returns the key for iterating auctions by time -func GetAuctionByTimeKey(endTime time.Time, auctionID uint64) []byte { - return append(sdk.FormatTimeBytes(endTime), Uint64ToBytes(auctionID)...) -} - -// Uint64ToBytes converts a uint64 into fixed length bytes for use in store keys. -func Uint64ToBytes(id uint64) []byte { - bz := make([]byte, 8) - binary.BigEndian.PutUint64(bz, uint64(id)) - return bz -} - -// Uint64FromBytes converts some fixed length bytes back into a uint64. -func Uint64FromBytes(bz []byte) uint64 { - return binary.BigEndian.Uint64(bz) -} diff --git a/x/auction/types/msg.go b/x/auction/types/msg.go deleted file mode 100644 index 2c94f0e3..00000000 --- a/x/auction/types/msg.go +++ /dev/null @@ -1,57 +0,0 @@ -package types - -import ( - "errors" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// ensure Msg interface compliance at compile time -var _ sdk.Msg = &MsgPlaceBid{} - -// NewMsgPlaceBid returns a new MsgPlaceBid. -func NewMsgPlaceBid(auctionID uint64, bidder string, amt sdk.Coin) MsgPlaceBid { - return MsgPlaceBid{ - AuctionId: auctionID, - Bidder: bidder, - Amount: amt, - } -} - -// Route return the message type used for routing the message. -func (msg MsgPlaceBid) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgPlaceBid) Type() string { return "place_bid" } - -// ValidateBasic does a simple validation check that doesn't require access to state. -func (msg MsgPlaceBid) ValidateBasic() error { - if msg.AuctionId == 0 { - return errors.New("auction id cannot be zero") - } - _, err := sdk.AccAddressFromBech32(msg.Bidder) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "bidder address cannot be empty or invalid") - } - if !msg.Amount.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "bid amount %s", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgPlaceBid) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgPlaceBid) GetSigners() []sdk.AccAddress { - bidder, err := sdk.AccAddressFromBech32(msg.Bidder) - if err != nil { - panic(err) - } - return []sdk.AccAddress{bidder} -} diff --git a/x/auction/types/msg_test.go b/x/auction/types/msg_test.go deleted file mode 100644 index ae12f1c1..00000000 --- a/x/auction/types/msg_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package types - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestMsgPlaceBid_ValidateBasic(t *testing.T) { - tests := []struct { - name string - msg MsgPlaceBid - expectPass bool - }{ - { - "normal", - NewMsgPlaceBid(1, testAccAddress1, c("token", 10)), - true, - }, - { - "zero id", - NewMsgPlaceBid(0, testAccAddress1, c("token", 10)), - false, - }, - { - "empty address ", - NewMsgPlaceBid(1, "", c("token", 10)), - false, - }, - { - "negative amount", - NewMsgPlaceBid(1, testAccAddress1, sdk.Coin{Denom: "token", Amount: sdkmath.NewInt(-10)}), - false, - }, - { - "zero amount", - NewMsgPlaceBid(1, testAccAddress1, c("token", 0)), - true, - }, - } - - for _, tc := range tests { - if tc.expectPass { - require.NoError(t, tc.msg.ValidateBasic(), tc.name) - } else { - require.Error(t, tc.msg.ValidateBasic(), tc.name) - } - } -} diff --git a/x/auction/types/params.go b/x/auction/types/params.go deleted file mode 100644 index eca7900f..00000000 --- a/x/auction/types/params.go +++ /dev/null @@ -1,190 +0,0 @@ -package types - -import ( - "errors" - "fmt" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -var emptyDec = sdk.Dec{} - -// Defaults for auction params -const ( - // DefaultMaxAuctionDuration max length of auction - DefaultMaxAuctionDuration time.Duration = 2 * 24 * time.Hour - // DefaultForwardBidDuration how long an auction gets extended when someone bids for a forward auction - DefaultForwardBidDuration time.Duration = 24 * time.Hour - // DefaultReverseBidDuration how long an auction gets extended when someone bids for a reverse auction - DefaultReverseBidDuration time.Duration = 1 * time.Hour -) - -var ( - // DefaultIncrement is the smallest percent change a new bid must have from the old one - DefaultIncrement sdk.Dec = sdk.MustNewDecFromStr("0.05") - // ParamStoreKeyParams Param store key for auction params - KeyForwardBidDuration = []byte("ForwardBidDuration") - KeyReverseBidDuration = []byte("ReverseBidDuration") - KeyMaxAuctionDuration = []byte("MaxAuctionDuration") - KeyIncrementSurplus = []byte("IncrementSurplus") - KeyIncrementDebt = []byte("IncrementDebt") - KeyIncrementCollateral = []byte("IncrementCollateral") -) - -// NewParams returns a new Params object. -func NewParams( - maxAuctionDuration, forwardBidDuration, reverseBidDuration time.Duration, - incrementSurplus, - incrementDebt, - incrementCollateral sdk.Dec, -) Params { - return Params{ - MaxAuctionDuration: maxAuctionDuration, - ForwardBidDuration: forwardBidDuration, - ReverseBidDuration: reverseBidDuration, - IncrementSurplus: incrementSurplus, - IncrementDebt: incrementDebt, - IncrementCollateral: incrementCollateral, - } -} - -// DefaultParams returns the default parameters for auctions. -func DefaultParams() Params { - return NewParams( - DefaultMaxAuctionDuration, - DefaultForwardBidDuration, - DefaultReverseBidDuration, - DefaultIncrement, - DefaultIncrement, - DefaultIncrement, - ) -} - -// ParamKeyTable Key declaration for parameters -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements the ParamSet interface and returns all the key/value pairs. -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyForwardBidDuration, &p.ForwardBidDuration, validateBidDurationParam), - paramtypes.NewParamSetPair(KeyReverseBidDuration, &p.ReverseBidDuration, validateBidDurationParam), - paramtypes.NewParamSetPair(KeyMaxAuctionDuration, &p.MaxAuctionDuration, validateMaxAuctionDurationParam), - paramtypes.NewParamSetPair(KeyIncrementSurplus, &p.IncrementSurplus, validateIncrementSurplusParam), - paramtypes.NewParamSetPair(KeyIncrementDebt, &p.IncrementDebt, validateIncrementDebtParam), - paramtypes.NewParamSetPair(KeyIncrementCollateral, &p.IncrementCollateral, validateIncrementCollateralParam), - } -} - -// Validate checks that the parameters have valid values. -func (p Params) Validate() error { - if err := validateBidDurationParam(p.ForwardBidDuration); err != nil { - return err - } - - if err := validateBidDurationParam(p.ReverseBidDuration); err != nil { - return err - } - - if err := validateMaxAuctionDurationParam(p.MaxAuctionDuration); err != nil { - return err - } - - if p.ForwardBidDuration > p.MaxAuctionDuration { - return errors.New("forward bid duration param cannot be larger than max auction duration") - } - - if p.ReverseBidDuration > p.MaxAuctionDuration { - return errors.New("reverse bid duration param cannot be larger than max auction duration") - } - - if err := validateIncrementSurplusParam(p.IncrementSurplus); err != nil { - return err - } - - if err := validateIncrementDebtParam(p.IncrementDebt); err != nil { - return err - } - - return validateIncrementCollateralParam(p.IncrementCollateral) -} - -func validateBidDurationParam(i interface{}) error { - bidDuration, ok := i.(time.Duration) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if bidDuration < 0 { - return fmt.Errorf("bid duration cannot be negative %d", bidDuration) - } - - return nil -} - -func validateMaxAuctionDurationParam(i interface{}) error { - maxAuctionDuration, ok := i.(time.Duration) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if maxAuctionDuration < 0 { - return fmt.Errorf("max auction duration cannot be negative %d", maxAuctionDuration) - } - - return nil -} - -func validateIncrementSurplusParam(i interface{}) error { - incrementSurplus, ok := i.(sdk.Dec) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if incrementSurplus == emptyDec || incrementSurplus.IsNil() { - return errors.New("surplus auction increment cannot be nil or empty") - } - - if incrementSurplus.IsNegative() { - return fmt.Errorf("surplus auction increment cannot be less than zero %s", incrementSurplus) - } - - return nil -} - -func validateIncrementDebtParam(i interface{}) error { - incrementDebt, ok := i.(sdk.Dec) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if incrementDebt == emptyDec || incrementDebt.IsNil() { - return errors.New("debt auction increment cannot be nil or empty") - } - - if incrementDebt.IsNegative() { - return fmt.Errorf("debt auction increment cannot be less than zero %s", incrementDebt) - } - - return nil -} - -func validateIncrementCollateralParam(i interface{}) error { - incrementCollateral, ok := i.(sdk.Dec) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if incrementCollateral == emptyDec || incrementCollateral.IsNil() { - return errors.New("collateral auction increment cannot be nil or empty") - } - - if incrementCollateral.IsNegative() { - return fmt.Errorf("collateral auction increment cannot be less than zero %s", incrementCollateral) - } - - return nil -} diff --git a/x/auction/types/params_test.go b/x/auction/types/params_test.go deleted file mode 100644 index 1061977c..00000000 --- a/x/auction/types/params_test.go +++ /dev/null @@ -1,133 +0,0 @@ -package types - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" -) - -func TestParams_Validate(t *testing.T) { - testCases := []struct { - name string - Params - expectErr bool - }{ - { - "normal", - DefaultParams(), - false, - }, - { - "negativeForwardBidDuration", - Params{ - MaxAuctionDuration: 24 * time.Hour, - ForwardBidDuration: -1 * time.Hour, - ReverseBidDuration: 1 * time.Hour, - IncrementSurplus: d("0.05"), - IncrementDebt: d("0.05"), - IncrementCollateral: d("0.05"), - }, - true, - }, - { - "negativeReverseBidDuration", - Params{ - MaxAuctionDuration: 24 * time.Hour, - ForwardBidDuration: 1 * time.Hour, - ReverseBidDuration: -1 * time.Hour, - IncrementSurplus: d("0.05"), - IncrementDebt: d("0.05"), - IncrementCollateral: d("0.05"), - }, - true, - }, - { - "negativeBidDuration", - Params{ - MaxAuctionDuration: 24 * time.Hour, - ForwardBidDuration: -1 * time.Hour, - ReverseBidDuration: -1 * time.Hour, - IncrementSurplus: d("0.05"), - IncrementDebt: d("0.05"), - IncrementCollateral: d("0.05"), - }, - true, - }, - { - "negativeAuction", - Params{ - MaxAuctionDuration: -24 * time.Hour, - ForwardBidDuration: 1 * time.Hour, - ReverseBidDuration: 1 * time.Hour, - IncrementSurplus: d("0.05"), - IncrementDebt: d("0.05"), - IncrementCollateral: d("0.05"), - }, - true, - }, - { - "bid>auction", - Params{ - MaxAuctionDuration: 1 * time.Hour, - ForwardBidDuration: 24 * time.Hour, - ReverseBidDuration: 1 * time.Hour, - IncrementSurplus: d("0.05"), - IncrementDebt: d("0.05"), - IncrementCollateral: d("0.05"), - }, - true, - }, - { - "negative increment surplus", - Params{ - MaxAuctionDuration: 24 * time.Hour, - ForwardBidDuration: 1 * time.Hour, - ReverseBidDuration: 1 * time.Hour, - IncrementSurplus: d("-0.05"), - IncrementDebt: d("0.05"), - IncrementCollateral: d("0.05"), - }, - true, - }, - { - "negative increment debt", - Params{ - MaxAuctionDuration: 24 * time.Hour, - ForwardBidDuration: 1 * time.Hour, - ReverseBidDuration: 1 * time.Hour, - IncrementSurplus: d("0.05"), - IncrementDebt: d("-0.05"), - IncrementCollateral: d("0.05"), - }, - true, - }, - { - "negative increment collateral", - Params{ - MaxAuctionDuration: 24 * time.Hour, - ForwardBidDuration: 1 * time.Hour, - ReverseBidDuration: 1 * time.Hour, - IncrementSurplus: d("0.05"), - IncrementDebt: d("0.05"), - IncrementCollateral: d("-0.05"), - }, - true, - }, - { - "zero value", - Params{}, - true, - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.Params.Validate() - if tc.expectErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} diff --git a/x/auction/types/query.pb.go b/x/auction/types/query.pb.go deleted file mode 100644 index 870fc067..00000000 --- a/x/auction/types/query.pb.go +++ /dev/null @@ -1,1868 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/auction/v1beta1/query.proto - -package types - -import ( - context "context" - fmt "fmt" - types "github.com/cosmos/cosmos-sdk/codec/types" - query "github.com/cosmos/cosmos-sdk/types/query" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// QueryParamsRequest defines the request type for querying x/auction parameters. -type QueryParamsRequest struct { -} - -func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } -func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryParamsRequest) ProtoMessage() {} -func (*QueryParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_0afd5f8bae92c6bb, []int{0} -} -func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsRequest.Merge(m, src) -} -func (m *QueryParamsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo - -// QueryParamsResponse defines the response type for querying x/auction parameters. -type QueryParamsResponse struct { - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` -} - -func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } -func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryParamsResponse) ProtoMessage() {} -func (*QueryParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_0afd5f8bae92c6bb, []int{1} -} -func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsResponse.Merge(m, src) -} -func (m *QueryParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo - -func (m *QueryParamsResponse) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -// QueryAuctionRequest is the request type for the Query/Auction RPC method. -type QueryAuctionRequest struct { - AuctionId uint64 `protobuf:"varint,1,opt,name=auction_id,json=auctionId,proto3" json:"auction_id,omitempty"` -} - -func (m *QueryAuctionRequest) Reset() { *m = QueryAuctionRequest{} } -func (m *QueryAuctionRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAuctionRequest) ProtoMessage() {} -func (*QueryAuctionRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_0afd5f8bae92c6bb, []int{2} -} -func (m *QueryAuctionRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAuctionRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAuctionRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryAuctionRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAuctionRequest.Merge(m, src) -} -func (m *QueryAuctionRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryAuctionRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAuctionRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAuctionRequest proto.InternalMessageInfo - -// QueryAuctionResponse is the response type for the Query/Auction RPC method. -type QueryAuctionResponse struct { - Auction *types.Any `protobuf:"bytes,1,opt,name=auction,proto3" json:"auction,omitempty"` -} - -func (m *QueryAuctionResponse) Reset() { *m = QueryAuctionResponse{} } -func (m *QueryAuctionResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAuctionResponse) ProtoMessage() {} -func (*QueryAuctionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_0afd5f8bae92c6bb, []int{3} -} -func (m *QueryAuctionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAuctionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAuctionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryAuctionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAuctionResponse.Merge(m, src) -} -func (m *QueryAuctionResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryAuctionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAuctionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAuctionResponse proto.InternalMessageInfo - -func (m *QueryAuctionResponse) GetAuction() *types.Any { - if m != nil { - return m.Auction - } - return nil -} - -// QueryAuctionsRequest is the request type for the Query/Auctions RPC method. -type QueryAuctionsRequest struct { - Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Denom string `protobuf:"bytes,3,opt,name=denom,proto3" json:"denom,omitempty"` - Phase string `protobuf:"bytes,4,opt,name=phase,proto3" json:"phase,omitempty"` - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,5,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryAuctionsRequest) Reset() { *m = QueryAuctionsRequest{} } -func (m *QueryAuctionsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAuctionsRequest) ProtoMessage() {} -func (*QueryAuctionsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_0afd5f8bae92c6bb, []int{4} -} -func (m *QueryAuctionsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAuctionsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAuctionsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryAuctionsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAuctionsRequest.Merge(m, src) -} -func (m *QueryAuctionsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryAuctionsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAuctionsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAuctionsRequest proto.InternalMessageInfo - -// QueryAuctionsResponse is the response type for the Query/Auctions RPC method. -type QueryAuctionsResponse struct { - Auctions []*types.Any `protobuf:"bytes,1,rep,name=auctions,proto3" json:"auctions,omitempty"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryAuctionsResponse) Reset() { *m = QueryAuctionsResponse{} } -func (m *QueryAuctionsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAuctionsResponse) ProtoMessage() {} -func (*QueryAuctionsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_0afd5f8bae92c6bb, []int{5} -} -func (m *QueryAuctionsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAuctionsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAuctionsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryAuctionsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAuctionsResponse.Merge(m, src) -} -func (m *QueryAuctionsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryAuctionsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAuctionsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAuctionsResponse proto.InternalMessageInfo - -func (m *QueryAuctionsResponse) GetAuctions() []*types.Any { - if m != nil { - return m.Auctions - } - return nil -} - -func (m *QueryAuctionsResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryNextAuctionIDRequest defines the request type for querying x/auction next auction ID. -type QueryNextAuctionIDRequest struct { -} - -func (m *QueryNextAuctionIDRequest) Reset() { *m = QueryNextAuctionIDRequest{} } -func (m *QueryNextAuctionIDRequest) String() string { return proto.CompactTextString(m) } -func (*QueryNextAuctionIDRequest) ProtoMessage() {} -func (*QueryNextAuctionIDRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_0afd5f8bae92c6bb, []int{6} -} -func (m *QueryNextAuctionIDRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryNextAuctionIDRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryNextAuctionIDRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryNextAuctionIDRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryNextAuctionIDRequest.Merge(m, src) -} -func (m *QueryNextAuctionIDRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryNextAuctionIDRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryNextAuctionIDRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryNextAuctionIDRequest proto.InternalMessageInfo - -// QueryNextAuctionIDResponse defines the response type for querying x/auction next auction ID. -type QueryNextAuctionIDResponse struct { - Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` -} - -func (m *QueryNextAuctionIDResponse) Reset() { *m = QueryNextAuctionIDResponse{} } -func (m *QueryNextAuctionIDResponse) String() string { return proto.CompactTextString(m) } -func (*QueryNextAuctionIDResponse) ProtoMessage() {} -func (*QueryNextAuctionIDResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_0afd5f8bae92c6bb, []int{7} -} -func (m *QueryNextAuctionIDResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryNextAuctionIDResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryNextAuctionIDResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryNextAuctionIDResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryNextAuctionIDResponse.Merge(m, src) -} -func (m *QueryNextAuctionIDResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryNextAuctionIDResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryNextAuctionIDResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryNextAuctionIDResponse proto.InternalMessageInfo - -func (m *QueryNextAuctionIDResponse) GetId() uint64 { - if m != nil { - return m.Id - } - return 0 -} - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.auction.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.auction.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryAuctionRequest)(nil), "kava.auction.v1beta1.QueryAuctionRequest") - proto.RegisterType((*QueryAuctionResponse)(nil), "kava.auction.v1beta1.QueryAuctionResponse") - proto.RegisterType((*QueryAuctionsRequest)(nil), "kava.auction.v1beta1.QueryAuctionsRequest") - proto.RegisterType((*QueryAuctionsResponse)(nil), "kava.auction.v1beta1.QueryAuctionsResponse") - proto.RegisterType((*QueryNextAuctionIDRequest)(nil), "kava.auction.v1beta1.QueryNextAuctionIDRequest") - proto.RegisterType((*QueryNextAuctionIDResponse)(nil), "kava.auction.v1beta1.QueryNextAuctionIDResponse") -} - -func init() { proto.RegisterFile("kava/auction/v1beta1/query.proto", fileDescriptor_0afd5f8bae92c6bb) } - -var fileDescriptor_0afd5f8bae92c6bb = []byte{ - // 634 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x94, 0xcf, 0x4f, 0xd4, 0x40, - 0x14, 0xc7, 0xdb, 0x65, 0xf9, 0x35, 0x46, 0x0f, 0x63, 0x4d, 0x96, 0x8a, 0x85, 0x34, 0x0a, 0x08, - 0xee, 0xcc, 0x02, 0x37, 0x0e, 0x26, 0x10, 0x82, 0xe1, 0x62, 0xa4, 0x47, 0x2f, 0x66, 0xba, 0x3b, - 0x96, 0x46, 0x76, 0xa6, 0xec, 0x74, 0x11, 0x62, 0xbc, 0xe8, 0xc5, 0xc4, 0x8b, 0xd1, 0x78, 0xc7, - 0x7f, 0xc4, 0x33, 0x47, 0x12, 0x0f, 0x7a, 0x32, 0x06, 0x3c, 0xf8, 0x67, 0x98, 0xce, 0xbc, 0xee, - 0x6e, 0xb5, 0xae, 0x7b, 0xeb, 0xbc, 0xf9, 0xbe, 0x37, 0x9f, 0x79, 0xef, 0x3b, 0x45, 0xf3, 0xcf, - 0xd8, 0x11, 0xa3, 0xac, 0xdb, 0x4c, 0x63, 0x29, 0xe8, 0xd1, 0x6a, 0xc8, 0x53, 0xb6, 0x4a, 0x0f, - 0xbb, 0xbc, 0x73, 0x42, 0x92, 0x8e, 0x4c, 0x25, 0x76, 0x32, 0x05, 0x01, 0x05, 0x01, 0x85, 0xbb, - 0xdc, 0x94, 0xaa, 0x2d, 0x15, 0x0d, 0x99, 0xe2, 0x46, 0xde, 0x4b, 0x4e, 0x58, 0x14, 0x0b, 0xa6, - 0xd5, 0xba, 0x82, 0xeb, 0x44, 0x32, 0x92, 0xfa, 0x93, 0x66, 0x5f, 0x10, 0x9d, 0x8d, 0xa4, 0x8c, - 0x0e, 0x38, 0x65, 0x49, 0x4c, 0x99, 0x10, 0x32, 0xd5, 0x29, 0x0a, 0x76, 0x67, 0x60, 0x57, 0xaf, - 0xc2, 0xee, 0x53, 0xca, 0x04, 0x00, 0xb9, 0x7e, 0x29, 0x72, 0xc4, 0x05, 0x57, 0x31, 0xa4, 0xfb, - 0x0e, 0xc2, 0x7b, 0x19, 0xd4, 0x23, 0xd6, 0x61, 0x6d, 0x15, 0xf0, 0xc3, 0x2e, 0x57, 0xa9, 0xbf, - 0x87, 0xae, 0x17, 0xa2, 0x2a, 0x91, 0x42, 0x71, 0xbc, 0x81, 0x26, 0x12, 0x1d, 0xa9, 0xd9, 0xf3, - 0xf6, 0xd2, 0x95, 0xb5, 0x59, 0x52, 0x76, 0x65, 0x62, 0xb2, 0xb6, 0xaa, 0x67, 0xdf, 0xe7, 0xac, - 0x00, 0x32, 0xfc, 0xfb, 0x50, 0x72, 0xd3, 0x88, 0xe1, 0x24, 0x7c, 0x0b, 0x21, 0x48, 0x7f, 0x12, - 0xb7, 0x74, 0xd9, 0x6a, 0x30, 0x0d, 0x91, 0xdd, 0xd6, 0xc6, 0xd4, 0x9b, 0xd3, 0x39, 0xeb, 0xd7, - 0xe9, 0x9c, 0xe5, 0xef, 0x20, 0xa7, 0x98, 0x0f, 0x4c, 0x04, 0x4d, 0x82, 0x1c, 0xa0, 0x1c, 0x62, - 0x3a, 0x42, 0xf2, 0x8e, 0x90, 0x4d, 0x71, 0x12, 0xe4, 0x22, 0xff, 0xb3, 0x5d, 0x2c, 0x94, 0xdf, - 0x19, 0x63, 0x54, 0x4d, 0x4f, 0x12, 0xae, 0xab, 0x4c, 0x07, 0xfa, 0x1b, 0x3b, 0x68, 0x5c, 0x3e, - 0x17, 0xbc, 0x53, 0xab, 0xe8, 0xa0, 0x59, 0x64, 0xd1, 0x16, 0x17, 0xb2, 0x5d, 0x1b, 0x33, 0x51, - 0xbd, 0xc8, 0xa2, 0xc9, 0x3e, 0x53, 0xbc, 0x56, 0x35, 0x51, 0xbd, 0xc0, 0x3b, 0x08, 0xf5, 0xc7, - 0x5c, 0x1b, 0xd7, 0x84, 0x0b, 0xc4, 0x78, 0x82, 0x64, 0x9e, 0x20, 0xc6, 0x42, 0xfd, 0xde, 0x45, - 0x1c, 0x88, 0x82, 0x81, 0xcc, 0x81, 0x46, 0xbc, 0xb7, 0xd1, 0x8d, 0x3f, 0x2e, 0x00, 0xad, 0x68, - 0xa0, 0x29, 0xb8, 0x65, 0x36, 0xa0, 0xb1, 0x7f, 0xf6, 0xa2, 0xa7, 0xc2, 0x0f, 0x0a, 0x74, 0x15, - 0x4d, 0xb7, 0xf8, 0x5f, 0x3a, 0x73, 0xdc, 0x20, 0x9e, 0x7f, 0x13, 0xcd, 0x68, 0xa6, 0x87, 0xfc, - 0x38, 0x05, 0xae, 0xdd, 0xed, 0xdc, 0x4d, 0xf7, 0x90, 0x5b, 0xb6, 0x09, 0xd4, 0xd7, 0x50, 0xa5, - 0x37, 0xf9, 0x4a, 0xdc, 0x5a, 0xfb, 0x5a, 0x45, 0xe3, 0x5a, 0x8e, 0x5f, 0xdb, 0x68, 0xc2, 0x78, - 0x09, 0x2f, 0x95, 0x3b, 0xed, 0x6f, 0xeb, 0xba, 0x77, 0x47, 0x50, 0x9a, 0x93, 0xfd, 0xdb, 0xaf, - 0xbe, 0xfc, 0xfc, 0x50, 0xf1, 0xf0, 0x2c, 0x2d, 0x7d, 0x28, 0xc6, 0xb8, 0xf8, 0xa3, 0x8d, 0x26, - 0x81, 0x1a, 0x0f, 0x2b, 0x5e, 0x34, 0xb6, 0xbb, 0x3c, 0x8a, 0x14, 0x40, 0xd6, 0x35, 0x48, 0x1d, - 0xaf, 0x94, 0x83, 0xe4, 0xe3, 0xa2, 0x2f, 0xfa, 0x4f, 0xe5, 0x25, 0x7e, 0x6b, 0xa3, 0xa9, 0xdc, - 0x02, 0x78, 0x84, 0xd3, 0x7a, 0x1d, 0x5a, 0x19, 0x49, 0x0b, 0x68, 0x0b, 0x1a, 0x6d, 0x1e, 0x7b, - 0xc3, 0xd1, 0xf0, 0x27, 0x1b, 0x5d, 0x2d, 0xcc, 0x17, 0xd3, 0x21, 0xc7, 0x94, 0xd9, 0xc4, 0x6d, - 0x8c, 0x9e, 0x00, 0x70, 0x75, 0x0d, 0xb7, 0x88, 0xef, 0x94, 0xc3, 0x09, 0x7e, 0x9c, 0xd6, 0x21, - 0x58, 0x8f, 0x5b, 0x5b, 0xdb, 0x67, 0x17, 0x9e, 0x7d, 0x7e, 0xe1, 0xd9, 0x3f, 0x2e, 0x3c, 0xfb, - 0xdd, 0xa5, 0x67, 0x9d, 0x5f, 0x7a, 0xd6, 0xb7, 0x4b, 0xcf, 0x7a, 0xbc, 0x1c, 0xc5, 0xe9, 0x7e, - 0x37, 0x24, 0x4d, 0xd9, 0xa6, 0x8d, 0xe8, 0x80, 0x85, 0x8a, 0x36, 0xa2, 0x7a, 0x73, 0x9f, 0xc5, - 0x82, 0x1e, 0xf7, 0xea, 0x66, 0xbf, 0x04, 0x15, 0x4e, 0xe8, 0xb7, 0xb4, 0xfe, 0x3b, 0x00, 0x00, - 0xff, 0xff, 0x39, 0xdb, 0x8f, 0x24, 0x11, 0x06, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - // Params queries all parameters of the auction module. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Auction queries an individual Auction by auction ID - Auction(ctx context.Context, in *QueryAuctionRequest, opts ...grpc.CallOption) (*QueryAuctionResponse, error) - // Auctions queries auctions filtered by asset denom, owner address, phase, and auction type - Auctions(ctx context.Context, in *QueryAuctionsRequest, opts ...grpc.CallOption) (*QueryAuctionsResponse, error) - // NextAuctionID queries the next auction ID - NextAuctionID(ctx context.Context, in *QueryNextAuctionIDRequest, opts ...grpc.CallOption) (*QueryNextAuctionIDResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { - out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, "/kava.auction.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Auction(ctx context.Context, in *QueryAuctionRequest, opts ...grpc.CallOption) (*QueryAuctionResponse, error) { - out := new(QueryAuctionResponse) - err := c.cc.Invoke(ctx, "/kava.auction.v1beta1.Query/Auction", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Auctions(ctx context.Context, in *QueryAuctionsRequest, opts ...grpc.CallOption) (*QueryAuctionsResponse, error) { - out := new(QueryAuctionsResponse) - err := c.cc.Invoke(ctx, "/kava.auction.v1beta1.Query/Auctions", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) NextAuctionID(ctx context.Context, in *QueryNextAuctionIDRequest, opts ...grpc.CallOption) (*QueryNextAuctionIDResponse, error) { - out := new(QueryNextAuctionIDResponse) - err := c.cc.Invoke(ctx, "/kava.auction.v1beta1.Query/NextAuctionID", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries all parameters of the auction module. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Auction queries an individual Auction by auction ID - Auction(context.Context, *QueryAuctionRequest) (*QueryAuctionResponse, error) - // Auctions queries auctions filtered by asset denom, owner address, phase, and auction type - Auctions(context.Context, *QueryAuctionsRequest) (*QueryAuctionsResponse, error) - // NextAuctionID queries the next auction ID - NextAuctionID(context.Context, *QueryNextAuctionIDRequest) (*QueryNextAuctionIDResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") -} -func (*UnimplementedQueryServer) Auction(ctx context.Context, req *QueryAuctionRequest) (*QueryAuctionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Auction not implemented") -} -func (*UnimplementedQueryServer) Auctions(ctx context.Context, req *QueryAuctionsRequest) (*QueryAuctionsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Auctions not implemented") -} -func (*UnimplementedQueryServer) NextAuctionID(ctx context.Context, req *QueryNextAuctionIDRequest) (*QueryNextAuctionIDResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method NextAuctionID not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryParamsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Params(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.auction.v1beta1.Query/Params", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Auction_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAuctionRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Auction(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.auction.v1beta1.Query/Auction", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Auction(ctx, req.(*QueryAuctionRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Auctions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAuctionsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Auctions(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.auction.v1beta1.Query/Auctions", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Auctions(ctx, req.(*QueryAuctionsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_NextAuctionID_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryNextAuctionIDRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).NextAuctionID(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.auction.v1beta1.Query/NextAuctionID", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).NextAuctionID(ctx, req.(*QueryNextAuctionIDRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.auction.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Auction", - Handler: _Query_Auction_Handler, - }, - { - MethodName: "Auctions", - Handler: _Query_Auctions_Handler, - }, - { - MethodName: "NextAuctionID", - Handler: _Query_NextAuctionID_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/auction/v1beta1/query.proto", -} - -func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryAuctionRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryAuctionRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAuctionRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.AuctionId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.AuctionId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryAuctionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryAuctionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAuctionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Auction != nil { - { - size, err := m.Auction.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryAuctionsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryAuctionsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAuctionsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - if len(m.Phase) > 0 { - i -= len(m.Phase) - copy(dAtA[i:], m.Phase) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Phase))) - i-- - dAtA[i] = 0x22 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0x1a - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.Type) > 0 { - i -= len(m.Type) - copy(dAtA[i:], m.Type) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Type))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryAuctionsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryAuctionsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAuctionsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Auctions) > 0 { - for iNdEx := len(m.Auctions) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Auctions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryNextAuctionIDRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryNextAuctionIDRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryNextAuctionIDRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryNextAuctionIDResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryNextAuctionIDResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryNextAuctionIDResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Id != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.Id)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryParamsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryAuctionRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.AuctionId != 0 { - n += 1 + sovQuery(uint64(m.AuctionId)) - } - return n -} - -func (m *QueryAuctionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Auction != nil { - l = m.Auction.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryAuctionsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Type) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Phase) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryAuctionsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Auctions) > 0 { - for _, e := range m.Auctions { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryNextAuctionIDRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryNextAuctionIDResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Id != 0 { - n += 1 + sovQuery(uint64(m.Id)) - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryAuctionRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryAuctionRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAuctionRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field AuctionId", wireType) - } - m.AuctionId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.AuctionId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryAuctionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryAuctionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAuctionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Auction", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Auction == nil { - m.Auction = &types.Any{} - } - if err := m.Auction.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryAuctionsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryAuctionsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAuctionsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Type = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Phase", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Phase = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryAuctionsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryAuctionsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAuctionsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Auctions", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Auctions = append(m.Auctions, &types.Any{}) - if err := m.Auctions[len(m.Auctions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryNextAuctionIDRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryNextAuctionIDRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryNextAuctionIDRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryNextAuctionIDResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryNextAuctionIDResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryNextAuctionIDResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) - } - m.Id = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Id |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/auction/types/query.pb.gw.go b/x/auction/types/query.pb.gw.go deleted file mode 100644 index 9d010e8a..00000000 --- a/x/auction/types/query.pb.gw.go +++ /dev/null @@ -1,402 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/auction/v1beta1/query.proto - -/* -Package types is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package types - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join - -func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Params(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Auction_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAuctionRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["auction_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "auction_id") - } - - protoReq.AuctionId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "auction_id", err) - } - - msg, err := client.Auction(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Auction_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAuctionRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["auction_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "auction_id") - } - - protoReq.AuctionId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "auction_id", err) - } - - msg, err := server.Auction(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Auctions_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Auctions_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAuctionsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Auctions_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Auctions(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Auctions_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAuctionsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Auctions_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Auctions(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_NextAuctionID_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryNextAuctionIDRequest - var metadata runtime.ServerMetadata - - msg, err := client.NextAuctionID(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_NextAuctionID_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryNextAuctionIDRequest - var metadata runtime.ServerMetadata - - msg, err := server.NextAuctionID(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Auction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Auction_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Auction_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Auctions_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Auctions_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Auctions_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_NextAuctionID_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_NextAuctionID_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_NextAuctionID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Auction_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Auction_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Auction_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Auctions_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Auctions_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Auctions_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_NextAuctionID_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_NextAuctionID_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_NextAuctionID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "auction", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Auction_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"kava", "auction", "v1beta1", "auctions", "auction_id"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Auctions_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "auction", "v1beta1", "auctions"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_NextAuctionID_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "auction", "v1beta1", "next-auction-id"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Auction_0 = runtime.ForwardResponseMessage - - forward_Query_Auctions_0 = runtime.ForwardResponseMessage - - forward_Query_NextAuctionID_0 = runtime.ForwardResponseMessage -) diff --git a/x/auction/types/tx.pb.go b/x/auction/types/tx.pb.go deleted file mode 100644 index 51032510..00000000 --- a/x/auction/types/tx.pb.go +++ /dev/null @@ -1,601 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/auction/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// MsgPlaceBid represents a message used by bidders to place bids on auctions -type MsgPlaceBid struct { - AuctionId uint64 `protobuf:"varint,1,opt,name=auction_id,json=auctionId,proto3" json:"auction_id,omitempty"` - Bidder string `protobuf:"bytes,2,opt,name=bidder,proto3" json:"bidder,omitempty"` - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *MsgPlaceBid) Reset() { *m = MsgPlaceBid{} } -func (m *MsgPlaceBid) String() string { return proto.CompactTextString(m) } -func (*MsgPlaceBid) ProtoMessage() {} -func (*MsgPlaceBid) Descriptor() ([]byte, []int) { - return fileDescriptor_226282be4da73be5, []int{0} -} -func (m *MsgPlaceBid) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgPlaceBid) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgPlaceBid.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgPlaceBid) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgPlaceBid.Merge(m, src) -} -func (m *MsgPlaceBid) XXX_Size() int { - return m.Size() -} -func (m *MsgPlaceBid) XXX_DiscardUnknown() { - xxx_messageInfo_MsgPlaceBid.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgPlaceBid proto.InternalMessageInfo - -// MsgPlaceBidResponse defines the Msg/PlaceBid response type. -type MsgPlaceBidResponse struct { -} - -func (m *MsgPlaceBidResponse) Reset() { *m = MsgPlaceBidResponse{} } -func (m *MsgPlaceBidResponse) String() string { return proto.CompactTextString(m) } -func (*MsgPlaceBidResponse) ProtoMessage() {} -func (*MsgPlaceBidResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_226282be4da73be5, []int{1} -} -func (m *MsgPlaceBidResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgPlaceBidResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgPlaceBidResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgPlaceBidResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgPlaceBidResponse.Merge(m, src) -} -func (m *MsgPlaceBidResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgPlaceBidResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgPlaceBidResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgPlaceBidResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgPlaceBid)(nil), "kava.auction.v1beta1.MsgPlaceBid") - proto.RegisterType((*MsgPlaceBidResponse)(nil), "kava.auction.v1beta1.MsgPlaceBidResponse") -} - -func init() { proto.RegisterFile("kava/auction/v1beta1/tx.proto", fileDescriptor_226282be4da73be5) } - -var fileDescriptor_226282be4da73be5 = []byte{ - // 316 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x91, 0xb1, 0x4e, 0x42, 0x31, - 0x18, 0x85, 0x6f, 0x85, 0x10, 0x28, 0xdb, 0x15, 0x0d, 0x92, 0x50, 0x90, 0x09, 0x4d, 0x6c, 0x01, - 0x07, 0x13, 0x47, 0x74, 0x71, 0x20, 0x31, 0x77, 0x32, 0x2e, 0xa4, 0xb7, 0xb7, 0x29, 0x8d, 0xd0, - 0x9f, 0xd0, 0x42, 0xf0, 0x09, 0x74, 0xf4, 0x11, 0x78, 0x1c, 0x46, 0x46, 0x27, 0x63, 0x60, 0xf1, - 0x31, 0x0c, 0x50, 0x08, 0x83, 0x89, 0xdb, 0xdf, 0xff, 0x9c, 0xd3, 0x7e, 0x39, 0xc5, 0xe5, 0x17, - 0x3e, 0xe1, 0x8c, 0x8f, 0x85, 0xd3, 0x60, 0xd8, 0xa4, 0x19, 0x4b, 0xc7, 0x9b, 0xcc, 0x4d, 0xe9, - 0x70, 0x04, 0x0e, 0xc2, 0xc2, 0x5a, 0xa6, 0x5e, 0xa6, 0x5e, 0x2e, 0x11, 0x01, 0x76, 0x00, 0x96, - 0xc5, 0xdc, 0xca, 0x7d, 0x46, 0x80, 0x36, 0xdb, 0x54, 0xa9, 0xa0, 0x40, 0xc1, 0x66, 0x64, 0xeb, - 0x69, 0xbb, 0xad, 0xbd, 0x21, 0x9c, 0xef, 0x58, 0xf5, 0xd8, 0xe7, 0x42, 0xb6, 0x75, 0x12, 0x96, - 0x31, 0xf6, 0x17, 0x77, 0x75, 0x52, 0x44, 0x55, 0x54, 0x4f, 0x47, 0x39, 0xbf, 0x79, 0x48, 0xc2, - 0x53, 0x9c, 0x89, 0x75, 0x92, 0xc8, 0x51, 0xf1, 0xa8, 0x8a, 0xea, 0xb9, 0xc8, 0x9f, 0xc2, 0x1b, - 0x9c, 0xe1, 0x03, 0x18, 0x1b, 0x57, 0x4c, 0x55, 0x51, 0x3d, 0xdf, 0x3a, 0xa3, 0x5b, 0x1a, 0xba, - 0xa6, 0xd9, 0x21, 0xd2, 0x3b, 0xd0, 0xa6, 0x9d, 0x9e, 0x7f, 0x55, 0x82, 0xc8, 0xdb, 0x6f, 0xb3, - 0xef, 0xb3, 0x4a, 0xf0, 0x33, 0xab, 0x04, 0xb5, 0x13, 0x7c, 0x7c, 0x00, 0x12, 0x49, 0x3b, 0x04, - 0x63, 0x65, 0xab, 0x8b, 0x53, 0x1d, 0xab, 0xc2, 0x27, 0x9c, 0xdd, 0x33, 0x9e, 0xd3, 0xbf, 0x0a, - 0xa0, 0x07, 0xe9, 0xd2, 0xc5, 0xbf, 0x96, 0xdd, 0x03, 0xed, 0xfb, 0xf9, 0x92, 0xa0, 0xc5, 0x92, - 0xa0, 0xef, 0x25, 0x41, 0x1f, 0x2b, 0x12, 0x2c, 0x56, 0x24, 0xf8, 0x5c, 0x91, 0xe0, 0xf9, 0x52, - 0x69, 0xd7, 0x1b, 0xc7, 0x54, 0xc0, 0x80, 0x35, 0x54, 0x9f, 0xc7, 0x96, 0x35, 0xd4, 0x95, 0xe8, - 0x71, 0x6d, 0xd8, 0x74, 0xff, 0x3d, 0xee, 0x75, 0x28, 0x6d, 0x9c, 0xd9, 0xd4, 0x79, 0xfd, 0x1b, - 0x00, 0x00, 0xff, 0xff, 0x12, 0xef, 0xd5, 0x8d, 0xbb, 0x01, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - // PlaceBid message type used by bidders to place bids on auctions - PlaceBid(ctx context.Context, in *MsgPlaceBid, opts ...grpc.CallOption) (*MsgPlaceBidResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) PlaceBid(ctx context.Context, in *MsgPlaceBid, opts ...grpc.CallOption) (*MsgPlaceBidResponse, error) { - out := new(MsgPlaceBidResponse) - err := c.cc.Invoke(ctx, "/kava.auction.v1beta1.Msg/PlaceBid", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // PlaceBid message type used by bidders to place bids on auctions - PlaceBid(context.Context, *MsgPlaceBid) (*MsgPlaceBidResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) PlaceBid(ctx context.Context, req *MsgPlaceBid) (*MsgPlaceBidResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method PlaceBid not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_PlaceBid_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgPlaceBid) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).PlaceBid(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.auction.v1beta1.Msg/PlaceBid", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).PlaceBid(ctx, req.(*MsgPlaceBid)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.auction.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "PlaceBid", - Handler: _Msg_PlaceBid_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/auction/v1beta1/tx.proto", -} - -func (m *MsgPlaceBid) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgPlaceBid) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgPlaceBid) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Bidder) > 0 { - i -= len(m.Bidder) - copy(dAtA[i:], m.Bidder) - i = encodeVarintTx(dAtA, i, uint64(len(m.Bidder))) - i-- - dAtA[i] = 0x12 - } - if m.AuctionId != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.AuctionId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *MsgPlaceBidResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgPlaceBidResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgPlaceBidResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgPlaceBid) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.AuctionId != 0 { - n += 1 + sovTx(uint64(m.AuctionId)) - } - l = len(m.Bidder) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgPlaceBidResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgPlaceBid) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgPlaceBid: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgPlaceBid: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field AuctionId", wireType) - } - m.AuctionId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.AuctionId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Bidder", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Bidder = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgPlaceBidResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgPlaceBidResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgPlaceBidResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/cdp/abci.go b/x/cdp/abci.go deleted file mode 100644 index 33fcc236..00000000 --- a/x/cdp/abci.go +++ /dev/null @@ -1,65 +0,0 @@ -package cdp - -import ( - "errors" - "fmt" - "time" - - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/0glabs/0g-chain/x/cdp/keeper" - "github.com/0glabs/0g-chain/x/cdp/types" - pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" -) - -// BeginBlocker compounds the debt in outstanding cdps and liquidates cdps that are below the required collateralization ratio -func BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock, k keeper.Keeper) { - defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) - - params := k.GetParams(ctx) - - // only run CDP liquidations every `LiquidationBlockInterval` blocks - skipSyncronizeAndLiquidations := ctx.BlockHeight()%params.LiquidationBlockInterval != 0 - - for _, cp := range params.CollateralParams { - ok := k.UpdatePricefeedStatus(ctx, cp.SpotMarketID) - if !ok { - continue - } - - ok = k.UpdatePricefeedStatus(ctx, cp.LiquidationMarketID) - if !ok { - continue - } - - err := k.AccumulateInterest(ctx, cp.Type) - if err != nil { - panic(err) - } - - if skipSyncronizeAndLiquidations { - ctx.Logger().Debug(fmt.Sprintf("skipping x/cdp SynchronizeInterestForRiskyCDPs and LiquidateCdps for %s", cp.Type)) - continue - } - - ctx.Logger().Debug(fmt.Sprintf("running x/cdp SynchronizeInterestForRiskyCDPs and LiquidateCdps for %s", cp.Type)) - - err = k.SynchronizeInterestForRiskyCDPs(ctx, cp.CheckCollateralizationIndexCount, sdk.MaxSortableDec, cp.Type) - if err != nil { - panic(err) - } - - err = k.LiquidateCdps(ctx, cp.LiquidationMarketID, cp.Type, cp.LiquidationRatio, cp.CheckCollateralizationIndexCount) - if err != nil && !errors.Is(err, pricefeedtypes.ErrNoValidPrice) { - panic(err) - } - } - - err := k.RunSurplusAndDebtAuctions(ctx) - if err != nil { - panic(err) - } -} diff --git a/x/cdp/abci_test.go b/x/cdp/abci_test.go deleted file mode 100644 index d26895c7..00000000 --- a/x/cdp/abci_test.go +++ /dev/null @@ -1,293 +0,0 @@ -package cdp_test - -import ( - "math/rand" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" - - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/0glabs/0g-chain/app" - auctiontypes "github.com/0glabs/0g-chain/x/auction/types" - "github.com/0glabs/0g-chain/x/cdp" - "github.com/0glabs/0g-chain/x/cdp/keeper" - "github.com/0glabs/0g-chain/x/cdp/types" -) - -type ModuleTestSuite struct { - suite.Suite - - keeper keeper.Keeper - addrs []sdk.AccAddress - app app.TestApp - cdps types.CDPs - ctx sdk.Context - liquidations liquidationTracker -} - -type liquidationTracker struct { - xrp []uint64 - btc []uint64 - debt int64 -} - -func (suite *ModuleTestSuite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - tracker := liquidationTracker{} - - coins := cs(c("btc", 100000000), c("xrp", 10000000000)) - _, addrs := app.GeneratePrivKeyAddressPairs(100) - authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs) - tApp.InitializeFromGenesisStates( - authGS, - NewPricefeedGenStateMulti(tApp.AppCodec()), - NewCDPGenStateMulti(tApp.AppCodec()), - ) - suite.ctx = ctx - suite.app = tApp - suite.keeper = tApp.GetCDPKeeper() - suite.cdps = types.CDPs{} - suite.addrs = addrs - suite.liquidations = tracker -} - -func (suite *ModuleTestSuite) createCdps() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - cdps := make(types.CDPs, 100) - tracker := liquidationTracker{} - - coins := cs(c("btc", 100000000), c("xrp", 10000000000)) - _, addrs := app.GeneratePrivKeyAddressPairs(100) - - authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs) - tApp.InitializeFromGenesisStates( - authGS, - NewPricefeedGenStateMulti(tApp.AppCodec()), - NewCDPGenStateMulti(tApp.AppCodec()), - ) - - suite.ctx = ctx - suite.app = tApp - suite.keeper = tApp.GetCDPKeeper() - - // create 100 cdps - for j := 0; j < 100; j++ { - // 50 of the cdps will be collateralized with xrp - collateral := "xrp" - amount := 10000000000 - debt := simulation.RandIntBetween(rand.New(rand.NewSource(int64(j))), 750000000, 1249000000) - // the other half (50) will be collateralized with btc - if j%2 == 0 { - collateral = "btc" - amount = 100000000 - debt = simulation.RandIntBetween(rand.New(rand.NewSource(int64(j))), 2700000000, 5332000000) - if debt >= 4000000000 { - tracker.btc = append(tracker.btc, uint64(j+1)) - tracker.debt += int64(debt) - } - } else { - if debt >= 1000000000 { - tracker.xrp = append(tracker.xrp, uint64(j+1)) - tracker.debt += int64(debt) - } - } - suite.Nil(suite.keeper.AddCdp(suite.ctx, addrs[j], c(collateral, int64(amount)), c("usdx", int64(debt)), collateral+"-a")) - c, f := suite.keeper.GetCDP(suite.ctx, collateral+"-a", uint64(j+1)) - suite.True(f) - cdps[j] = c - } - - suite.cdps = cdps - suite.addrs = addrs - suite.liquidations = tracker -} - -func (suite *ModuleTestSuite) setPrice(price sdk.Dec, market string) { - pfKeeper := suite.app.GetPriceFeedKeeper() - - _, err := pfKeeper.SetPrice(suite.ctx, sdk.AccAddress{}, market, price, suite.ctx.BlockTime().Add(time.Hour*3)) - suite.NoError(err) - - err = pfKeeper.SetCurrentPrices(suite.ctx, market) - suite.NoError(err) - pp, err := pfKeeper.GetCurrentPrice(suite.ctx, market) - suite.NoError(err) - suite.Equal(price, pp.Price) -} - -func (suite *ModuleTestSuite) TestBeginBlock() { - // test setup, creating - // 50 xrp cdps each with - // collateral: 10000000000 - // debt: between 750000000 - 1249000000 - // if debt above 10000000000, - // cdp added to tracker / liquidation list - // debt total added to trackers debt total - // 50 btc cdps each with - // collateral: 10000000000 - // debt: between 2700000000 - 5332000000 - // if debt above 4000000000, - // cdp added to tracker / liquidation list - // debt total added to trackers debt total - - // naively we expect roughly half of the cdps to be above the debt tracking floor, roughly 25 of them collaterallized with xrp, the other 25 with btcb - - // usdx is the principal for all cdps - suite.createCdps() - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - - // test case 1 setup - acc := ak.GetModuleAccount(suite.ctx, types.ModuleName) - // track how much xrp collateral exists in the cdp module - originalXrpCollateral := bk.GetBalance(suite.ctx, acc.GetAddress(), "xrp").Amount - // set the trading price for xrp:usd pools - suite.setPrice(d("0.2"), "xrp:usd") - - // test case 1 execution - cdp.BeginBlocker(suite.ctx, abci.RequestBeginBlock{Header: suite.ctx.BlockHeader()}, suite.keeper) - - // test case 1 assert - acc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - // get the current amount of xrp held by the cdp module - finalXrpCollateral := bk.GetBalance(suite.ctx, acc.GetAddress(), "xrp").Amount - seizedXrpCollateral := originalXrpCollateral.Sub(finalXrpCollateral) - // calculate the number of cdps that were liquidated based on the total - // seized collateral divided by the size of each cdp when it was created - xrpLiquidations := int(seizedXrpCollateral.Quo(i(10000000000)).Int64()) - // should be 10 because...? - suite.Equal(10, xrpLiquidations) - - // btc collateral test case setup - acc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - originalBtcCollateral := bk.GetBalance(suite.ctx, acc.GetAddress(), "btc").Amount - // set the trading price for btc:usd pools - suite.setPrice(d("6000"), "btc:usd") - - // btc collateral test case execution - cdp.BeginBlocker(suite.ctx, abci.RequestBeginBlock{Header: suite.ctx.BlockHeader()}, suite.keeper) - - // btc collateral test case assertion 1 - acc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - finalBtcCollateral := bk.GetBalance(suite.ctx, acc.GetAddress(), "btc").Amount - seizedBtcCollateral := originalBtcCollateral.Sub(finalBtcCollateral) - // calculate the number of btc cdps that were liquidated based on the - // total seized collateral divided by the fixed size of each cdp - // when it was created during test setup - btcLiquidations := int(seizedBtcCollateral.Quo(i(100000000)).Int64()) - suite.Equal(10, btcLiquidations) - - // btc collateral test case assertion 2 - // test that the auction module has a balance equal to the amount of collateral seized - acc = ak.GetModuleAccount(suite.ctx, auctiontypes.ModuleName) - // should be this exact value because...? - suite.Equal(int64(71955653865), bk.GetBalance(suite.ctx, acc.GetAddress(), "debt").Amount.Int64()) -} - -func (suite *ModuleTestSuite) TestSeizeSingleCdpWithFees() { - // test setup - // starting with zero cdps, add a single cdp of - // xrp backed 1:1 with usdx - err := suite.keeper.AddCdp(suite.ctx, suite.addrs[0], c("xrp", 10000000000), c("usdx", 1000000000), "xrp-a") - suite.NoError(err) - // verify the total value of all assets in cdps composed of xrp-a/usdx pair equals the amount of the single cdp we just added above - suite.Equal(i(1000000000), suite.keeper.GetTotalPrincipal(suite.ctx, "xrp-a", "usdx")) - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - - cdpMacc := ak.GetModuleAccount(suite.ctx, types.ModuleName) - suite.Equal(i(1000000000), bk.GetBalance(suite.ctx, cdpMacc.GetAddress(), "debt").Amount) - for i := 0; i < 100; i++ { - suite.ctx = suite.ctx.WithBlockTime(suite.ctx.BlockTime().Add(time.Second * 6)) - cdp.BeginBlocker(suite.ctx, abci.RequestBeginBlock{Header: suite.ctx.BlockHeader()}, suite.keeper) - } - - cdpMacc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - suite.Equal(i(1000000891), (bk.GetBalance(suite.ctx, cdpMacc.GetAddress(), "debt").Amount)) - cdp, _ := suite.keeper.GetCDP(suite.ctx, "xrp-a", 1) - - err = suite.keeper.SeizeCollateral(suite.ctx, cdp) - suite.NoError(err) - _, found := suite.keeper.GetCDP(suite.ctx, "xrp-a", 1) - suite.False(found) -} - -func (suite *ModuleTestSuite) TestCDPBeginBlockerRunsOnlyOnConfiguredInterval() { - // test setup, creating - // 50 xrp cdps each with - // collateral: 10000000000 - // debt: between 750000000 - 1249000000 - // if debt above 10000000000, - // cdp added to tracker / liquidation list - // debt total added to trackers debt total - // 50 btc cdps each with - // collateral: 10000000000 - // debt: between 2700000000 - 5332000000 - // if debt above 4000000000, - // cdp added to tracker / liquidation list - // debt total added to trackers debt total - - // naively we expect roughly half of the cdps to be above the debt tracking floor, roughly 25 of them collaterallized with xrp, the other 25 with btcb - - // usdx is the principal for all cdps - suite.createCdps() - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - - // set the cdp begin blocker to run every other block - params := suite.keeper.GetParams(suite.ctx) - params.LiquidationBlockInterval = 2 - suite.keeper.SetParams(suite.ctx, params) - - // test case 1 setup - acc := ak.GetModuleAccount(suite.ctx, types.ModuleName) - // track how much xrp collateral exists in the cdp module - originalXrpCollateral := bk.GetBalance(suite.ctx, acc.GetAddress(), "xrp").Amount - // set the trading price for xrp:usd pools - suite.setPrice(d("0.2"), "xrp:usd") - - // test case 1 execution - cdp.BeginBlocker(suite.ctx, abci.RequestBeginBlock{Header: suite.ctx.BlockHeader()}, suite.keeper) - - // test case 1 assert - acc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - // get the current amount of xrp held by the cdp module - finalXrpCollateral := bk.GetBalance(suite.ctx, acc.GetAddress(), "xrp").Amount - seizedXrpCollateral := originalXrpCollateral.Sub(finalXrpCollateral) - // calculate the number of cdps that were liquidated based on the total - // seized collateral divided by the size of each cdp when it was created - xrpLiquidations := int(seizedXrpCollateral.Quo(i(10000000000)).Int64()) - // should be 0 because the cdp begin blocker is configured to - // skip execution every odd numbered block - suite.Equal(0, xrpLiquidations, "expected cdp begin blocker not to run liqudations") - - // test case 2 setup - // simulate running the second block of the chain - suite.ctx = suite.ctx.WithBlockHeight(2) - - // test case 2 execution - cdp.BeginBlocker(suite.ctx, abci.RequestBeginBlock{Header: suite.ctx.BlockHeader()}, suite.keeper) - - // test case 2 assert - acc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - // get the current amount of xrp held by the cdp module - finalXrpCollateral = bk.GetBalance(suite.ctx, acc.GetAddress(), "xrp").Amount - seizedXrpCollateral = originalXrpCollateral.Sub(finalXrpCollateral) - // calculate the number of cdps that were liquidated based on the total - // seized collateral divided by the size of each cdp when it was created - xrpLiquidations = int(seizedXrpCollateral.Quo(i(10000000000)).Int64()) - suite.Greater(xrpLiquidations, 0, "expected cdp begin blocker to run liquidations") -} - -func TestModuleTestSuite(t *testing.T) { - suite.Run(t, new(ModuleTestSuite)) -} diff --git a/x/cdp/client/cli/query.go b/x/cdp/client/cli/query.go deleted file mode 100644 index 3b2089c9..00000000 --- a/x/cdp/client/cli/query.go +++ /dev/null @@ -1,272 +0,0 @@ -package cli - -import ( - "context" - "fmt" - "strconv" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/0glabs/0g-chain/x/cdp/types" -) - -// Query CDP flags -const ( - flagCollateralType = "collateral-type" - flagOwner = "owner" - flagID = "id" - flagRatio = "ratio" // returns CDPs under the given collateralization ratio threshold -) - -// GetQueryCmd returns the cli query commands for this module -func GetQueryCmd() *cobra.Command { - // Group nameservice queries under a subcommand - cdpQueryCmd := &cobra.Command{ - Use: "cdp", - Short: "Querying commands for the cdp module", - } - - cmds := []*cobra.Command{ - QueryCdpCmd(), - QueryGetCdpsCmd(), - QueryCdpDepositsCmd(), - QueryParamsCmd(), - QueryGetAccounts(), - } - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - cdpQueryCmd.AddCommand(cmds...) - - return cdpQueryCmd -} - -// QueryCdpCmd returns the command handler for querying a particular cdp -func QueryCdpCmd() *cobra.Command { - return &cobra.Command{ - Use: "cdp [owner-addr] [collateral-type]", - Short: "get info about a cdp", - Long: strings.TrimSpace( - fmt.Sprintf(`Get a CDP by the owner address and the collateral name. - -Example: -$ %s query %s cdp kava15qdefkmwswysgg4qxgqpqr35k3m49pkx2jdfnw atom-a -`, version.AppName, types.ModuleName)), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - _, err = sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - - res, err := queryClient.Cdp(context.Background(), &types.QueryCdpRequest{ - Owner: args[0], - CollateralType: args[1], - }) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -// QueryGetCdpsCmd queries the cdps in the store -func QueryGetCdpsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "cdps", - Short: "query cdps with optional filters", - Long: strings.TrimSpace(`Query for all paginated cdps that match optional filters: -Example: -$ kvcli q cdp cdps --collateral-type=bnb -$ kvcli q cdp cdps --owner=kava1hatdq32u5x4wnxrtv5wzjzmq49sxgjgsj0mffm -$ kvcli q cdp cdps --id=21 -$ kvcli q cdp cdps --ratio=2.75 -$ kvcli q cdp cdps --page=2 --limit=100 -`, - ), - RunE: func(cmd *cobra.Command, args []string) error { - strCollateralType, err := cmd.Flags().GetString(flagCollateralType) - if err != nil { - return err - } - strOwner, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - strID, err := cmd.Flags().GetString(flagID) - if err != nil { - return err - } - strRatio, err := cmd.Flags().GetString(flagRatio) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - req := types.QueryCdpsRequest{ - Pagination: pageReq, - } - - if len(strCollateralType) != 0 { - req.CollateralType = strings.ToLower(strings.TrimSpace(strCollateralType)) - } - - if len(strOwner) != 0 { - cdpOwner, err := sdk.AccAddressFromBech32(strings.ToLower(strings.TrimSpace(strOwner))) - if err != nil { - return fmt.Errorf("cannot parse address from cdp owner %s", strOwner) - } - req.Owner = cdpOwner.String() - } - - if len(strID) != 0 { - cdpID, err := strconv.ParseUint(strID, 10, 64) - if err != nil { - return fmt.Errorf("cannot parse cdp ID %s", strID) - } - req.ID = cdpID - } - - if len(strRatio) != 0 { - cdpRatio, err := sdk.NewDecFromStr(strRatio) - if err != nil { - return fmt.Errorf("cannot parse cdp ratio %s", strRatio) - } - // ratio is also validated on server - req.Ratio = cdpRatio.String() - } - - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.Cdps(context.Background(), &req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - cmd.Flags().String(flagCollateralType, "", "(optional) filter by CDP collateral type") - cmd.Flags().String(flagOwner, "", "(optional) filter by CDP owner") - cmd.Flags().String(flagID, "", "(optional) filter by CDP ID") - cmd.Flags().String(flagRatio, "", "(optional) filter by CDP collateralization ratio threshold") - - flags.AddPaginationFlagsToCmd(cmd, "cdps") - - return cmd -} - -// QueryCdpDepositsCmd returns the command handler for querying the deposits of a particular cdp -func QueryCdpDepositsCmd() *cobra.Command { - return &cobra.Command{ - Use: "deposits [owner-addr] [collateral-type]", - Short: "get deposits for a cdp", - Long: strings.TrimSpace( - fmt.Sprintf(`Get the deposits of a CDP. - -Example: -$ %s query %s deposits kava15qdefkmwswysgg4qxgqpqr35k3m49pkx2jdfnw atom-a -`, version.AppName, types.ModuleName)), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - _, err = sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - - res, err := queryClient.Deposits(context.Background(), &types.QueryDepositsRequest{ - Owner: args[0], - CollateralType: args[1], - }) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -// QueryParamsCmd returns the command handler for cdp parameter querying -func QueryParamsCmd() *cobra.Command { - return &cobra.Command{ - Use: "params", - Short: "get the cdp module parameters", - Long: "get the current global cdp module parameters.", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.Params(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - } -} - -// QueryGetAccounts queries CDP module accounts -func QueryGetAccounts() *cobra.Command { - return &cobra.Command{ - Use: "accounts", - Short: "get module accounts", - Long: "get cdp module account addresses", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.Accounts(context.Background(), &types.QueryAccountsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} diff --git a/x/cdp/client/cli/tx.go b/x/cdp/client/cli/tx.go deleted file mode 100644 index 87c9e1eb..00000000 --- a/x/cdp/client/cli/tx.go +++ /dev/null @@ -1,245 +0,0 @@ -package cli - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/0glabs/0g-chain/x/cdp/types" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - cdpTxCmd := &cobra.Command{ - Use: "cdp", - Short: "cdp transactions subcommands", - } - - cmds := []*cobra.Command{ - GetCmdCreateCdp(), - GetCmdDeposit(), - GetCmdWithdraw(), - GetCmdDraw(), - GetCmdRepay(), - GetCmdLiquidate(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - cdpTxCmd.AddCommand(cmds...) - - return cdpTxCmd -} - -// GetCmdCreateCdp returns the command handler for creating a cdp -func GetCmdCreateCdp() *cobra.Command { - return &cobra.Command{ - Use: "create [collateral] [debt] [collateral-type]", - Short: "create a new cdp", - Long: strings.TrimSpace( - fmt.Sprintf(`Create a new cdp, depositing some collateral and drawing some debt. - -Example: -$ %s tx %s create 10000000uatom 1000usdx atom-a --from myKeyName -`, version.AppName, types.ModuleName)), - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - collateral, err := sdk.ParseCoinNormalized(args[0]) - if err != nil { - return err - } - debt, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - msg := types.NewMsgCreateCDP(clientCtx.GetFromAddress(), collateral, debt, args[2]) - err = msg.ValidateBasic() - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -// GetCmdDeposit cli command for depositing to a cdp. -func GetCmdDeposit() *cobra.Command { - return &cobra.Command{ - Use: "deposit [owner-addr] [collateral] [collateral-type]", - Short: "deposit collateral to an existing cdp", - Long: strings.TrimSpace( - fmt.Sprintf(`Add collateral to an existing cdp. - -Example: -$ %s tx %s deposit kava15qdefkmwswysgg4qxgqpqr35k3m49pkx2jdfnw 10000000uatom atom-a --from myKeyName -`, version.AppName, types.ModuleName)), - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - collateral, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - owner, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - msg := types.NewMsgDeposit(owner, clientCtx.GetFromAddress(), collateral, args[2]) - err = msg.ValidateBasic() - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -// GetCmdWithdraw cli command for withdrawing from a cdp. -func GetCmdWithdraw() *cobra.Command { - return &cobra.Command{ - Use: "withdraw [owner-addr] [collateral] [collateral-type]", - Short: "withdraw collateral from an existing cdp", - Long: strings.TrimSpace( - fmt.Sprintf(`Remove collateral from an existing cdp. - -Example: -$ %s tx %s withdraw kava15qdefkmwswysgg4qxgqpqr35k3m49pkx2jdfnw 10000000uatom atom-a --from myKeyName -`, version.AppName, types.ModuleName)), - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - collateral, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - owner, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - msg := types.NewMsgWithdraw(owner, clientCtx.GetFromAddress(), collateral, args[2]) - err = msg.ValidateBasic() - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -// GetCmdDraw cli command for depositing to a cdp. -func GetCmdDraw() *cobra.Command { - return &cobra.Command{ - Use: "draw [collateral-type] [debt]", - Short: "draw debt off an existing cdp", - Long: strings.TrimSpace( - fmt.Sprintf(`Create debt in an existing cdp and send the newly minted asset to your account. - -Example: -$ %s tx %s draw atom-a 1000usdx --from myKeyName -`, version.AppName, types.ModuleName)), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - debt, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - msg := types.NewMsgDrawDebt(clientCtx.GetFromAddress(), args[0], debt) - err = msg.ValidateBasic() - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -// GetCmdRepay cli command for depositing to a cdp. -func GetCmdRepay() *cobra.Command { - return &cobra.Command{ - Use: "repay [collateral-name] [debt]", - Short: "repay debt to an existing cdp", - Long: strings.TrimSpace( - fmt.Sprintf(`Cancel out debt in an existing cdp. - -Example: -$ %s tx %s repay atom-a 1000usdx --from myKeyName -`, version.AppName, types.ModuleName)), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - payment, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - msg := types.NewMsgRepayDebt(clientCtx.GetFromAddress(), args[0], payment) - err = msg.ValidateBasic() - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -// GetCmdLiquidate cli command for liquidating a cdp. -func GetCmdLiquidate() *cobra.Command { - return &cobra.Command{ - Use: "liquidate [cdp-owner-address] [collateral-type]", - Short: "liquidate a cdp", - Long: strings.TrimSpace( - fmt.Sprintf(`Liquidate a cdp if it is below the required liquidation ratio - -Example: -$ %s tx %s liquidate kava1y70y90wzmnf00e63efk2lycgqwepthdmyzsfzm btcb-a --from myKeyName -`, version.AppName, types.ModuleName)), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - addr, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - msg := types.NewMsgLiquidate(clientCtx.GetFromAddress(), addr, args[1]) - err = msg.ValidateBasic() - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} diff --git a/x/cdp/genesis.go b/x/cdp/genesis.go deleted file mode 100644 index 0f5b3148..00000000 --- a/x/cdp/genesis.go +++ /dev/null @@ -1,133 +0,0 @@ -package cdp - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/cdp/keeper" - "github.com/0glabs/0g-chain/x/cdp/types" -) - -// InitGenesis sets initial genesis state for cdp module -func InitGenesis(ctx sdk.Context, k keeper.Keeper, pk types.PricefeedKeeper, ak types.AccountKeeper, gs types.GenesisState) { - if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) - } - - // check if the module accounts exists - cdpModuleAcc := ak.GetModuleAccount(ctx, types.ModuleName) - if cdpModuleAcc == nil { - panic(fmt.Sprintf("%s module account has not been set", types.ModuleName)) - } - liqModuleAcc := ak.GetModuleAccount(ctx, types.LiquidatorMacc) - if liqModuleAcc == nil { - panic(fmt.Sprintf("%s module account has not been set", types.LiquidatorMacc)) - } - - // validate denoms - check that any collaterals in the params are in the pricefeed, - // pricefeed MUST call InitGenesis before cdp - collateralMap := make(map[string]int) - ap := pk.GetParams(ctx) - for _, a := range ap.Markets { - collateralMap[a.MarketID] = 1 - } - - for _, col := range gs.Params.CollateralParams { - _, found := collateralMap[col.SpotMarketID] - if !found { - panic(fmt.Sprintf("%s collateral market %v not found in pricefeed", col.Denom, col.SpotMarketID)) - } - // sets the status of the pricefeed in the store - // if pricefeed not active, debt operations are paused - _ = k.UpdatePricefeedStatus(ctx, col.SpotMarketID) - - _, found = collateralMap[col.LiquidationMarketID] - if !found { - panic(fmt.Sprintf("%s collateral market %v not found in pricefeed", col.Denom, col.LiquidationMarketID)) - } - // sets the status of the pricefeed in the store - // if pricefeed not active, debt operations are paused - _ = k.UpdatePricefeedStatus(ctx, col.LiquidationMarketID) - } - - k.SetParams(ctx, gs.Params) - - for _, gat := range gs.PreviousAccumulationTimes { - k.SetInterestFactor(ctx, gat.CollateralType, gat.InterestFactor) - if gat.PreviousAccumulationTime.Unix() > 0 { - k.SetPreviousAccrualTime(ctx, gat.CollateralType, gat.PreviousAccumulationTime) - } - } - - for _, gtp := range gs.TotalPrincipals { - k.SetTotalPrincipal(ctx, gtp.CollateralType, types.DefaultStableDenom, gtp.TotalPrincipal) - } - // add cdps - for _, cdp := range gs.CDPs { - if cdp.ID == gs.StartingCdpID { - panic(fmt.Sprintf("starting cdp id is assigned to an existing cdp: %v", cdp)) - } - err := k.SetCDP(ctx, cdp) - if err != nil { - panic(fmt.Sprintf("error setting cdp: %v", err)) - } - k.IndexCdpByOwner(ctx, cdp) - ratio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Type, cdp.GetTotalPrincipal()) - k.IndexCdpByCollateralRatio(ctx, cdp.Type, cdp.ID, ratio) - } - - k.SetNextCdpID(ctx, gs.StartingCdpID) - k.SetDebtDenom(ctx, gs.DebtDenom) - k.SetGovDenom(ctx, gs.GovDenom) - - for _, d := range gs.Deposits { - k.SetDeposit(ctx, d) - } -} - -// ExportGenesis export genesis state for cdp module -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { - params := k.GetParams(ctx) - - cdps := types.CDPs{} - deposits := types.Deposits{} - k.IterateAllCdps(ctx, func(cdp types.CDP) (stop bool) { - syncedCdp := k.SynchronizeInterest(ctx, cdp) - cdps = append(cdps, syncedCdp) - k.IterateDeposits(ctx, cdp.ID, func(deposit types.Deposit) (stop bool) { - deposits = append(deposits, deposit) - return false - }) - return false - }) - - cdpID := k.GetNextCdpID(ctx) - debtDenom := k.GetDebtDenom(ctx) - govDenom := k.GetGovDenom(ctx) - - var previousAccumTimes types.GenesisAccumulationTimes - var totalPrincipals types.GenesisTotalPrincipals - - for _, cp := range params.CollateralParams { - interestFactor, found := k.GetInterestFactor(ctx, cp.Type) - if !found { - interestFactor = sdk.OneDec() - } - // Governance param changes happen in the end blocker. If a new collateral type is added and then the chain - // is exported before the BeginBlocker can run, previous accrual time won't be found. We can't set it to - // current block time because it is not available in the export ctx. We should panic instead of exporting - // bad state. - previousAccumTime, f := k.GetPreviousAccrualTime(ctx, cp.Type) - if !f { - panic(fmt.Sprintf("expected previous accrual time to be set in state for %s", cp.Type)) - } - previousAccumTimes = append(previousAccumTimes, types.NewGenesisAccumulationTime(cp.Type, previousAccumTime, interestFactor)) - - tp := k.GetTotalPrincipal(ctx, cp.Type, types.DefaultStableDenom) - genTotalPrincipal := types.NewGenesisTotalPrincipal(cp.Type, tp) - totalPrincipals = append(totalPrincipals, genTotalPrincipal) - } - - return types.NewGenesisState(params, cdps, deposits, cdpID, debtDenom, govDenom, previousAccumTimes, totalPrincipals) -} diff --git a/x/cdp/genesis_test.go b/x/cdp/genesis_test.go deleted file mode 100644 index fea06051..00000000 --- a/x/cdp/genesis_test.go +++ /dev/null @@ -1,331 +0,0 @@ -package cdp_test - -import ( - "fmt" - "sort" - "strings" - "testing" - "time" - - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/cdp" - "github.com/0glabs/0g-chain/x/cdp/keeper" - "github.com/0glabs/0g-chain/x/cdp/types" -) - -type GenesisTestSuite struct { - suite.Suite - - app app.TestApp - ctx sdk.Context - genTime time.Time - keeper keeper.Keeper - addrs []sdk.AccAddress -} - -func (suite *GenesisTestSuite) SetupTest() { - tApp := app.NewTestApp() - suite.genTime = tmtime.Canonical(time.Date(2021, 1, 1, 1, 1, 1, 1, time.UTC)) - suite.ctx = tApp.NewContext(true, tmproto.Header{Height: 1, Time: suite.genTime}) - suite.keeper = tApp.GetCDPKeeper() - suite.app = tApp - - _, addrs := app.GeneratePrivKeyAddressPairs(3) - suite.addrs = addrs -} - -func (suite *GenesisTestSuite) TestInvalidGenState() { - type args struct { - params types.Params - cdps types.CDPs - deposits types.Deposits - startingID uint64 - debtDenom string - govDenom string - genAccumTimes types.GenesisAccumulationTimes - genTotalPrincipals types.GenesisTotalPrincipals - } - type errArgs struct { - expectPass bool - contains string - } - - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - name: "empty debt denom", - args: args{ - params: types.DefaultParams(), - cdps: types.CDPs{}, - deposits: types.Deposits{}, - debtDenom: "", - govDenom: types.DefaultGovDenom, - genAccumTimes: types.DefaultGenesisState().PreviousAccumulationTimes, - genTotalPrincipals: types.DefaultGenesisState().TotalPrincipals, - }, - errArgs: errArgs{ - expectPass: false, - contains: "debt denom invalid", - }, - }, - { - name: "empty gov denom", - args: args{ - params: types.DefaultParams(), - cdps: types.CDPs{}, - deposits: types.Deposits{}, - debtDenom: types.DefaultDebtDenom, - govDenom: "", - genAccumTimes: types.DefaultGenesisState().PreviousAccumulationTimes, - genTotalPrincipals: types.DefaultGenesisState().TotalPrincipals, - }, - errArgs: errArgs{ - expectPass: false, - contains: "gov denom invalid", - }, - }, - { - name: "interest factor below one", - args: args{ - params: types.DefaultParams(), - cdps: types.CDPs{}, - deposits: types.Deposits{}, - debtDenom: types.DefaultDebtDenom, - govDenom: types.DefaultGovDenom, - genAccumTimes: types.GenesisAccumulationTimes{types.NewGenesisAccumulationTime("bnb-a", time.Time{}, sdk.OneDec().Sub(sdk.SmallestDec()))}, - genTotalPrincipals: types.DefaultGenesisState().TotalPrincipals, - }, - errArgs: errArgs{ - expectPass: false, - contains: "interest factor should be ≥ 1.0", - }, - }, - { - name: "negative total principal", - args: args{ - params: types.DefaultParams(), - cdps: types.CDPs{}, - deposits: types.Deposits{}, - debtDenom: types.DefaultDebtDenom, - govDenom: types.DefaultGovDenom, - genAccumTimes: types.DefaultGenesisState().PreviousAccumulationTimes, - genTotalPrincipals: types.GenesisTotalPrincipals{types.NewGenesisTotalPrincipal("bnb-a", sdkmath.NewInt(-1))}, - }, - errArgs: errArgs{ - expectPass: false, - contains: "total principal should be positive", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - gs := types.NewGenesisState(tc.args.params, tc.args.cdps, tc.args.deposits, tc.args.startingID, - tc.args.debtDenom, tc.args.govDenom, tc.args.genAccumTimes, tc.args.genTotalPrincipals) - err := gs.Validate() - if tc.errArgs.expectPass { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *GenesisTestSuite) TestValidGenState() { - cdc := suite.app.AppCodec() - - suite.NotPanics(func() { - suite.app.InitializeFromGenesisStates( - NewPricefeedGenStateMulti(cdc), - NewCDPGenStateMulti(cdc), - ) - }) - - cdpGS := NewCDPGenStateMulti(cdc) - gs := types.GenesisState{} - suite.app.AppCodec().MustUnmarshalJSON(cdpGS["cdp"], &gs) - gs.CDPs = cdps() - gs.StartingCdpID = uint64(5) - appGS := app.GenesisState{"cdp": suite.app.AppCodec().MustMarshalJSON(&gs)} - suite.NotPanics(func() { - suite.SetupTest() - suite.app.InitializeFromGenesisStates( - NewPricefeedGenStateMulti(cdc), - appGS, - ) - }) -} - -func (suite *GenesisTestSuite) Test_InitExportGenesis() { - cdps := types.CDPs{ - { - ID: 2, - Owner: suite.addrs[0], - Type: "xrp-a", - Collateral: c("xrp", 200000000), - Principal: c("usdx", 10000000), - AccumulatedFees: c("usdx", 0), - FeesUpdated: suite.genTime, - InterestFactor: sdk.NewDec(1), - }, - } - - genTotalPrincipals := types.GenesisTotalPrincipals{ - types.NewGenesisTotalPrincipal("btc-a", sdk.ZeroInt()), - types.NewGenesisTotalPrincipal("xrp-a", sdk.ZeroInt()), - } - - var deposits types.Deposits - for _, c := range cdps { - deposit := types.Deposit{ - CdpID: c.ID, - Depositor: c.Owner, - Amount: c.Collateral, - } - deposits = append(deposits, deposit) - - for i, p := range genTotalPrincipals { - if p.CollateralType == c.Type { - genTotalPrincipals[i].TotalPrincipal = genTotalPrincipals[i].TotalPrincipal.Add(c.Principal.Amount) - } - } - } - - cdpGenesis := types.GenesisState{ - Params: types.Params{ - GlobalDebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - SurplusAuctionThreshold: types.DefaultSurplusThreshold, - SurplusAuctionLot: types.DefaultSurplusLot, - DebtAuctionThreshold: types.DefaultDebtThreshold, - DebtAuctionLot: types.DefaultDebtLot, - LiquidationBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - CollateralParams: types.CollateralParams{ - { - Denom: "xrp", - Type: "xrp-a", - LiquidationRatio: sdk.MustNewDecFromStr("2.0"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // 5% apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(7000000000), - SpotMarketID: "xrp:usd", - LiquidationMarketID: "xrp:usd", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(6), - }, - { - Denom: "btc", - Type: "btc-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000000782997609"), // 2.5% apr - LiquidationPenalty: d("0.025"), - AuctionSize: i(10000000), - SpotMarketID: "btc:usd", - LiquidationMarketID: "btc:usd", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(8), - }, - }, - DebtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: i(6), - DebtFloor: i(10000000), - }, - }, - StartingCdpID: types.DefaultCdpStartingID, - DebtDenom: types.DefaultDebtDenom, - GovDenom: types.DefaultGovDenom, - CDPs: cdps, - Deposits: deposits, - PreviousAccumulationTimes: types.GenesisAccumulationTimes{ - types.NewGenesisAccumulationTime("btc-a", suite.genTime, sdk.OneDec()), - types.NewGenesisAccumulationTime("xrp-a", suite.genTime, sdk.OneDec()), - }, - TotalPrincipals: genTotalPrincipals, - } - - suite.NotPanics(func() { - suite.app.InitializeFromGenesisStatesWithTime( - suite.genTime, - NewPricefeedGenStateMulti(suite.app.AppCodec()), - app.GenesisState{types.ModuleName: suite.app.AppCodec().MustMarshalJSON(&cdpGenesis)}, - ) - }) - - // We run the BeginBlocker at time.Now() to accumulate interest - suite.ctx = suite.ctx.WithBlockTime(time.Now()) - cdp.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}, suite.keeper) - - expectedGenesis := cdpGenesis - - // Update previous accrual times in expected genesis - var expectedPrevAccTimes types.GenesisAccumulationTimes - for _, prevAccTime := range cdpGenesis.PreviousAccumulationTimes { - time, found := suite.keeper.GetPreviousAccrualTime(suite.ctx, prevAccTime.CollateralType) - if !found { - panic(fmt.Sprintf("couldn't find previous accrual time for %s", prevAccTime.CollateralType)) - } - prevAccTime.PreviousAccumulationTime = time - - interestFactor, found := suite.keeper.GetInterestFactor(suite.ctx, prevAccTime.CollateralType) - if !found { - panic(fmt.Sprintf("couldn't find interest factor for %s", prevAccTime.CollateralType)) - } - prevAccTime.InterestFactor = interestFactor - - expectedPrevAccTimes = append(expectedPrevAccTimes, prevAccTime) - } - expectedGenesis.PreviousAccumulationTimes = expectedPrevAccTimes - - // Update total principals - var totalPrincipals types.GenesisTotalPrincipals - for _, p := range expectedGenesis.TotalPrincipals { - totalPrincipal := suite.keeper.GetTotalPrincipal(suite.ctx, p.CollateralType, "usdx") - p.TotalPrincipal = totalPrincipal - totalPrincipals = append(totalPrincipals, p) - } - expectedGenesis.TotalPrincipals = totalPrincipals - - // Update CDPs - expectedGenesis.CDPs = suite.keeper.GetAllCdps(suite.ctx) - - exportedGenesis := cdp.ExportGenesis(suite.ctx, suite.keeper) - - // Sort TotalPrincipals in both genesis files so slice order matches - sort.SliceStable(expectedGenesis.TotalPrincipals, func(i, j int) bool { - return expectedGenesis.TotalPrincipals[i].CollateralType < expectedGenesis.TotalPrincipals[j].CollateralType - }) - sort.SliceStable(exportedGenesis.TotalPrincipals, func(i, j int) bool { - return exportedGenesis.TotalPrincipals[i].CollateralType < exportedGenesis.TotalPrincipals[j].CollateralType - }) - - // Sort PreviousAccumulationTimes in both genesis files so slice order matches - sort.SliceStable(expectedGenesis.PreviousAccumulationTimes, func(i, j int) bool { - return expectedGenesis.PreviousAccumulationTimes[i].CollateralType < expectedGenesis.PreviousAccumulationTimes[j].CollateralType - }) - sort.SliceStable(exportedGenesis.PreviousAccumulationTimes, func(i, j int) bool { - return exportedGenesis.PreviousAccumulationTimes[i].CollateralType < exportedGenesis.PreviousAccumulationTimes[j].CollateralType - }) - - suite.Equal(expectedGenesis, exportedGenesis) -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(GenesisTestSuite)) -} diff --git a/x/cdp/integration_test.go b/x/cdp/integration_test.go deleted file mode 100644 index 80b99507..00000000 --- a/x/cdp/integration_test.go +++ /dev/null @@ -1,183 +0,0 @@ -package cdp_test - -import ( - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/cdp/types" - pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" -) - -// Avoid cluttering test cases with long function names -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...) } - -func NewPricefeedGenState(cdc codec.JSONCodec, asset string, price sdk.Dec) app.GenesisState { - pfGenesis := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: asset + ":usd", BaseAsset: asset, QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: asset + ":usd", - OracleAddress: sdk.AccAddress{}, - Price: price, - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - return app.GenesisState{pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pfGenesis)} -} - -func NewCDPGenState(cdc codec.JSONCodec, asset string, liquidationRatio sdk.Dec) app.GenesisState { - cdpGenesis := types.GenesisState{ - Params: types.Params{ - GlobalDebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - SurplusAuctionThreshold: types.DefaultSurplusThreshold, - SurplusAuctionLot: types.DefaultSurplusLot, - DebtAuctionThreshold: types.DefaultDebtThreshold, - DebtAuctionLot: types.DefaultDebtLot, - CollateralParams: types.CollateralParams{ - { - Denom: asset, - Type: asset + "-a", - LiquidationRatio: liquidationRatio, - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(1000000000), - ConversionFactor: i(6), - SpotMarketID: asset + ":usd", - LiquidationMarketID: asset + ":usd", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - }, - }, - DebtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: i(6), - DebtFloor: i(10000000), - }, - }, - StartingCdpID: types.DefaultCdpStartingID, - DebtDenom: types.DefaultDebtDenom, - GovDenom: types.DefaultGovDenom, - CDPs: types.CDPs{}, - PreviousAccumulationTimes: types.GenesisAccumulationTimes{ - types.NewGenesisAccumulationTime(asset+"-a", time.Time{}, sdk.OneDec()), - }, - TotalPrincipals: types.GenesisTotalPrincipals{ - types.NewGenesisTotalPrincipal(asset+"-a", sdk.ZeroInt()), - }, - } - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&cdpGenesis)} -} - -func NewPricefeedGenStateMulti(cdc codec.JSONCodec) app.GenesisState { - pfGenesis := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "btc:usd", BaseAsset: "btc", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "xrp:usd", BaseAsset: "xrp", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "btc:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("8000.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "xrp:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("0.25"), - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - return app.GenesisState{pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pfGenesis)} -} - -func NewCDPGenStateMulti(cdc codec.JSONCodec) app.GenesisState { - cdpGenesis := types.GenesisState{ - Params: types.Params{ - GlobalDebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - SurplusAuctionThreshold: types.DefaultSurplusThreshold, - SurplusAuctionLot: types.DefaultSurplusLot, - DebtAuctionThreshold: types.DefaultDebtThreshold, - DebtAuctionLot: types.DefaultDebtLot, - LiquidationBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - CollateralParams: types.CollateralParams{ - { - Denom: "xrp", - Type: "xrp-a", - LiquidationRatio: sdk.MustNewDecFromStr("2.0"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(7000000000), - SpotMarketID: "xrp:usd", - LiquidationMarketID: "xrp:usd", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(6), - }, - { - Denom: "btc", - Type: "btc-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000000782997609"), // %2.5 apr - LiquidationPenalty: d("0.025"), - AuctionSize: i(10000000), - SpotMarketID: "btc:usd", - LiquidationMarketID: "btc:usd", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(8), - }, - }, - DebtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: i(6), - DebtFloor: i(10000000), - }, - }, - StartingCdpID: types.DefaultCdpStartingID, - DebtDenom: types.DefaultDebtDenom, - GovDenom: types.DefaultGovDenom, - CDPs: types.CDPs{}, - PreviousAccumulationTimes: types.GenesisAccumulationTimes{ - types.NewGenesisAccumulationTime("btc-a", time.Time{}, sdk.OneDec()), - types.NewGenesisAccumulationTime("xrp-a", time.Time{}, sdk.OneDec()), - }, - TotalPrincipals: types.GenesisTotalPrincipals{ - types.NewGenesisTotalPrincipal("btc-a", sdk.ZeroInt()), - types.NewGenesisTotalPrincipal("xrp-a", sdk.ZeroInt()), - }, - } - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&cdpGenesis)} -} - -func cdps() (cdps types.CDPs) { - _, addrs := app.GeneratePrivKeyAddressPairs(3) - 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 -} diff --git a/x/cdp/keeper/auctions.go b/x/cdp/keeper/auctions.go deleted file mode 100644 index 14df5b1f..00000000 --- a/x/cdp/keeper/auctions.go +++ /dev/null @@ -1,171 +0,0 @@ -package keeper - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/cdp/types" -) - -const ( - // factor for setting the initial value of gov tokens to sell at debt auctions -- assuming stable token is ~1 usd, this starts the auction with a price of $0.01 KAVA - dump = 100 -) - -// 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 sdkmath.Int, bidDenom string) error { - auctionSize := k.getAuctionSize(ctx, collateralType) - totalCollateral := deposits.SumCollateral() - for _, deposit := range deposits { - debtCoveredByDeposit := (sdk.NewDecFromInt(deposit.Amount.Amount).Quo(sdk.NewDecFromInt(totalCollateral))).Mul(sdk.NewDecFromInt(debt)).RoundInt() - if err := k.CreateAuctionsFromDeposit(ctx, deposit.Amount, collateralType, deposit.Depositor, debtCoveredByDeposit, auctionSize, bidDenom); err != nil { - return err - } - } - return nil -} - -// CreateAuctionsFromDeposit creates auctions from the input deposit -func (k Keeper) CreateAuctionsFromDeposit( - ctx sdk.Context, collateral sdk.Coin, collateralType string, returnAddr sdk.AccAddress, debt, auctionSize sdkmath.Int, - principalDenom string, -) error { - // number of auctions of auctionSize - numberOfAuctions := collateral.Amount.Quo(auctionSize) - debtPerAuction := debt.Mul(auctionSize).Quo(collateral.Amount) - - // last auction for remaining collateral (collateral < auctionSize) - lastAuctionCollateral := collateral.Amount.Mod(auctionSize) - lastAuctionDebt := debt.Mul(lastAuctionCollateral).Quo(collateral.Amount) - - // amount of debt that has not been allocated due to - // rounding error (unallocated debt is less than numberOfAuctions + 1) - unallocatedDebt := debt.Sub(numberOfAuctions.Mul(debtPerAuction).Add(lastAuctionDebt)) - - // rounding error for whole and last auctions in units of collateral - // higher value means a larger truncation - wholeAuctionError := debt.Mul(auctionSize).Mod(collateral.Amount) - lastAuctionError := debt.Mul(lastAuctionCollateral).Mod(collateral.Amount) - - // if last auction has larger rounding error, then allocate one debt to last auction first - // follows the largest remainder method https://en.wikipedia.org/wiki/Largest_remainder_method - if lastAuctionError.GT(wholeAuctionError) { - lastAuctionDebt = lastAuctionDebt.Add(sdk.OneInt()) - unallocatedDebt = unallocatedDebt.Sub(sdk.OneInt()) - } - - debtDenom := k.GetDebtDenom(ctx) - numAuctions := numberOfAuctions.Int64() - - // create whole auctions - for i := int64(0); i < numAuctions; i++ { - debtAmount := debtPerAuction - - // distribute unallocated debt left over starting with first auction created - if unallocatedDebt.IsPositive() { - debtAmount = debtAmount.Add(sdk.OneInt()) - unallocatedDebt = unallocatedDebt.Sub(sdk.OneInt()) - } - - penalty := k.ApplyLiquidationPenalty(ctx, collateralType, debtAmount) - - _, err := k.auctionKeeper.StartCollateralAuction( - ctx, types.LiquidatorMacc, sdk.NewCoin(collateral.Denom, auctionSize), - sdk.NewCoin(principalDenom, debtAmount.Add(penalty)), []sdk.AccAddress{returnAddr}, - []sdkmath.Int{auctionSize}, sdk.NewCoin(debtDenom, debtAmount), - ) - if err != nil { - return err - } - } - - // skip last auction if there is no collateral left to auction - if !lastAuctionCollateral.IsPositive() { - return nil - } - - // if the last auction had a larger rounding error than whole auctions, - // then unallocatedDebt will be zero since we will have already distributed - // all of the unallocated debt - if unallocatedDebt.IsPositive() { - lastAuctionDebt = lastAuctionDebt.Add(sdk.OneInt()) - unallocatedDebt = unallocatedDebt.Sub(sdk.OneInt()) - } - - penalty := k.ApplyLiquidationPenalty(ctx, collateralType, lastAuctionDebt) - - _, err := k.auctionKeeper.StartCollateralAuction( - ctx, types.LiquidatorMacc, sdk.NewCoin(collateral.Denom, lastAuctionCollateral), - sdk.NewCoin(principalDenom, lastAuctionDebt.Add(penalty)), []sdk.AccAddress{returnAddr}, - []sdkmath.Int{lastAuctionCollateral}, sdk.NewCoin(debtDenom, lastAuctionDebt), - ) - - return err -} - -// NetSurplusAndDebt burns surplus and debt coins equal to the minimum of surplus and debt balances held by the liquidator module account -// for example, if there is 1000 debt and 100 surplus, 100 surplus and 100 debt are burned, netting to 900 debt -func (k Keeper) NetSurplusAndDebt(ctx sdk.Context) error { - totalSurplus := k.GetTotalSurplus(ctx, types.LiquidatorMacc) - debt := k.GetTotalDebt(ctx, types.LiquidatorMacc) - netAmount := sdk.MinInt(totalSurplus, debt) - if netAmount.IsZero() { - return nil - } - - // burn debt coins equal to netAmount - err := k.bankKeeper.BurnCoins(ctx, types.LiquidatorMacc, sdk.NewCoins(sdk.NewCoin(k.GetDebtDenom(ctx), netAmount))) - if err != nil { - return err - } - - // burn stable coins equal to min(balance, netAmount) - dp := k.GetParams(ctx).DebtParam - liquidatorAcc := k.accountKeeper.GetModuleAccount(ctx, types.LiquidatorMacc) - balance := k.bankKeeper.GetBalance(ctx, liquidatorAcc.GetAddress(), dp.Denom).Amount - burnAmount := sdk.MinInt(balance, netAmount) - return k.bankKeeper.BurnCoins(ctx, types.LiquidatorMacc, sdk.NewCoins(sdk.NewCoin(dp.Denom, burnAmount))) -} - -// GetTotalSurplus returns the total amount of surplus tokens held by the liquidator module account -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) sdkmath.Int { - acc := k.accountKeeper.GetModuleAccount(ctx, accountName) - return k.bankKeeper.GetBalance(ctx, acc.GetAddress(), k.GetDebtDenom(ctx)).Amount -} - -// RunSurplusAndDebtAuctions nets the surplus and debt balances and then creates surplus or debt auctions if the remaining balance is above the auction threshold parameter -func (k Keeper) RunSurplusAndDebtAuctions(ctx sdk.Context) error { - if err := k.NetSurplusAndDebt(ctx); err != nil { - return err - } - remainingDebt := k.GetTotalDebt(ctx, types.LiquidatorMacc) - params := k.GetParams(ctx) - - 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(sdkmath.NewInt(dump))) - - _, err := k.auctionKeeper.StartDebtAuction(ctx, types.LiquidatorMacc, bidCoin, initialLot, debtLot) - if err != nil { - return err - } - } - - liquidatorAcc := k.accountKeeper.GetModuleAccount(ctx, types.LiquidatorMacc) - surplus := k.bankKeeper.GetBalance(ctx, liquidatorAcc.GetAddress(), params.DebtParam.Denom).Amount - if !surplus.GTE(params.SurplusAuctionThreshold) { - return nil - } - - surplusLot := sdk.NewCoin(params.DebtParam.Denom, sdk.MinInt(params.SurplusAuctionLot, surplus)) - _, err := k.auctionKeeper.StartSurplusAuction(ctx, types.LiquidatorMacc, surplusLot, k.GetGovDenom(ctx)) - return err -} diff --git a/x/cdp/keeper/auctions_test.go b/x/cdp/keeper/auctions_test.go deleted file mode 100644 index b28fcdf2..00000000 --- a/x/cdp/keeper/auctions_test.go +++ /dev/null @@ -1,168 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/app" - auctiontypes "github.com/0glabs/0g-chain/x/auction/types" - "github.com/0glabs/0g-chain/x/cdp/keeper" - "github.com/0glabs/0g-chain/x/cdp/types" - - "github.com/stretchr/testify/suite" - - "github.com/cometbft/cometbft/crypto" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" -) - -type AuctionTestSuite struct { - suite.Suite - - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context - addrs []sdk.AccAddress -} - -func (suite *AuctionTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - tApp := app.NewTestApp() - taddr := sdk.AccAddress(crypto.AddressHash([]byte("KavaTestUser1"))) - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), cs(c("usdx", 21000000000)), []sdk.AccAddress{taddr}) - tApp.InitializeFromGenesisStates( - authGS, - NewPricefeedGenStateMulti(tApp.AppCodec()), - NewCDPGenStateMulti(tApp.AppCodec()), - ) - keeper := tApp.GetCDPKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - suite.addrs = []sdk.AccAddress{taddr} -} - -func (suite *AuctionTestSuite) TestNetDebtSurplus() { - bk := suite.app.GetBankKeeper() - ak := suite.app.GetAccountKeeper() - - err := bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("debt", 100))) - suite.NoError(err) - err = bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("usdx", 10))) - suite.NoError(err) - suite.NotPanics(func() { - err := suite.keeper.NetSurplusAndDebt(suite.ctx) - suite.NoError(err) - }) - acc := ak.GetModuleAccount(suite.ctx, types.LiquidatorMacc) - suite.Equal(cs(c("debt", 90)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) -} - -func (suite *AuctionTestSuite) TestCollateralAuction() { - bk := suite.app.GetBankKeeper() - err := bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("debt", 21000000000), c("bnb", 190000000000))) - suite.Require().NoError(err) - testDeposit := types.NewDeposit(1, suite.addrs[0], c("bnb", 190000000000)) - err = suite.keeper.AuctionCollateral(suite.ctx, types.Deposits{testDeposit}, "bnb-a", i(21000000000), "usdx") - suite.Require().NoError(err) -} - -func (suite *AuctionTestSuite) TestSurplusAuction() { - bk := suite.app.GetBankKeeper() - ak := suite.app.GetAccountKeeper() - - err := bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("usdx", 600000000000))) - suite.NoError(err) - err = bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("debt", 100000000000))) - suite.NoError(err) - err = suite.keeper.RunSurplusAndDebtAuctions(suite.ctx) - suite.NoError(err) - acc := ak.GetModuleAccount(suite.ctx, auctiontypes.ModuleName) - suite.Equal(cs(c("usdx", 10000000000)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) - acc = ak.GetModuleAccount(suite.ctx, types.LiquidatorMacc) - suite.Equal(cs(c("usdx", 490000000000)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) -} - -func (suite *AuctionTestSuite) TestDebtAuction() { - bk := suite.app.GetBankKeeper() - ak := suite.app.GetAccountKeeper() - - err := bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("usdx", 100000000000))) - suite.NoError(err) - err = bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("debt", 200000000000))) - suite.NoError(err) - err = suite.keeper.RunSurplusAndDebtAuctions(suite.ctx) - suite.NoError(err) - acc := ak.GetModuleAccount(suite.ctx, auctiontypes.ModuleName) - suite.Equal(cs(c("debt", 10000000000)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) - acc = ak.GetModuleAccount(suite.ctx, types.LiquidatorMacc) - suite.Equal(cs(c("debt", 90000000000)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) -} - -func (suite *AuctionTestSuite) TestGetTotalSurplus() { - bk := suite.app.GetBankKeeper() - - // liquidator account has zero coins - 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))) - suite.Require().NoError(err) - err = bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("usdx", 200e6))) - suite.Require().NoError(err) - - // liquidator account has 300e6 total usdx - 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(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(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(sdkmath.NewInt(0), suite.keeper.GetTotalSurplus(suite.ctx, types.LiquidatorMacc)) - - // mint some debt - err := bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("debt", 100e6))) - suite.Require().NoError(err) - err = bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("debt", 200e6))) - suite.Require().NoError(err) - - // liquidator account has 300e6 total debt - 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(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(sdkmath.NewInt(250e6), suite.keeper.GetTotalDebt(suite.ctx, types.LiquidatorMacc)) -} - -func TestAuctionTestSuite(t *testing.T) { - suite.Run(t, new(AuctionTestSuite)) -} diff --git a/x/cdp/keeper/cdp.go b/x/cdp/keeper/cdp.go deleted file mode 100644 index 3d131d23..00000000 --- a/x/cdp/keeper/cdp.go +++ /dev/null @@ -1,667 +0,0 @@ -package keeper - -import ( - "fmt" - "sort" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/cdp/types" -) - -// AddCdp adds a cdp for a specific owner and collateral type -func (k Keeper) AddCdp(ctx sdk.Context, owner sdk.AccAddress, collateral sdk.Coin, principal sdk.Coin, collateralType string) error { - // validation - err := k.ValidateCollateral(ctx, collateral, collateralType) - if err != nil { - return err - } - err = k.ValidateBalance(ctx, collateral, owner) - if err != nil { - return err - } - _, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType) - if found { - return errorsmod.Wrapf(types.ErrCdpAlreadyExists, "owner %s, denom %s", owner, collateral.Denom) - } - err = k.ValidatePrincipalAdd(ctx, principal) - if err != nil { - return err - } - - err = k.ValidateDebtLimit(ctx, collateralType, principal) - if err != nil { - return err - } - err = k.ValidateCollateralizationRatio(ctx, collateral, collateralType, principal, sdk.NewCoin(principal.Denom, sdk.ZeroInt())) - if err != nil { - return err - } - - // send coins from the owners account to the cdp module - id := k.GetNextCdpID(ctx) - interestFactor, found := k.GetInterestFactor(ctx, collateralType) - if !found { - interestFactor = sdk.OneDec() - k.SetInterestFactor(ctx, collateralType, interestFactor) - - } - cdp := types.NewCDP(id, owner, collateral, collateralType, principal, ctx.BlockHeader().Time, interestFactor) - deposit := types.NewDeposit(cdp.ID, owner, collateral) - err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, owner, types.ModuleName, sdk.NewCoins(collateral)) - if err != nil { - return err - } - - // mint the principal and send to the owners account - err = k.bankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(principal)) - if err != nil { - panic(err) - } - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, owner, sdk.NewCoins(principal)) - if err != nil { - panic(err) - } - - // mint the corresponding amount of debt coins - err = k.MintDebtCoins(ctx, types.ModuleName, k.GetDebtDenom(ctx), principal) - if err != nil { - panic(err) - } - - // update total principal for input collateral type - k.IncrementTotalPrincipal(ctx, collateralType, principal) - - // set the cdp, deposit, and indexes in the store - collateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, collateral, cdp.Type, principal) - err = k.SetCdpAndCollateralRatioIndex(ctx, cdp, collateralToDebtRatio) - if err != nil { - return err - } - k.IndexCdpByOwner(ctx, cdp) - k.SetDeposit(ctx, deposit) - k.SetNextCdpID(ctx, id+1) - - k.hooks.AfterCDPCreated(ctx, cdp) - - // emit events for cdp creation, deposit, and draw - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCreateCdp, - sdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf("%d", cdp.ID)), - ), - ) - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCdpDeposit, - sdk.NewAttribute(sdk.AttributeKeyAmount, collateral.String()), - sdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf("%d", cdp.ID)), - ), - ) - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCdpDraw, - sdk.NewAttribute(sdk.AttributeKeyAmount, principal.String()), - sdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf("%d", cdp.ID)), - ), - ) - - return nil -} - -// UpdateCdpAndCollateralRatioIndex updates the state of an existing cdp in the store by replacing the old index values and updating the store to the latest cdp object values -func (k Keeper) UpdateCdpAndCollateralRatioIndex(ctx sdk.Context, cdp types.CDP, ratio sdk.Dec) error { - err := k.removeOldCollateralRatioIndex(ctx, cdp.Type, cdp.ID) - if err != nil { - return err - } - - err = k.SetCDP(ctx, cdp) - if err != nil { - return err - } - k.IndexCdpByCollateralRatio(ctx, cdp.Type, cdp.ID, ratio) - return nil -} - -// DeleteCdpAndCollateralRatioIndex deletes an existing cdp in the store by removing the old index value and deleting the cdp object from the store -func (k Keeper) DeleteCdpAndCollateralRatioIndex(ctx sdk.Context, cdp types.CDP) error { - err := k.removeOldCollateralRatioIndex(ctx, cdp.Type, cdp.ID) - if err != nil { - return err - } - - return k.DeleteCDP(ctx, cdp) -} - -// SetCdpAndCollateralRatioIndex sets the cdp and collateral ratio index in the store -func (k Keeper) SetCdpAndCollateralRatioIndex(ctx sdk.Context, cdp types.CDP, ratio sdk.Dec) error { - err := k.SetCDP(ctx, cdp) - if err != nil { - return err - } - k.IndexCdpByCollateralRatio(ctx, cdp.Type, cdp.ID, ratio) - return nil -} - -func (k Keeper) removeOldCollateralRatioIndex(ctx sdk.Context, ctype string, id uint64) error { - storedCDP, found := k.GetCDP(ctx, ctype, id) - if !found { - 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) - return nil -} - -// MintDebtCoins mints debt coins in the cdp module account -func (k Keeper) MintDebtCoins(ctx sdk.Context, moduleAccount string, denom string, principalCoins sdk.Coin) error { - debtCoins := sdk.NewCoins(sdk.NewCoin(denom, principalCoins.Amount)) - return k.bankKeeper.MintCoins(ctx, moduleAccount, debtCoins) -} - -// BurnDebtCoins burns debt coins from the cdp module account -func (k Keeper) BurnDebtCoins(ctx sdk.Context, moduleAccount string, denom string, paymentCoins sdk.Coin) error { - macc := k.accountKeeper.GetModuleAccount(ctx, moduleAccount) - maxBurnableAmount := k.bankKeeper.GetBalance(ctx, macc.GetAddress(), denom).Amount - // check that the requested burn is not greater than the mod account balance - debtCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.MinInt(paymentCoins.Amount, maxBurnableAmount))) - return k.bankKeeper.BurnCoins(ctx, moduleAccount, debtCoins) -} - -// GetCdpID returns the id of the cdp corresponding to a specific owner and collateral denom -func (k Keeper) GetCdpID(ctx sdk.Context, owner sdk.AccAddress, collateralType string) (uint64, bool) { - cdpIDs, found := k.GetCdpIdsByOwner(ctx, owner) - if !found { - return 0, false - } - for _, id := range cdpIDs { - _, found = k.GetCDP(ctx, collateralType, id) - if found { - return id, true - } - } - return 0, false -} - -// GetCdpIdsByOwner returns all the ids of cdps corresponding to a particular owner -func (k Keeper) GetCdpIdsByOwner(ctx sdk.Context, owner sdk.AccAddress) ([]uint64, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.CdpIDKeyPrefix) - bz := store.Get(owner) - if bz == nil { - return []uint64{}, false - } - - var index types.OwnerCDPIndex - k.cdc.MustUnmarshal(bz, &index) - return index.CdpIDs, true -} - -// GetCdpByOwnerAndCollateralType queries cdps owned by owner and returns the cdp with matching denom -func (k Keeper) GetCdpByOwnerAndCollateralType(ctx sdk.Context, owner sdk.AccAddress, collateralType string) (types.CDP, bool) { - cdpIDs, found := k.GetCdpIdsByOwner(ctx, owner) - if !found { - return types.CDP{}, false - } - for _, id := range cdpIDs { - cdp, found := k.GetCDP(ctx, collateralType, id) - if found { - return cdp, true - } - } - return types.CDP{}, false -} - -// GetCDP returns the cdp associated with a particular collateral denom and id -func (k Keeper) GetCDP(ctx sdk.Context, collateralType string, cdpID uint64) (types.CDP, bool) { - // get store - store := prefix.NewStore(ctx.KVStore(k.key), types.CdpKeyPrefix) - _, found := k.GetCollateral(ctx, collateralType) - if !found { - return types.CDP{}, false - } - // get CDP - bz := store.Get(types.CdpKey(collateralType, cdpID)) - // unmarshal - if bz == nil { - return types.CDP{}, false - } - var cdp types.CDP - k.cdc.MustUnmarshal(bz, &cdp) - return cdp, true -} - -// SetCDP sets a cdp in the store -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 errorsmod.Wrapf(types.ErrDenomPrefixNotFound, "%s", cdp.Collateral.Denom) - } - bz := k.cdc.MustMarshal(&cdp) - store.Set(types.CdpKey(cdp.Type, cdp.ID), bz) - return nil -} - -// DeleteCDP deletes a cdp from the store -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 errorsmod.Wrapf(types.ErrDenomPrefixNotFound, "%s", cdp.Collateral.Denom) - } - store.Delete(types.CdpKey(cdp.Type, cdp.ID)) - return nil -} - -// GetAllCdps returns all cdps from the store -func (k Keeper) GetAllCdps(ctx sdk.Context) (cdps types.CDPs) { - k.IterateAllCdps(ctx, func(cdp types.CDP) bool { - cdps = append(cdps, cdp) - return false - }) - return -} - -// GetAllCdpsByCollateralType returns all cdps of a particular collateral type from the store -func (k Keeper) GetAllCdpsByCollateralType(ctx sdk.Context, collateralType string) (cdps types.CDPs) { - k.IterateCdpsByCollateralType(ctx, collateralType, func(cdp types.CDP) bool { - cdps = append(cdps, cdp) - return false - }) - return -} - -// GetAllCdpsByCollateralTypeAndRatio returns all cdps of a particular collateral type and below a certain collateralization ratio -func (k Keeper) GetAllCdpsByCollateralTypeAndRatio(ctx sdk.Context, collateralType string, targetRatio sdk.Dec) (cdps types.CDPs) { - k.IterateCdpsByCollateralRatio(ctx, collateralType, targetRatio, func(cdp types.CDP) bool { - cdps = append(cdps, cdp) - return false - }) - return -} - -// SetNextCdpID sets the highest cdp id in the store -func (k Keeper) SetNextCdpID(ctx sdk.Context, id uint64) { - store := prefix.NewStore(ctx.KVStore(k.key), types.CdpIDKey) - store.Set(types.CdpIDKey, types.GetCdpIDBytes(id)) -} - -// GetNextCdpID returns the highest cdp id from the store -func (k Keeper) GetNextCdpID(ctx sdk.Context) (id uint64) { - store := prefix.NewStore(ctx.KVStore(k.key), types.CdpIDKey) - bz := store.Get(types.CdpIDKey) - if bz == nil { - panic("starting cdp id not set in genesis") - } - id = types.GetCdpIDFromBytes(bz) - return -} - -// IndexCdpByOwner sets the cdp id in the store, indexed by the owner -func (k Keeper) IndexCdpByOwner(ctx sdk.Context, cdp types.CDP) { - store := prefix.NewStore(ctx.KVStore(k.key), types.CdpIDKeyPrefix) - - cdpIDs, found := k.GetCdpIdsByOwner(ctx, cdp.Owner) - - if found { - cdpIDs = append(cdpIDs, cdp.ID) - sort.Slice(cdpIDs, func(i, j int) bool { return cdpIDs[i] < cdpIDs[j] }) - } else { - cdpIDs = []uint64{cdp.ID} - } - - newIndex := types.OwnerCDPIndex{CdpIDs: cdpIDs} - store.Set(cdp.Owner, k.cdc.MustMarshal(&newIndex)) -} - -// RemoveCdpOwnerIndex deletes the cdp id from the store's index of cdps by owner -func (k Keeper) RemoveCdpOwnerIndex(ctx sdk.Context, cdp types.CDP) { - store := prefix.NewStore(ctx.KVStore(k.key), types.CdpIDKeyPrefix) - - cdpIDs, found := k.GetCdpIdsByOwner(ctx, cdp.Owner) - if !found { - return - } - updatedCdpIds := []uint64{} - for _, id := range cdpIDs { - if id != cdp.ID { - updatedCdpIds = append(updatedCdpIds, id) - } - } - if len(updatedCdpIds) == 0 { - store.Delete(cdp.Owner) - return - } - - updatedIndex := types.OwnerCDPIndex{CdpIDs: updatedCdpIds} - updatedBytes := k.cdc.MustMarshal(&updatedIndex) - store.Set(cdp.Owner, updatedBytes) -} - -// IndexCdpByCollateralRatio sets the cdp id in the store, indexed by the collateral type and collateral to debt ratio -func (k Keeper) IndexCdpByCollateralRatio(ctx sdk.Context, collateralType string, id uint64, collateralRatio sdk.Dec) { - store := prefix.NewStore(ctx.KVStore(k.key), types.CollateralRatioIndexPrefix) - _, found := k.GetCollateral(ctx, collateralType) - if !found { - panic(fmt.Sprintf("denom %s prefix not found", collateralType)) - } - store.Set(types.CollateralRatioKey(collateralType, id, collateralRatio), types.GetCdpIDBytes(id)) -} - -// RemoveCdpCollateralRatioIndex deletes the cdp id from the store's index of cdps by collateral type and collateral to debt ratio -func (k Keeper) RemoveCdpCollateralRatioIndex(ctx sdk.Context, collateralType string, id uint64, collateralRatio sdk.Dec) { - store := prefix.NewStore(ctx.KVStore(k.key), types.CollateralRatioIndexPrefix) - _, found := k.GetCollateral(ctx, collateralType) - if !found { - panic(fmt.Sprintf("denom %s prefix not found", collateralType)) - } - store.Delete(types.CollateralRatioKey(collateralType, id, collateralRatio)) -} - -// GetDebtDenom returns the denom of debt in the system -func (k Keeper) GetDebtDenom(ctx sdk.Context) string { - store := prefix.NewStore(ctx.KVStore(k.key), types.DebtDenomKey) - bz := store.Get(types.DebtDenomKey) - return string(bz) -} - -// GetGovDenom returns the denom of the governance token -func (k Keeper) GetGovDenom(ctx sdk.Context) string { - store := prefix.NewStore(ctx.KVStore(k.key), types.GovDenomKey) - bz := store.Get(types.GovDenomKey) - return string(bz) -} - -// SetDebtDenom set the denom of debt in the system -func (k Keeper) SetDebtDenom(ctx sdk.Context, denom string) { - if denom == "" { - panic("debt denom not set in genesis") - } - store := prefix.NewStore(ctx.KVStore(k.key), types.DebtDenomKey) - store.Set(types.DebtDenomKey, []byte(denom)) -} - -// SetGovDenom set the denom of the governance token in the system -func (k Keeper) SetGovDenom(ctx sdk.Context, denom string) { - if denom == "" { - panic("gov denom not set in genesis") - } - store := prefix.NewStore(ctx.KVStore(k.key), types.GovDenomKey) - store.Set(types.GovDenomKey, []byte(denom)) -} - -// ValidateCollateral validates that a collateral is valid for use in cdps -func (k Keeper) ValidateCollateral(ctx sdk.Context, collateral sdk.Coin, collateralType string) error { - cp, found := k.GetCollateral(ctx, collateralType) - if !found { - return errorsmod.Wrap(types.ErrCollateralNotSupported, collateral.Denom) - } - if 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 errorsmod.Wrap(types.ErrPricefeedDown, collateral.Denom) - } - ok = k.GetMarketStatus(ctx, cp.LiquidationMarketID) - if !ok { - return errorsmod.Wrap(types.ErrPricefeedDown, collateral.Denom) - } - return nil -} - -// ValidatePrincipalAdd validates that an asset is valid for use as debt when creating a new cdp -func (k Keeper) ValidatePrincipalAdd(ctx sdk.Context, principal sdk.Coin) error { - dp, found := k.GetDebtParam(ctx, principal.Denom) - if !found { - return errorsmod.Wrap(types.ErrDebtNotSupported, principal.Denom) - } - if principal.Amount.LT(dp.DebtFloor) { - return errorsmod.Wrapf(types.ErrBelowDebtFloor, "proposed %s < minimum %s", principal, dp.DebtFloor) - } - return nil -} - -// 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 errorsmod.Wrapf(types.ErrInvalidDebtRequest, "proposed %s, expected %s", principal.Denom, expectedDenom) - } - _, found := k.GetDebtParam(ctx, principal.Denom) - if !found { - return errorsmod.Wrap(types.ErrDebtNotSupported, principal.Denom) - } - return nil -} - -// ValidateDebtLimit validates that the input debt amount does not exceed the global debt limit or the debt limit for that collateral -func (k Keeper) ValidateDebtLimit(ctx sdk.Context, collateralType string, principal sdk.Coin) error { - cp, found := k.GetCollateral(ctx, collateralType) - if !found { - 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 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 errorsmod.Wrapf(types.ErrExceedsDebtLimit, "debt increase %s > global debt limit %s", sdk.NewCoin(principal.Denom, totalPrincipal), sdk.NewCoin(principal.Denom, globalLimit)) - } - return nil -} - -// ValidateCollateralizationRatio validate that adding the input principal doesn't put the cdp below the liquidation ratio -func (k Keeper) ValidateCollateralizationRatio(ctx sdk.Context, collateral sdk.Coin, collateralType string, principal sdk.Coin, fees sdk.Coin) error { - collateralizationRatio, err := k.CalculateCollateralizationRatio(ctx, collateral, collateralType, principal, fees, spot) - if err != nil { - return err - } - liquidationRatio := k.getLiquidationRatio(ctx, collateralType) - if collateralizationRatio.LT(liquidationRatio) { - return errorsmod.Wrapf(types.ErrInvalidCollateralRatio, "collateral %s, collateral ratio %s, liquidation ratio %s", collateral.Denom, collateralizationRatio, liquidationRatio) - } - return nil -} - -// ValidateBalance validates that the input account has sufficient spendable funds -func (k Keeper) ValidateBalance(ctx sdk.Context, amount sdk.Coin, sender sdk.AccAddress) error { - acc := k.accountKeeper.GetAccount(ctx, sender) - if acc == nil { - return errorsmod.Wrapf(types.ErrAccountNotFound, "address: %s", sender) - } - spendableBalance := k.bankKeeper.SpendableCoins(ctx, acc.GetAddress()).AmountOf(amount.Denom) - if spendableBalance.LT(amount.Amount) { - return errorsmod.Wrapf(types.ErrInsufficientBalance, "%s < %s", sdk.NewCoin(amount.Denom, spendableBalance), amount) - } - - return nil -} - -// CalculateCollateralToDebtRatio returns the collateral to debt ratio of the input collateral and debt amounts -func (k Keeper) CalculateCollateralToDebtRatio(ctx sdk.Context, collateral sdk.Coin, collateralType string, debt sdk.Coin) sdk.Dec { - debtTotal := k.convertDebtToBaseUnits(ctx, debt) - - if debtTotal.IsZero() || debtTotal.GTE(types.MaxSortableDec) { - return types.MaxSortableDec.Sub(sdk.SmallestDec()) - } - - collateralBaseUnits := k.convertCollateralToBaseUnits(ctx, collateral, collateralType) - return collateralBaseUnits.Quo(debtTotal) -} - -// LoadAugmentedCDP creates a new augmented CDP from an existing CDP -func (k Keeper) LoadAugmentedCDP(ctx sdk.Context, cdp types.CDP) types.AugmentedCDP { - // sync the latest interest of the cdp - interestAccumulated := k.CalculateNewInterest(ctx, cdp) - cdp.AccumulatedFees = cdp.AccumulatedFees.Add(interestAccumulated) - // update cdp fields to match synced accumulated fees - prevAccrualTime, found := k.GetPreviousAccrualTime(ctx, cdp.Type) - if found { - cdp.FeesUpdated = prevAccrualTime - } - globalInterestFactor, found := k.GetInterestFactor(ctx, cdp.Type) - if found { - cdp.InterestFactor = globalInterestFactor - } - // calculate collateralization ratio - collateralizationRatio, err := k.CalculateCollateralizationRatio(ctx, cdp.Collateral, cdp.Type, cdp.Principal, cdp.AccumulatedFees, liquidation) - if err != nil { - return types.AugmentedCDP{CDP: cdp} - } - // convert collateral value to debt coin - totalDebt := cdp.GetTotalPrincipal().Amount - collateralValueInDebtDenom := sdk.NewDecFromInt(totalDebt).Mul(collateralizationRatio) - collateralValueInDebt := sdk.NewCoin(cdp.Principal.Denom, collateralValueInDebtDenom.RoundInt()) - // create new augmuented cdp - augmentedCDP := types.NewAugmentedCDP(cdp, collateralValueInDebt, collateralizationRatio) - return augmentedCDP -} - -// LoadCDPResponse creates a new CDPResponse from an existing CDP -func (k Keeper) LoadCDPResponse(ctx sdk.Context, cdp types.CDP) types.CDPResponse { - // sync the latest interest of the cdp - interestAccumulated := k.CalculateNewInterest(ctx, cdp) - cdp.AccumulatedFees = cdp.AccumulatedFees.Add(interestAccumulated) - // update cdp fields to match synced accumulated fees - prevAccrualTime, found := k.GetPreviousAccrualTime(ctx, cdp.Type) - if found { - cdp.FeesUpdated = prevAccrualTime - } - globalInterestFactor, found := k.GetInterestFactor(ctx, cdp.Type) - if found { - cdp.InterestFactor = globalInterestFactor - } - // calculate collateralization ratio - collateralizationRatio, err := k.CalculateCollateralizationRatio(ctx, cdp.Collateral, cdp.Type, cdp.Principal, cdp.AccumulatedFees, liquidation) - if err != nil { - return types.CDPResponse{ - ID: cdp.ID, - Owner: cdp.Owner.String(), - Type: cdp.Type, - Collateral: cdp.Collateral, - Principal: cdp.Principal, - AccumulatedFees: cdp.AccumulatedFees, - FeesUpdated: cdp.FeesUpdated, - InterestFactor: cdp.InterestFactor.String(), - } - } - // convert collateral value to debt coin - totalDebt := cdp.GetTotalPrincipal().Amount - collateralValueInDebtDenom := sdk.NewDecFromInt(totalDebt).Mul(collateralizationRatio) - collateralValueInDebt := sdk.NewCoin(cdp.Principal.Denom, collateralValueInDebtDenom.RoundInt()) - // create new cdp response - return types.NewCDPResponse(cdp, collateralValueInDebt, collateralizationRatio) -} - -// CalculateCollateralizationRatio returns the collateralization ratio of the input collateral to the input debt plus fees -func (k Keeper) CalculateCollateralizationRatio(ctx sdk.Context, collateral sdk.Coin, collateralType string, principal sdk.Coin, fees sdk.Coin, pfType pricefeedType) (sdk.Dec, error) { - if collateral.IsZero() { - return sdk.ZeroDec(), nil - } - var marketID string - switch pfType { - case spot: - marketID = k.getSpotMarketID(ctx, collateralType) - case liquidation: - marketID = k.getliquidationMarketID(ctx, collateralType) - default: - return sdk.Dec{}, pfType.IsValid() - } - - price, err := k.pricefeedKeeper.GetCurrentPrice(ctx, marketID) - if err != nil { - return sdk.Dec{}, err - } - collateralBaseUnits := k.convertCollateralToBaseUnits(ctx, collateral, collateralType) - collateralValue := collateralBaseUnits.Mul(price.Price) - - prinicpalBaseUnits := k.convertDebtToBaseUnits(ctx, principal) - principalTotal := prinicpalBaseUnits - feeBaseUnits := k.convertDebtToBaseUnits(ctx, fees) - principalTotal = principalTotal.Add(feeBaseUnits) - - collateralRatio := collateralValue.Quo(principalTotal) - return collateralRatio, nil -} - -// CalculateCollateralizationRatioFromAbsoluteRatio takes a coin's denom and an absolute ratio and returns the respective collateralization ratio -func (k Keeper) CalculateCollateralizationRatioFromAbsoluteRatio(ctx sdk.Context, collateralType string, absoluteRatio sdk.Dec, pfType pricefeedType) (sdk.Dec, error) { - // get price of collateral - var marketID string - switch pfType { - case spot: - marketID = k.getSpotMarketID(ctx, collateralType) - case liquidation: - marketID = k.getliquidationMarketID(ctx, collateralType) - default: - return sdk.Dec{}, pfType.IsValid() - } - - price, err := k.pricefeedKeeper.GetCurrentPrice(ctx, marketID) - if err != nil { - return sdk.Dec{}, err - } - // convert absolute ratio to collateralization ratio - respectiveCollateralRatio := absoluteRatio.Quo(price.Price) - return respectiveCollateralRatio, nil -} - -// SetMarketStatus sets the status of the input market, true means the market is up and running, false means it is down -func (k Keeper) SetMarketStatus(ctx sdk.Context, marketID string, up bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PricefeedStatusKeyPrefix) - if up { - store.Set([]byte(marketID), []byte{}) - } else { - store.Delete([]byte(marketID)) - } -} - -// GetMarketStatus returns true if the market has a price, otherwise false -func (k Keeper) GetMarketStatus(ctx sdk.Context, marketID string) bool { - store := prefix.NewStore(ctx.KVStore(k.key), types.PricefeedStatusKeyPrefix) - bz := store.Get([]byte(marketID)) - return bz != nil -} - -// UpdatePricefeedStatus determines if the price of an asset is available and updates the global status of the market -func (k Keeper) UpdatePricefeedStatus(ctx sdk.Context, marketID string) (ok bool) { - _, err := k.pricefeedKeeper.GetCurrentPrice(ctx, marketID) - if err != nil { - k.SetMarketStatus(ctx, marketID, false) - return false - } - k.SetMarketStatus(ctx, marketID, true) - return true -} - -// converts the input collateral to base units (ie multiplies the input by 10^(-ConversionFactor)) -func (k Keeper) convertCollateralToBaseUnits(ctx sdk.Context, collateral sdk.Coin, collateralType string) (baseUnits sdk.Dec) { - cp, _ := k.GetCollateral(ctx, collateralType) - return sdk.NewDecFromInt(collateral.Amount).Mul(sdk.NewDecFromIntWithPrec(sdk.OneInt(), cp.ConversionFactor.Int64())) -} - -// converts the input debt to base units (ie multiplies the input by 10^(-ConversionFactor)) -func (k Keeper) convertDebtToBaseUnits(ctx sdk.Context, debt sdk.Coin) (baseUnits sdk.Dec) { - dp, _ := k.GetDebtParam(ctx, debt.Denom) - return sdk.NewDecFromInt(debt.Amount).Mul(sdk.NewDecFromIntWithPrec(sdk.OneInt(), dp.ConversionFactor.Int64())) -} - -type pricefeedType string - -const ( - spot pricefeedType = "spot" - liquidation pricefeedType = "liquidation" -) - -func (pft pricefeedType) IsValid() error { - switch pft { - case spot, liquidation: - return nil - } - return fmt.Errorf("invalid pricefeed type: %s", pft) -} diff --git a/x/cdp/keeper/cdp_test.go b/x/cdp/keeper/cdp_test.go deleted file mode 100644 index 51d90409..00000000 --- a/x/cdp/keeper/cdp_test.go +++ /dev/null @@ -1,396 +0,0 @@ -package keeper_test - -import ( - "errors" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/cdp/keeper" - "github.com/0glabs/0g-chain/x/cdp/types" -) - -type CdpTestSuite struct { - suite.Suite - - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context -} - -func (suite *CdpTestSuite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - tApp.InitializeFromGenesisStates( - NewPricefeedGenStateMulti(tApp.AppCodec()), - NewCDPGenStateMulti(tApp.AppCodec()), - ) - keeper := tApp.GetCDPKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper -} - -func (suite *CdpTestSuite) TestAddCdp() { - _, addrs := app.GeneratePrivKeyAddressPairs(2) - ak := suite.app.GetAccountKeeper() - acc := ak.NewAccountWithAddress(suite.ctx, addrs[0]) - err := suite.app.FundAccount(suite.ctx, acc.GetAddress(), cs(c("xrp", 200000000), c("btc", 500000000))) - suite.Require().NoError(err) - - ak.SetAccount(suite.ctx, acc) - err = suite.keeper.AddCdp(suite.ctx, addrs[0], c("xrp", 200000000), c("usdx", 10000000), "btc-a") - suite.Require().True(errors.Is(err, types.ErrInvalidCollateral)) - err = suite.keeper.AddCdp(suite.ctx, addrs[0], c("xrp", 200000000), c("usdx", 26000000), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrInvalidCollateralRatio)) - err = suite.keeper.AddCdp(suite.ctx, addrs[0], c("xrp", 500000000), c("usdx", 26000000), "xrp-a") - suite.Error(err) // insufficient balance - err = suite.keeper.AddCdp(suite.ctx, addrs[0], c("xrp", 200000000), c("xusd", 10000000), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrDebtNotSupported)) - - acc2 := ak.NewAccountWithAddress(suite.ctx, addrs[1]) - err = suite.app.FundAccount(suite.ctx, acc2.GetAddress(), cs(c("btc", 500000000000))) - suite.Require().NoError(err) - - ak.SetAccount(suite.ctx, acc2) - err = suite.keeper.AddCdp(suite.ctx, addrs[1], c("btc", 500000000000), c("usdx", 500000000001), "btc-a") - suite.Require().True(errors.Is(err, types.ErrExceedsDebtLimit)) - - ctx := suite.ctx.WithBlockTime(suite.ctx.BlockTime().Add(time.Hour * 2)) - pk := suite.app.GetPriceFeedKeeper() - err = pk.SetCurrentPrices(ctx, "xrp:usd") - suite.Error(err) - ok := suite.keeper.UpdatePricefeedStatus(ctx, "xrp:usd") - suite.False(ok) - err = suite.keeper.AddCdp(ctx, addrs[0], c("xrp", 100000000), c("usdx", 10000000), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrPricefeedDown)) - - err = pk.SetCurrentPrices(suite.ctx, "xrp:usd") - ok = suite.keeper.UpdatePricefeedStatus(suite.ctx, "xrp:usd") - suite.True(ok) - suite.NoError(err) - err = suite.keeper.AddCdp(suite.ctx, addrs[0], c("xrp", 100000000), c("usdx", 10000000), "xrp-a") - suite.NoError(err) - id := suite.keeper.GetNextCdpID(suite.ctx) - suite.Equal(uint64(2), id) - tp := suite.keeper.GetTotalPrincipal(suite.ctx, "xrp-a", "usdx") - suite.Equal(i(10000000), tp) - - bk := suite.app.GetBankKeeper() - - macc := ak.GetModuleAccount(suite.ctx, types.ModuleName) - suite.Equal(cs(c("debt", 10000000), c("xrp", 100000000)), bk.GetAllBalances(suite.ctx, macc.GetAddress())) - acc = ak.GetAccount(suite.ctx, addrs[0]) - suite.Equal(cs(c("usdx", 10000000), c("xrp", 100000000), c("btc", 500000000)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) - - err = suite.keeper.AddCdp(suite.ctx, addrs[0], c("btc", 500000000), c("usdx", 26667000000), "btc-a") - suite.Require().True(errors.Is(err, types.ErrInvalidCollateralRatio)) - - err = suite.keeper.AddCdp(suite.ctx, addrs[0], c("btc", 500000000), c("usdx", 100000000), "btc-a") - suite.NoError(err) - id = suite.keeper.GetNextCdpID(suite.ctx) - suite.Equal(uint64(3), id) - tp = suite.keeper.GetTotalPrincipal(suite.ctx, "btc-a", "usdx") - suite.Equal(i(100000000), tp) - macc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - suite.Equal(cs(c("debt", 110000000), c("xrp", 100000000), c("btc", 500000000)), bk.GetAllBalances(suite.ctx, macc.GetAddress())) - acc = ak.GetAccount(suite.ctx, addrs[0]) - suite.Equal(cs(c("usdx", 110000000), c("xrp", 100000000)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) - - err = suite.keeper.AddCdp(suite.ctx, addrs[0], c("lol", 100), c("usdx", 10), "lol-a") - suite.Require().True(errors.Is(err, types.ErrCollateralNotSupported)) - err = suite.keeper.AddCdp(suite.ctx, addrs[0], c("xrp", 100), c("usdx", 10), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrCdpAlreadyExists)) -} - -func (suite *CdpTestSuite) TestGetCollateral() { - _, found := suite.keeper.GetCollateral(suite.ctx, "lol-a") - suite.False(found) - _, found = suite.keeper.GetCollateral(suite.ctx, "xrp-a") - suite.True(found) -} - -func (suite *CdpTestSuite) TestGetDebtDenom() { - suite.Panics(func() { suite.keeper.SetDebtDenom(suite.ctx, "") }) - t := suite.keeper.GetDebtDenom(suite.ctx) - suite.Equal("debt", t) - suite.keeper.SetDebtDenom(suite.ctx, "lol") - t = suite.keeper.GetDebtDenom(suite.ctx) - suite.Equal("lol", t) -} - -func (suite *CdpTestSuite) TestGetNextCdpID() { - id := suite.keeper.GetNextCdpID(suite.ctx) - suite.Equal(types.DefaultCdpStartingID, id) -} - -func (suite *CdpTestSuite) TestGetSetCdp() { - _, addrs := app.GeneratePrivKeyAddressPairs(1) - cdp := types.NewCDP(types.DefaultCdpStartingID, addrs[0], c("xrp", 1), "xrp-a", c("usdx", 1), tmtime.Canonical(time.Now()), sdk.OneDec()) - err := suite.keeper.SetCDP(suite.ctx, cdp) - suite.NoError(err) - - t, found := suite.keeper.GetCDP(suite.ctx, "xrp-a", types.DefaultCdpStartingID) - suite.True(found) - suite.Equal(cdp, t) - _, found = suite.keeper.GetCDP(suite.ctx, "xrp-a", uint64(2)) - suite.False(found) - suite.NoError(suite.keeper.DeleteCDP(suite.ctx, cdp)) - _, found = suite.keeper.GetCDP(suite.ctx, "btc-a", types.DefaultCdpStartingID) - suite.False(found) -} - -func (suite *CdpTestSuite) TestGetSetCdpId() { - _, addrs := app.GeneratePrivKeyAddressPairs(2) - cdp := types.NewCDP(types.DefaultCdpStartingID, addrs[0], c("xrp", 1), "xrp-a", c("usdx", 1), tmtime.Canonical(time.Now()), sdk.OneDec()) - err := suite.keeper.SetCDP(suite.ctx, cdp) - suite.NoError(err) - suite.keeper.IndexCdpByOwner(suite.ctx, cdp) - id, found := suite.keeper.GetCdpID(suite.ctx, addrs[0], "xrp-a") - suite.True(found) - suite.Equal(types.DefaultCdpStartingID, id) - _, found = suite.keeper.GetCdpID(suite.ctx, addrs[0], "lol-a") - suite.False(found) - _, found = suite.keeper.GetCdpID(suite.ctx, addrs[1], "xrp-a") - suite.False(found) -} - -func (suite *CdpTestSuite) TestGetSetCdpByOwnerAndCollateralType() { - _, addrs := app.GeneratePrivKeyAddressPairs(2) - cdp := types.NewCDP(types.DefaultCdpStartingID, addrs[0], c("xrp", 1), "xrp-a", c("usdx", 1), tmtime.Canonical(time.Now()), sdk.OneDec()) - err := suite.keeper.SetCDP(suite.ctx, cdp) - suite.NoError(err) - suite.keeper.IndexCdpByOwner(suite.ctx, cdp) - t, found := suite.keeper.GetCdpByOwnerAndCollateralType(suite.ctx, addrs[0], "xrp-a") - suite.True(found) - suite.Equal(cdp, t) - _, found = suite.keeper.GetCdpByOwnerAndCollateralType(suite.ctx, addrs[0], "lol-a") - suite.False(found) - _, found = suite.keeper.GetCdpByOwnerAndCollateralType(suite.ctx, addrs[1], "xrp-a") - suite.False(found) - suite.NotPanics(func() { suite.keeper.IndexCdpByOwner(suite.ctx, cdp) }) -} - -func (suite *CdpTestSuite) TestCalculateCollateralToDebtRatio() { - _, addrs := app.GeneratePrivKeyAddressPairs(1) - cdp := types.NewCDP(types.DefaultCdpStartingID, addrs[0], c("xrp", 3), "xrp-a", c("usdx", 1), tmtime.Canonical(time.Now()), sdk.OneDec()) - cr := suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, cdp.Collateral, cdp.Type, cdp.Principal) - suite.Equal(sdk.MustNewDecFromStr("3.0"), cr) - cdp = types.NewCDP(types.DefaultCdpStartingID, addrs[0], c("xrp", 1), "xrp-a", c("usdx", 2), tmtime.Canonical(time.Now()), sdk.OneDec()) - cr = suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, cdp.Collateral, cdp.Type, cdp.Principal) - suite.Equal(sdk.MustNewDecFromStr("0.5"), cr) -} - -func (suite *CdpTestSuite) TestSetCdpByCollateralRatio() { - _, addrs := app.GeneratePrivKeyAddressPairs(1) - cdp := types.NewCDP(types.DefaultCdpStartingID, addrs[0], c("xrp", 3), "xrp-a", c("usdx", 1), tmtime.Canonical(time.Now()), sdk.OneDec()) - cr := suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, cdp.Collateral, cdp.Type, cdp.Principal) - suite.NotPanics(func() { suite.keeper.IndexCdpByCollateralRatio(suite.ctx, cdp.Type, cdp.ID, cr) }) -} - -func (suite *CdpTestSuite) TestIterateCdps() { - cdps := cdps() - for _, c := range cdps { - err := suite.keeper.SetCDP(suite.ctx, c) - suite.NoError(err) - suite.keeper.IndexCdpByOwner(suite.ctx, c) - cr := suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, c.Collateral, c.Type, c.Principal) - suite.keeper.IndexCdpByCollateralRatio(suite.ctx, c.Type, c.ID, cr) - } - t := suite.keeper.GetAllCdps(suite.ctx) - suite.Equal(4, len(t)) -} - -func (suite *CdpTestSuite) TestIterateCdpsByCollateralType() { - cdps := cdps() - for _, c := range cdps { - err := suite.keeper.SetCDP(suite.ctx, c) - suite.NoError(err) - suite.keeper.IndexCdpByOwner(suite.ctx, c) - cr := suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, c.Collateral, c.Type, c.Principal) - suite.keeper.IndexCdpByCollateralRatio(suite.ctx, c.Type, c.ID, cr) - } - xrpCdps := suite.keeper.GetAllCdpsByCollateralType(suite.ctx, "xrp-a") - suite.Equal(3, len(xrpCdps)) - btcCdps := suite.keeper.GetAllCdpsByCollateralType(suite.ctx, "btc-a") - suite.Equal(1, len(btcCdps)) - suite.NoError(suite.keeper.DeleteCDP(suite.ctx, cdps[0])) - suite.keeper.RemoveCdpOwnerIndex(suite.ctx, cdps[0]) - xrpCdps = suite.keeper.GetAllCdpsByCollateralType(suite.ctx, "xrp-a") - suite.Equal(2, len(xrpCdps)) - suite.NoError(suite.keeper.DeleteCDP(suite.ctx, cdps[1])) - suite.keeper.RemoveCdpOwnerIndex(suite.ctx, cdps[1]) - ids, found := suite.keeper.GetCdpIdsByOwner(suite.ctx, cdps[1].Owner) - suite.True(found) - suite.Equal(1, len(ids)) - suite.Equal(uint64(3), ids[0]) -} - -func (suite *CdpTestSuite) TestIterateCdpsByCollateralRatio() { - cdps := cdps() - for _, c := range cdps { - err := suite.keeper.SetCDP(suite.ctx, c) - suite.NoError(err) - suite.keeper.IndexCdpByOwner(suite.ctx, c) - cr := suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, c.Collateral, c.Type, c.Principal) - suite.keeper.IndexCdpByCollateralRatio(suite.ctx, c.Type, c.ID, cr) - } - xrpCdps := suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", d("1.25")) - suite.Equal(0, len(xrpCdps)) - xrpCdps = suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", d("1.25").Add(sdk.SmallestDec())) - suite.Equal(1, len(xrpCdps)) - xrpCdps = suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", d("2.0").Add(sdk.SmallestDec())) - suite.Equal(2, len(xrpCdps)) - xrpCdps = suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", d("100.0").Add(sdk.SmallestDec())) - suite.Equal(3, len(xrpCdps)) - - suite.NoError(suite.keeper.DeleteCDP(suite.ctx, cdps[0])) - - suite.keeper.RemoveCdpOwnerIndex(suite.ctx, cdps[0]) - cr := suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, cdps[0].Collateral, cdps[0].Type, cdps[0].Principal) - suite.keeper.RemoveCdpCollateralRatioIndex(suite.ctx, cdps[0].Type, cdps[0].ID, cr) - xrpCdps = suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", d("2.0").Add(sdk.SmallestDec())) - suite.Equal(1, len(xrpCdps)) -} - -func (suite *CdpTestSuite) TestValidateCollateral() { - c := sdk.NewCoin("xrp", sdkmath.NewInt(1)) - err := suite.keeper.ValidateCollateral(suite.ctx, c, "xrp-a") - suite.NoError(err) - 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", sdkmath.NewInt(10000000)) - err := suite.keeper.ValidatePrincipalAdd(suite.ctx, d) - suite.NoError(err) - 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", sdkmath.NewInt(1000000000001)) - err = suite.keeper.ValidateDebtLimit(suite.ctx, "xrp-a", d) - suite.Require().True(errors.Is(err, types.ErrExceedsDebtLimit)) - d = sdk.NewCoin("usdx", sdkmath.NewInt(100000000)) - err = suite.keeper.ValidateDebtLimit(suite.ctx, "xrp-a", d) - suite.NoError(err) -} - -func (suite *CdpTestSuite) TestCalculateCollateralizationRatio() { - c := cdps()[1] - err := suite.keeper.SetCDP(suite.ctx, c) - suite.NoError(err) - suite.keeper.IndexCdpByOwner(suite.ctx, c) - cr := suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, c.Collateral, c.Type, c.Principal) - suite.keeper.IndexCdpByCollateralRatio(suite.ctx, c.Type, c.ID, cr) - cr, err = suite.keeper.CalculateCollateralizationRatio(suite.ctx, c.Collateral, c.Type, c.Principal, c.AccumulatedFees, "spot") - suite.NoError(err) - suite.Equal(d("2.5"), cr) - c.AccumulatedFees = sdk.NewCoin("usdx", i(10000000)) - cr, err = suite.keeper.CalculateCollateralizationRatio(suite.ctx, c.Collateral, c.Type, c.Principal, c.AccumulatedFees, "spot") - suite.NoError(err) - suite.Equal(d("1.25"), cr) -} - -func (suite *CdpTestSuite) TestMintBurnDebtCoins() { - cd := cdps()[1] - err := suite.keeper.MintDebtCoins(suite.ctx, types.ModuleName, suite.keeper.GetDebtDenom(suite.ctx), cd.Principal) - suite.NoError(err) - suite.Require().Panics(func() { - _ = suite.keeper.MintDebtCoins(suite.ctx, "notamodule", suite.keeper.GetDebtDenom(suite.ctx), cd.Principal) - }) - - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - acc := ak.GetModuleAccount(suite.ctx, types.ModuleName) - suite.Equal(cs(c("debt", 10000000)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) - - err = suite.keeper.BurnDebtCoins(suite.ctx, types.ModuleName, suite.keeper.GetDebtDenom(suite.ctx), cd.Principal) - suite.NoError(err) - suite.Require().Panics(func() { - _ = suite.keeper.BurnDebtCoins(suite.ctx, "notamodule", suite.keeper.GetDebtDenom(suite.ctx), cd.Principal) - }) - - acc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - suite.Equal(sdk.Coins{}, bk.GetAllBalances(suite.ctx, acc.GetAddress())) -} - -func (suite *CdpTestSuite) TestCdpOwnerIndex() { - cdps := cdps() - - owner_1 := cdps[0].Owner - owner_2 := cdps[1].Owner - - cdpIds_1, found := suite.keeper.GetCdpIdsByOwner(suite.ctx, owner_1) - suite.Require().False(found) - cdpIds_2, found := suite.keeper.GetCdpIdsByOwner(suite.ctx, owner_2) - suite.Require().False(found) - - suite.Require().Equal(0, len(cdpIds_1)) - suite.Require().Equal(0, len(cdpIds_2)) - - suite.keeper.IndexCdpByOwner(suite.ctx, cdps[2]) - suite.keeper.IndexCdpByOwner(suite.ctx, cdps[1]) - suite.keeper.IndexCdpByOwner(suite.ctx, cdps[0]) - - expectedCdpIds, found := suite.keeper.GetCdpIdsByOwner(suite.ctx, owner_1) - suite.Require().True(found) - suite.Require().Equal([]uint64{cdps[0].ID}, expectedCdpIds) - - expectedCdpIds, found = suite.keeper.GetCdpIdsByOwner(suite.ctx, owner_2) - suite.Require().True(found) - suite.Require().Equal([]uint64{cdps[1].ID, cdps[2].ID}, expectedCdpIds) - - suite.keeper.RemoveCdpOwnerIndex(suite.ctx, cdps[0]) - expectedCdpIds, found = suite.keeper.GetCdpIdsByOwner(suite.ctx, owner_1) - suite.Require().False(found) - suite.Require().Equal([]uint64{}, expectedCdpIds) - - suite.keeper.RemoveCdpOwnerIndex(suite.ctx, cdps[1]) - expectedCdpIds, found = suite.keeper.GetCdpIdsByOwner(suite.ctx, owner_2) - suite.Require().True(found) - suite.Require().Equal([]uint64{cdps[2].ID}, expectedCdpIds) - - suite.keeper.RemoveCdpOwnerIndex(suite.ctx, cdps[2]) - expectedCdpIds, found = suite.keeper.GetCdpIdsByOwner(suite.ctx, owner_2) - suite.Require().False(found) - suite.Require().Equal([]uint64{}, expectedCdpIds) -} - -func (suite *CdpTestSuite) TestMarketStatus() { - suite.keeper.SetMarketStatus(suite.ctx, "ukava:usd", true) - status := suite.keeper.GetMarketStatus(suite.ctx, "ukava:usd") - suite.Require().True(status) - suite.keeper.SetMarketStatus(suite.ctx, "ukava:usd", false) - status = suite.keeper.GetMarketStatus(suite.ctx, "ukava:usd") - suite.Require().False(status) - suite.keeper.SetMarketStatus(suite.ctx, "ukava:usd", true) - status = suite.keeper.GetMarketStatus(suite.ctx, "ukava:usd") - suite.Require().True(status) - - status = suite.keeper.GetMarketStatus(suite.ctx, "unknown:usd") - suite.Require().False(status) - - suite.keeper.SetMarketStatus(suite.ctx, "btc:usd", false) - status = suite.keeper.GetMarketStatus(suite.ctx, "btc:usd") - suite.Require().False(status) - suite.keeper.SetMarketStatus(suite.ctx, "btc:usd", true) - status = suite.keeper.GetMarketStatus(suite.ctx, "btc:usd") - suite.Require().True(status) - suite.keeper.SetMarketStatus(suite.ctx, "btc:usd", false) - status = suite.keeper.GetMarketStatus(suite.ctx, "btc:usd") - suite.Require().False(status) -} - -func TestCdpTestSuite(t *testing.T) { - suite.Run(t, new(CdpTestSuite)) -} diff --git a/x/cdp/keeper/deposit.go b/x/cdp/keeper/deposit.go deleted file mode 100644 index 6c4978cf..00000000 --- a/x/cdp/keeper/deposit.go +++ /dev/null @@ -1,166 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/cdp/types" -) - -// DepositCollateral adds collateral to a cdp -func (k Keeper) DepositCollateral(ctx sdk.Context, owner, depositor sdk.AccAddress, collateral sdk.Coin, collateralType string) error { - // check that collateral exists and has a functioning pricefeed - err := k.ValidateCollateral(ctx, collateral, collateralType) - if err != nil { - return err - } - cdp, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType) - if !found { - return errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, collateral %s", owner, collateralType) - } - err = k.ValidateBalance(ctx, collateral, depositor) - if err != nil { - return err - } - k.hooks.BeforeCDPModified(ctx, cdp) - cdp = k.SynchronizeInterest(ctx, cdp) - - deposit, found := k.GetDeposit(ctx, cdp.ID, depositor) - if found { - deposit.Amount = deposit.Amount.Add(collateral) - } else { - deposit = types.NewDeposit(cdp.ID, depositor, collateral) - } - err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, depositor, types.ModuleName, sdk.NewCoins(collateral)) - if err != nil { - return err - } - - k.SetDeposit(ctx, deposit) - - cdp.Collateral = cdp.Collateral.Add(collateral) - collateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Type, cdp.GetTotalPrincipal()) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCdpDeposit, - sdk.NewAttribute(sdk.AttributeKeyAmount, collateral.String()), - sdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf("%d", cdp.ID)), - ), - ) - - return k.UpdateCdpAndCollateralRatioIndex(ctx, cdp, collateralToDebtRatio) -} - -// WithdrawCollateral removes collateral from a cdp if it does not put the cdp below the liquidation ratio -func (k Keeper) WithdrawCollateral(ctx sdk.Context, owner, depositor sdk.AccAddress, collateral sdk.Coin, collateralType string) error { - err := k.ValidateCollateral(ctx, collateral, collateralType) - if err != nil { - return err - } - cdp, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType) - if !found { - return errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, collateral %s", owner, collateral.Denom) - } - deposit, found := k.GetDeposit(ctx, cdp.ID, depositor) - if !found { - return errorsmod.Wrapf(types.ErrDepositNotFound, "depositor %s, collateral %s %s", depositor, collateral.Denom, collateralType) - } - if collateral.Amount.GT(deposit.Amount.Amount) { - return errorsmod.Wrapf(types.ErrInvalidWithdrawAmount, "collateral %s, deposit %s", collateral, deposit.Amount) - } - k.hooks.BeforeCDPModified(ctx, cdp) - cdp = k.SynchronizeInterest(ctx, cdp) - - collateralizationRatio, err := k.CalculateCollateralizationRatio(ctx, cdp.Collateral.Sub(collateral), cdp.Type, cdp.Principal, cdp.AccumulatedFees, spot) - if err != nil { - return err - } - liquidationRatio := k.getLiquidationRatio(ctx, cdp.Type) - if collateralizationRatio.LT(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)) - if err != nil { - panic(err) - } - - cdp.Collateral = cdp.Collateral.Sub(collateral) - collateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Type, cdp.GetTotalPrincipal()) - err = k.UpdateCdpAndCollateralRatioIndex(ctx, cdp, collateralToDebtRatio) - if err != nil { - return err - } - - deposit.Amount = deposit.Amount.Sub(collateral) - // delete deposits if amount is 0 - if deposit.Amount.IsZero() { - k.DeleteDeposit(ctx, deposit.CdpID, deposit.Depositor) - } else { - k.SetDeposit(ctx, deposit) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCdpWithdrawal, - sdk.NewAttribute(sdk.AttributeKeyAmount, collateral.String()), - sdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf("%d", cdp.ID)), - ), - ) - - return nil -} - -// GetDeposit returns the deposit of a depositor on a particular cdp from the store -func (k Keeper) GetDeposit(ctx sdk.Context, cdpID uint64, depositor sdk.AccAddress) (deposit types.Deposit, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositKeyPrefix) - bz := store.Get(types.DepositKey(cdpID, depositor)) - if bz == nil { - return deposit, false - } - k.cdc.MustUnmarshal(bz, &deposit) - return deposit, true -} - -// SetDeposit sets the deposit in the store -func (k Keeper) SetDeposit(ctx sdk.Context, deposit types.Deposit) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositKeyPrefix) - bz := k.cdc.MustMarshal(&deposit) - - store.Set(types.DepositKey(deposit.CdpID, deposit.Depositor), bz) -} - -// DeleteDeposit deletes a deposit from the store -func (k Keeper) DeleteDeposit(ctx sdk.Context, cdpID uint64, depositor sdk.AccAddress) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositKeyPrefix) - store.Delete(types.DepositKey(cdpID, depositor)) -} - -// IterateDeposits iterates over the all the deposits of a cdp and performs a callback function -func (k Keeper) IterateDeposits(ctx sdk.Context, cdpID uint64, cb func(deposit types.Deposit) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, types.GetCdpIDBytes(cdpID)) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var deposit types.Deposit - k.cdc.MustUnmarshal(iterator.Value(), &deposit) - - if cb(deposit) { - break - } - } -} - -// GetDeposits returns all the deposits to a cdp -func (k Keeper) GetDeposits(ctx sdk.Context, cdpID uint64) (deposits types.Deposits) { - k.IterateDeposits(ctx, cdpID, func(deposit types.Deposit) bool { - deposits = append(deposits, deposit) - return false - }) - return -} diff --git a/x/cdp/keeper/deposit_test.go b/x/cdp/keeper/deposit_test.go deleted file mode 100644 index c4cbb696..00000000 --- a/x/cdp/keeper/deposit_test.go +++ /dev/null @@ -1,139 +0,0 @@ -package keeper_test - -import ( - "errors" - "testing" - - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/cdp/keeper" - "github.com/0glabs/0g-chain/x/cdp/types" -) - -type DepositTestSuite struct { - suite.Suite - - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context - addrs []sdk.AccAddress -} - -func (suite *DepositTestSuite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - cdc := tApp.AppCodec() - - _, addrs := app.GeneratePrivKeyAddressPairs(10) - authGS := app.NewFundedGenStateWithCoins( - cdc, - []sdk.Coins{ - cs(c("xrp", 500000000), c("btc", 500000000)), - cs(c("xrp", 200000000)), - }, - addrs[0:2], - ) - tApp.InitializeFromGenesisStates( - authGS, - NewPricefeedGenStateMulti(cdc), - NewCDPGenStateMulti(cdc), - ) - keeper := tApp.GetCDPKeeper() - suite.app = tApp - suite.keeper = keeper - suite.ctx = ctx - suite.addrs = addrs - err := suite.keeper.AddCdp(suite.ctx, addrs[0], c("xrp", 400000000), c("usdx", 10000000), "xrp-a") - suite.NoError(err) -} - -func (suite *DepositTestSuite) TestGetSetDeposit() { - d, found := suite.keeper.GetDeposit(suite.ctx, uint64(1), suite.addrs[0]) - suite.True(found) - td := types.NewDeposit(uint64(1), suite.addrs[0], c("xrp", 400000000)) - suite.True(d.Equals(td)) - ds := suite.keeper.GetDeposits(suite.ctx, uint64(1)) - suite.Equal(1, len(ds)) - suite.True(ds[0].Equals(td)) - suite.keeper.DeleteDeposit(suite.ctx, uint64(1), suite.addrs[0]) - _, found = suite.keeper.GetDeposit(suite.ctx, uint64(1), suite.addrs[0]) - suite.False(found) - ds = suite.keeper.GetDeposits(suite.ctx, uint64(1)) - suite.Equal(0, len(ds)) -} - -func (suite *DepositTestSuite) TestDepositCollateral() { - err := suite.keeper.DepositCollateral(suite.ctx, suite.addrs[0], suite.addrs[0], c("xrp", 10000000), "xrp-a") - suite.NoError(err) - d, found := suite.keeper.GetDeposit(suite.ctx, uint64(1), suite.addrs[0]) - suite.True(found) - td := types.NewDeposit(uint64(1), suite.addrs[0], c("xrp", 410000000)) - suite.True(d.Equals(td)) - ds := suite.keeper.GetDeposits(suite.ctx, uint64(1)) - suite.Equal(1, len(ds)) - suite.True(ds[0].Equals(td)) - cd, _ := suite.keeper.GetCDP(suite.ctx, "xrp-a", uint64(1)) - suite.Equal(c("xrp", 410000000), cd.Collateral) - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - - acc := ak.GetAccount(suite.ctx, suite.addrs[0]) - suite.Equal(i(90000000), bk.GetBalance(suite.ctx, acc.GetAddress(), "xrp").Amount) - - err = suite.keeper.DepositCollateral(suite.ctx, suite.addrs[0], suite.addrs[0], c("btc", 1), "btc-a") - suite.Require().True(errors.Is(err, types.ErrCdpNotFound)) - - err = suite.keeper.DepositCollateral(suite.ctx, suite.addrs[1], suite.addrs[0], c("xrp", 1), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrCdpNotFound)) - - err = suite.keeper.DepositCollateral(suite.ctx, suite.addrs[0], suite.addrs[1], c("xrp", 10000000), "xrp-a") - suite.NoError(err) - d, found = suite.keeper.GetDeposit(suite.ctx, uint64(1), suite.addrs[1]) - suite.True(found) - td = types.NewDeposit(uint64(1), suite.addrs[1], c("xrp", 10000000)) - suite.True(d.Equals(td)) - ds = suite.keeper.GetDeposits(suite.ctx, uint64(1)) - suite.Equal(2, len(ds)) - suite.True(ds[1].Equals(td)) -} - -func (suite *DepositTestSuite) TestWithdrawCollateral() { - err := suite.keeper.WithdrawCollateral(suite.ctx, suite.addrs[0], suite.addrs[0], c("xrp", 400000000), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrInvalidCollateralRatio)) - err = suite.keeper.WithdrawCollateral(suite.ctx, suite.addrs[0], suite.addrs[0], c("xrp", 321000000), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrInvalidCollateralRatio)) - err = suite.keeper.WithdrawCollateral(suite.ctx, suite.addrs[1], suite.addrs[0], c("xrp", 10000000), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrCdpNotFound)) - - cd, _ := suite.keeper.GetCDP(suite.ctx, "xrp-a", uint64(1)) - cd.AccumulatedFees = c("usdx", 1) - err = suite.keeper.SetCDP(suite.ctx, cd) - suite.NoError(err) - err = suite.keeper.WithdrawCollateral(suite.ctx, suite.addrs[0], suite.addrs[0], c("xrp", 320000000), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrInvalidCollateralRatio)) - - err = suite.keeper.WithdrawCollateral(suite.ctx, suite.addrs[0], suite.addrs[0], c("xrp", 10000000), "xrp-a") - suite.NoError(err) - dep, _ := suite.keeper.GetDeposit(suite.ctx, uint64(1), suite.addrs[0]) - td := types.NewDeposit(uint64(1), suite.addrs[0], c("xrp", 390000000)) - suite.True(dep.Equals(td)) - - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - - acc := ak.GetAccount(suite.ctx, suite.addrs[0]) - suite.Equal(i(110000000), bk.GetBalance(suite.ctx, acc.GetAddress(), "xrp").Amount) - - err = suite.keeper.WithdrawCollateral(suite.ctx, suite.addrs[0], suite.addrs[1], c("xrp", 10000000), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrDepositNotFound)) -} - -func TestDepositTestSuite(t *testing.T) { - suite.Run(t, new(DepositTestSuite)) -} diff --git a/x/cdp/keeper/draw.go b/x/cdp/keeper/draw.go deleted file mode 100644 index 626b8a45..00000000 --- a/x/cdp/keeper/draw.go +++ /dev/null @@ -1,243 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/cdp/types" -) - -// AddPrincipal adds debt to a cdp if the additional debt does not put the cdp below the liquidation ratio -func (k Keeper) AddPrincipal(ctx sdk.Context, owner sdk.AccAddress, collateralType string, principal sdk.Coin) error { - // validation - cdp, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType) - if !found { - return errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", owner, collateralType) - } - err := k.ValidatePrincipalDraw(ctx, principal, cdp.Principal.Denom) - if err != nil { - return err - } - - err = k.ValidateDebtLimit(ctx, cdp.Type, principal) - if err != nil { - return err - } - k.hooks.BeforeCDPModified(ctx, cdp) - cdp = k.SynchronizeInterest(ctx, cdp) - - err = k.ValidateCollateralizationRatio(ctx, cdp.Collateral, cdp.Type, cdp.Principal.Add(principal), cdp.AccumulatedFees) - if err != nil { - return err - } - - // mint the principal and send it to the cdp owner - err = k.bankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(principal)) - if err != nil { - panic(err) - } - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, owner, sdk.NewCoins(principal)) - if err != nil { - panic(err) - } - - // mint the corresponding amount of debt coins in the cdp module account - err = k.MintDebtCoins(ctx, types.ModuleName, k.GetDebtDenom(ctx), principal) - if err != nil { - panic(err) - } - - // emit cdp draw event - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCdpDraw, - sdk.NewAttribute(sdk.AttributeKeyAmount, principal.String()), - sdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf("%d", cdp.ID)), - ), - ) - - // update cdp state - cdp.Principal = cdp.Principal.Add(principal) - - // increment total principal for the input collateral type - k.IncrementTotalPrincipal(ctx, cdp.Type, principal) - - // set cdp state and indexes in the store - collateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Type, cdp.GetTotalPrincipal()) - return k.UpdateCdpAndCollateralRatioIndex(ctx, cdp, collateralToDebtRatio) -} - -// RepayPrincipal removes debt from the cdp -// If all debt is repaid, the collateral is returned to depositors and the cdp is removed from the store -func (k Keeper) RepayPrincipal(ctx sdk.Context, owner sdk.AccAddress, collateralType string, payment sdk.Coin) error { - // validation - cdp, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType) - if !found { - return errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", owner, collateralType) - } - - err := k.ValidatePaymentCoins(ctx, cdp, payment) - if err != nil { - return err - } - - err = k.ValidateBalance(ctx, payment, owner) - if err != nil { - return err - } - k.hooks.BeforeCDPModified(ctx, cdp) - cdp = k.SynchronizeInterest(ctx, cdp) - - // Note: assumes cdp.Principal and cdp.AccumulatedFees don't change during calculations - totalPrincipal := cdp.GetTotalPrincipal() - - // calculate fee and principal payment - feePayment, principalPayment := k.calculatePayment(ctx, totalPrincipal, cdp.AccumulatedFees, payment) - - err = k.validatePrincipalPayment(ctx, cdp, principalPayment) - if err != nil { - return err - } - // send the payment from the sender to the cpd module - err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, owner, types.ModuleName, sdk.NewCoins(feePayment.Add(principalPayment))) - if err != nil { - return err - } - - // burn the payment coins - err = k.bankKeeper.BurnCoins(ctx, types.ModuleName, sdk.NewCoins(feePayment.Add(principalPayment))) - if err != nil { - panic(err) - } - - // burn the corresponding amount of debt coins - cdpDebt := k.getModAccountDebt(ctx, types.ModuleName) - paymentAmount := feePayment.Add(principalPayment).Amount - - debtDenom := k.GetDebtDenom(ctx) - coinsToBurn := sdk.NewCoin(debtDenom, paymentAmount) - - if paymentAmount.GT(cdpDebt) { - coinsToBurn = sdk.NewCoin(debtDenom, cdpDebt) - } - - err = k.BurnDebtCoins(ctx, types.ModuleName, debtDenom, coinsToBurn) - - if err != nil { - panic(err) - } - - // emit repayment event - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCdpRepay, - sdk.NewAttribute(sdk.AttributeKeyAmount, feePayment.Add(principalPayment).String()), - sdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf("%d", cdp.ID)), - ), - ) - - // remove the old collateral:debt ratio index - - // update cdp state - if !principalPayment.IsZero() { - cdp.Principal = cdp.Principal.Sub(principalPayment) - } - cdp.AccumulatedFees = cdp.AccumulatedFees.Sub(feePayment) - - // decrement the total principal for the input collateral type - k.DecrementTotalPrincipal(ctx, cdp.Type, feePayment.Add(principalPayment)) - - // if the debt is fully paid, return collateral to depositors, - // and remove the cdp and indexes from the store - if cdp.Principal.IsZero() && cdp.AccumulatedFees.IsZero() { - k.ReturnCollateral(ctx, cdp) - k.RemoveCdpOwnerIndex(ctx, cdp) - err := k.DeleteCdpAndCollateralRatioIndex(ctx, cdp) - if err != nil { - return err - } - - // emit cdp close event - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCdpClose, - sdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf("%d", cdp.ID)), - ), - ) - return nil - } - - // set cdp state and update indexes - collateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Type, cdp.GetTotalPrincipal()) - return k.UpdateCdpAndCollateralRatioIndex(ctx, cdp, collateralToDebtRatio) -} - -// ValidatePaymentCoins validates that the input coins are valid for repaying debt -func (k Keeper) ValidatePaymentCoins(ctx sdk.Context, cdp types.CDP, payment sdk.Coin) error { - debt := cdp.GetTotalPrincipal() - if payment.Denom != debt.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 errorsmod.Wrapf(types.ErrInvalidPayment, "payment denom %s not found", payment.Denom) - } - return nil -} - -// ReturnCollateral returns collateral to depositors on a cdp and removes deposits from the store -func (k Keeper) ReturnCollateral(ctx sdk.Context, cdp types.CDP) { - deposits := k.GetDeposits(ctx, cdp.ID) - for _, deposit := range deposits { - if err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, deposit.Depositor, sdk.NewCoins(deposit.Amount)); err != nil { - panic(err) - } - k.DeleteDeposit(ctx, cdp.ID, deposit.Depositor) - } -} - -// calculatePayment divides the input payment into the portions that will be used to repay fees and principal -// owed - Principal + AccumulatedFees -// fees - AccumulatedFees -// CONTRACT: owned and payment denoms must be checked before calling this function. -func (k Keeper) calculatePayment(ctx sdk.Context, owed, fees, payment sdk.Coin) (sdk.Coin, sdk.Coin) { - // divides repayment into principal and fee components, with fee payment applied first. - - feePayment := sdk.NewCoin(payment.Denom, sdk.ZeroInt()) - principalPayment := sdk.NewCoin(payment.Denom, sdk.ZeroInt()) - var overpayment sdk.Coin - // return zero value coins if payment amount is invalid - if !payment.Amount.IsPositive() { - return feePayment, principalPayment - } - // check for over payment - if payment.Amount.GT(owed.Amount) { - overpayment = payment.Sub(owed) - payment = payment.Sub(overpayment) - } - // if no fees, 100% of payment is principal payment - if fees.IsZero() { - return feePayment, payment - } - // pay fees before repaying principal - if payment.Amount.GT(fees.Amount) { - feePayment = fees - principalPayment = payment.Sub(fees) - } else { - feePayment = payment - } - return feePayment, principalPayment -} - -// validatePrincipalPayment checks that the payment is either full or does not put the cdp below the debt floor -// CONTRACT: payment denom must be checked before calling this function. -func (k Keeper) validatePrincipalPayment(ctx sdk.Context, cdp types.CDP, payment sdk.Coin) error { - proposedBalance := cdp.Principal.Amount.Sub(payment.Amount) - dp, _ := k.GetDebtParam(ctx, payment.Denom) - if proposedBalance.GT(sdk.ZeroInt()) && proposedBalance.LT(dp.DebtFloor) { - return errorsmod.Wrapf(types.ErrBelowDebtFloor, "proposed %s < minimum %s", sdk.NewCoin(payment.Denom, proposedBalance), dp.DebtFloor) - } - return nil -} diff --git a/x/cdp/keeper/draw_test.go b/x/cdp/keeper/draw_test.go deleted file mode 100644 index e580e8ba..00000000 --- a/x/cdp/keeper/draw_test.go +++ /dev/null @@ -1,173 +0,0 @@ -package keeper_test - -import ( - "errors" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/cdp/keeper" - "github.com/0glabs/0g-chain/x/cdp/types" -) - -type DrawTestSuite struct { - suite.Suite - - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context - addrs []sdk.AccAddress -} - -func (suite *DrawTestSuite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - cdc := tApp.AppCodec() - _, addrs := app.GeneratePrivKeyAddressPairs(3) - coins := []sdk.Coins{ - cs(c("xrp", 500000000), c("btc", 500000000), c("usdx", 10000000000)), - cs(c("xrp", 200000000)), - cs(c("xrp", 10000000000000), c("usdx", 100000000000)), - } - - authGS := app.NewFundedGenStateWithCoins(cdc, coins, addrs) - tApp.InitializeFromGenesisStates( - authGS, - NewPricefeedGenStateMulti(cdc), - NewCDPGenStateMulti(cdc), - ) - keeper := tApp.GetCDPKeeper() - suite.app = tApp - suite.keeper = keeper - suite.ctx = ctx - suite.addrs = addrs - err := suite.keeper.AddCdp(suite.ctx, addrs[0], c("xrp", 400000000), c("usdx", 10000000), "xrp-a") - suite.NoError(err) -} - -func (suite *DrawTestSuite) TestAddRepayPrincipal() { - err := suite.keeper.AddPrincipal(suite.ctx, suite.addrs[0], "xrp-a", c("usdx", 10000000)) - suite.NoError(err) - - t, found := suite.keeper.GetCDP(suite.ctx, "xrp-a", uint64(1)) - suite.True(found) - suite.Equal(c("usdx", 20000000), t.Principal) - ctd := suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, t.Collateral, "xrp-a", t.Principal.Add(t.AccumulatedFees)) - suite.Equal(d("20.0"), ctd) - ts := suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", d("20.0")) - suite.Equal(0, len(ts)) - ts = suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", d("20.0").Add(sdk.SmallestDec())) - suite.Equal(ts[0], t) - tp := suite.keeper.GetTotalPrincipal(suite.ctx, "xrp-a", "usdx") - suite.Equal(i(20000000), tp) - - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - - acc := ak.GetModuleAccount(suite.ctx, types.ModuleName) - suite.Equal(cs(c("xrp", 400000000), c("debt", 20000000)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) - - err = suite.keeper.AddPrincipal(suite.ctx, suite.addrs[0], "xrp-a", c("susd", 10000000)) - suite.Require().True(errors.Is(err, types.ErrInvalidDebtRequest)) - - err = suite.keeper.AddPrincipal(suite.ctx, suite.addrs[1], "xrp-a", c("usdx", 10000000)) - suite.Require().True(errors.Is(err, types.ErrCdpNotFound)) - err = suite.keeper.AddPrincipal(suite.ctx, suite.addrs[0], "xrp-a", c("xusd", 10000000)) - suite.Require().True(errors.Is(err, types.ErrInvalidDebtRequest)) - err = suite.keeper.AddPrincipal(suite.ctx, suite.addrs[0], "xrp-a", c("usdx", 311000000)) - suite.Require().True(errors.Is(err, types.ErrInvalidCollateralRatio)) - - err = suite.keeper.RepayPrincipal(suite.ctx, suite.addrs[0], "xrp-a", c("usdx", 10000000)) - suite.NoError(err) - - t, found = suite.keeper.GetCDP(suite.ctx, "xrp-a", uint64(1)) - suite.True(found) - suite.Equal(c("usdx", 10000000), t.Principal) - - ctd = suite.keeper.CalculateCollateralToDebtRatio(suite.ctx, t.Collateral, "xrp-a", t.Principal.Add(t.AccumulatedFees)) - suite.Equal(d("40.0"), ctd) - ts = suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", d("40.0")) - suite.Equal(0, len(ts)) - ts = suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", d("40.0").Add(sdk.SmallestDec())) - suite.Equal(ts[0], t) - - ak = suite.app.GetAccountKeeper() - bk = suite.app.GetBankKeeper() - acc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - suite.Equal(cs(c("xrp", 400000000), c("debt", 10000000)), bk.GetAllBalances(suite.ctx, acc.GetAddress())) - - err = suite.keeper.RepayPrincipal(suite.ctx, suite.addrs[0], "xrp-a", c("xusd", 10000000)) - suite.Require().True(errors.Is(err, types.ErrInvalidPayment)) - err = suite.keeper.RepayPrincipal(suite.ctx, suite.addrs[1], "xrp-a", c("xusd", 10000000)) - suite.Require().True(errors.Is(err, types.ErrCdpNotFound)) - - err = suite.keeper.RepayPrincipal(suite.ctx, suite.addrs[0], "xrp-a", c("usdx", 9000000)) - suite.Require().True(errors.Is(err, types.ErrBelowDebtFloor)) - err = suite.keeper.RepayPrincipal(suite.ctx, suite.addrs[0], "xrp-a", c("usdx", 10000000)) - suite.NoError(err) - - _, found = suite.keeper.GetCDP(suite.ctx, "xrp-a", uint64(1)) - suite.False(found) - ts = suite.keeper.GetAllCdpsByCollateralTypeAndRatio(suite.ctx, "xrp-a", types.MaxSortableDec) - suite.Equal(0, len(ts)) - ts = suite.keeper.GetAllCdpsByCollateralType(suite.ctx, "xrp-a") - suite.Equal(0, len(ts)) - - ak = suite.app.GetAccountKeeper() - bk = suite.app.GetBankKeeper() - acc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - suite.Equal(sdk.Coins{}, bk.GetAllBalances(suite.ctx, acc.GetAddress())) -} - -func (suite *DrawTestSuite) TestRepayPrincipalOverpay() { - err := suite.keeper.RepayPrincipal(suite.ctx, suite.addrs[0], "xrp-a", c("usdx", 20000000)) - suite.NoError(err) - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - - acc := ak.GetAccount(suite.ctx, suite.addrs[0]) - suite.Equal(i(10000000000), (bk.GetBalance(suite.ctx, acc.GetAddress(), "usdx")).Amount) - _, found := suite.keeper.GetCDP(suite.ctx, "xrp-a", 1) - suite.False(found) -} - -func (suite *DrawTestSuite) TestPricefeedFailure() { - ctx := suite.ctx.WithBlockTime(suite.ctx.BlockTime().Add(time.Hour * 2)) - pfk := suite.app.GetPriceFeedKeeper() - err := pfk.SetCurrentPrices(ctx, "xrp:usd") - suite.Error(err) - - err = suite.keeper.AddPrincipal(ctx, suite.addrs[0], "xrp-a", c("usdx", 10000000)) - suite.Error(err) - err = suite.keeper.RepayPrincipal(ctx, suite.addrs[0], "xrp-a", c("usdx", 10000000)) - suite.NoError(err) -} - -func (suite *DrawTestSuite) TestModuleAccountFailure() { - ctx := suite.ctx.WithBlockHeader(suite.ctx.BlockHeader()) - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - acc := ak.GetModuleAccount(ctx, types.ModuleName) - - // Remove module account balance - ak.RemoveAccount(ctx, acc) - // Also need to burn coins as account keeper no longer stores balances - err := bk.BurnCoins(ctx, types.ModuleName, bk.GetAllBalances(ctx, acc.GetAddress())) - suite.Require().NoError(err) - - suite.Panics(func() { - // Error ignored here since this should panic - _ = suite.keeper.RepayPrincipal(ctx, suite.addrs[0], "xrp-a", c("usdx", 10000000)) - }) -} - -func TestDrawTestSuite(t *testing.T) { - suite.Run(t, new(DrawTestSuite)) -} diff --git a/x/cdp/keeper/grpc_query.go b/x/cdp/keeper/grpc_query.go deleted file mode 100644 index 32ca9562..00000000 --- a/x/cdp/keeper/grpc_query.go +++ /dev/null @@ -1,297 +0,0 @@ -package keeper - -import ( - "context" - "sort" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/0glabs/0g-chain/x/cdp/types" -) - -type QueryServer struct { - keeper Keeper -} - -// NewQueryServer returns an implementation of the pricefeed MsgServer interface -// for the provided Keeper. -func NewQueryServerImpl(keeper Keeper) types.QueryServer { - return &QueryServer{keeper: keeper} -} - -var _ types.QueryServer = QueryServer{} - -// Params queries all parameters of the cdp module. -func (s QueryServer) Params(c context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(c) - params := s.keeper.GetParams(sdkCtx) - - return &types.QueryParamsResponse{Params: params}, nil -} - -// Accounts queries the CDP module accounts. -func (s QueryServer) Accounts(c context.Context, req *types.QueryAccountsRequest) (*types.QueryAccountsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - cdpAccAccount := s.keeper.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - liquidatorAccAccount := s.keeper.accountKeeper.GetModuleAccount(ctx, types.LiquidatorMacc) - - accounts := []authtypes.ModuleAccount{ - *cdpAccAccount.(*authtypes.ModuleAccount), - *liquidatorAccAccount.(*authtypes.ModuleAccount), - } - - return &types.QueryAccountsResponse{Accounts: accounts}, nil -} - -// TotalPrincipal queries the total principal of a given collateral type. -func (s QueryServer) TotalPrincipal(c context.Context, req *types.QueryTotalPrincipalRequest) (*types.QueryTotalPrincipalResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - var queryCollateralTypes []string - - if req.CollateralType != "" { - // Single collateralType provided - queryCollateralTypes = append(queryCollateralTypes, req.CollateralType) - } else { - // No collateralType provided, respond with all of them - keeperParams := s.keeper.GetParams(ctx) - - for _, collateral := range keeperParams.CollateralParams { - queryCollateralTypes = append(queryCollateralTypes, collateral.Type) - } - } - - var collateralPrincipals types.TotalPrincipals - - for _, queryType := range queryCollateralTypes { - // Hardcoded to default USDX - principalAmount := s.keeper.GetTotalPrincipal(ctx, queryType, types.DefaultStableDenom) - // Wrap it in an sdk.Coin - totalAmountCoin := sdk.NewCoin(types.DefaultStableDenom, principalAmount) - - totalPrincipal := types.NewTotalPrincipal(queryType, totalAmountCoin) - collateralPrincipals = append(collateralPrincipals, totalPrincipal) - } - - return &types.QueryTotalPrincipalResponse{ - TotalPrincipal: collateralPrincipals, - }, nil -} - -// TotalCollateral queries the total collateral of a given collateral type. -func (s QueryServer) TotalCollateral(c context.Context, req *types.QueryTotalCollateralRequest) (*types.QueryTotalCollateralResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - params := s.keeper.GetParams(ctx) - denomCollateralTypes := make(map[string][]string) - - // collect collateral types for each denom - for _, collateralParam := range params.CollateralParams { - denomCollateralTypes[collateralParam.Denom] = append(denomCollateralTypes[collateralParam.Denom], collateralParam.Type) - } - - // sort collateral types alphabetically - for _, collateralTypes := range denomCollateralTypes { - sort.Slice(collateralTypes, func(i int, j int) bool { - return collateralTypes[i] < collateralTypes[j] - }) - } - - // get total collateral in all cdps - cdpAccount := s.keeper.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - totalCdpCollateral := s.keeper.bankKeeper.GetAllBalances(ctx, cdpAccount.GetAddress()) - - var totalCollaterals types.TotalCollaterals - - for denom, collateralTypes := range denomCollateralTypes { - // skip any denoms that do not match the requested collateral type - if req.CollateralType != "" { - match := false - for _, ctype := range collateralTypes { - if ctype == req.CollateralType { - match = true - } - } - - if !match { - continue - } - } - - totalCollateral := totalCdpCollateral.AmountOf(denom) - - // we need to query individual cdps for denoms with more than one collateral type - for i := len(collateralTypes) - 1; i > 0; i-- { - cdps := s.keeper.GetAllCdpsByCollateralType(ctx, collateralTypes[i]) - - collateral := sdk.ZeroInt() - - for _, cdp := range cdps { - collateral = collateral.Add(cdp.Collateral.Amount) - } - - totalCollateral = totalCollateral.Sub(collateral) - - // if we have no collateralType filter, or the filter matches, include it in the response - if req.CollateralType == "" || collateralTypes[i] == req.CollateralType { - totalCollaterals = append(totalCollaterals, types.NewTotalCollateral(collateralTypes[i], sdk.NewCoin(denom, collateral))) - } - - // skip the rest of the cdp queries if we have a matching filter - if collateralTypes[i] == req.CollateralType { - break - } - } - - if req.CollateralType == "" || collateralTypes[0] == req.CollateralType { - // all leftover total collateral belongs to the first collateral type - totalCollaterals = append(totalCollaterals, types.NewTotalCollateral(collateralTypes[0], sdk.NewCoin(denom, totalCollateral))) - } - } - - // sort to ensure deterministic response - sort.Slice(totalCollaterals, func(i int, j int) bool { - return totalCollaterals[i].CollateralType < totalCollaterals[j].CollateralType - }) - - return &types.QueryTotalCollateralResponse{ - TotalCollateral: totalCollaterals, - }, nil -} - -// Cdps queries all active CDPs. -func (s QueryServer) Cdps(c context.Context, req *types.QueryCdpsRequest) (*types.QueryCdpsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - // Filter CDPs - filteredCDPs, err := GrpcFilterCDPs(ctx, s.keeper, *req) - if err != nil { - return nil, err - } - - return &types.QueryCdpsResponse{ - Cdps: filteredCDPs, - // TODO: Use built in pagination and respond - Pagination: nil, - }, nil -} - -// Cdp queries a CDP with the input owner address and collateral type. -func (s QueryServer) Cdp(c context.Context, req *types.QueryCdpRequest) (*types.QueryCdpResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - owner, err := sdk.AccAddressFromBech32(req.Owner) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid address") - } - - _, valid := s.keeper.GetCollateral(ctx, req.CollateralType) - if !valid { - return nil, errorsmod.Wrap(types.ErrInvalidCollateral, req.CollateralType) - } - - cdp, found := s.keeper.GetCdpByOwnerAndCollateralType(ctx, owner, req.CollateralType) - if !found { - return nil, errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", req.Owner, req.CollateralType) - } - - cdpResponse := s.keeper.LoadCDPResponse(ctx, cdp) - - return &types.QueryCdpResponse{ - Cdp: cdpResponse, - }, nil -} - -// Deposits queries deposits associated with the CDP owned by an address for a collateral type. -func (s QueryServer) Deposits(c context.Context, req *types.QueryDepositsRequest) (*types.QueryDepositsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - owner, err := sdk.AccAddressFromBech32(req.Owner) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid address") - } - - _, valid := s.keeper.GetCollateral(ctx, req.CollateralType) - if !valid { - return nil, errorsmod.Wrap(types.ErrInvalidCollateral, req.CollateralType) - } - - cdp, found := s.keeper.GetCdpByOwnerAndCollateralType(ctx, owner, req.CollateralType) - if !found { - return nil, errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", req.Owner, req.CollateralType) - } - - deposits := s.keeper.GetDeposits(ctx, cdp.ID) - - return &types.QueryDepositsResponse{ - Deposits: deposits, - }, nil -} - -// FilterCDPs queries the store for all CDPs that match query req -func GrpcFilterCDPs(ctx sdk.Context, k Keeper, req types.QueryCdpsRequest) (types.CDPResponses, error) { - // TODO: Ideally use query.Paginate() here over existing FilterCDPs. However - // This is difficult to use different CDP indices and specific keeper - // methods without iterating over all CDPs. - page, limit, err := query.ParsePagination(req.Pagination) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, err.Error()) - } - - // Owner address is optional, only parse if it's provided otherwise it will - // respond with an error - var owner sdk.AccAddress - if req.Owner != "" { - owner, err = sdk.AccAddressFromBech32(req.Owner) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid owner address") - } - } - - ratio := sdk.ZeroDec() - - if req.Ratio != "" { - ratio, err = sdk.NewDecFromStr(req.Ratio) - if err != nil { - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid ratio") - } - } - } - - legacyParams := types.NewQueryCdpsParams(page, limit, req.CollateralType, owner, req.ID, ratio) - - cdps, err := FilterCDPs(ctx, k, legacyParams) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, err.Error()) - } - - var cdpResponses types.CDPResponses - for _, cdp := range cdps { - cdpResponse := types.CDPResponse{ - ID: cdp.ID, - Owner: cdp.Owner.String(), - Type: cdp.Type, - Collateral: cdp.Collateral, - Principal: cdp.Principal, - AccumulatedFees: cdp.AccumulatedFees, - FeesUpdated: cdp.FeesUpdated, - InterestFactor: cdp.InterestFactor.String(), - CollateralValue: cdp.CollateralValue, - CollateralizationRatio: cdp.CollateralizationRatio.String(), - } - cdpResponses = append(cdpResponses, cdpResponse) - } - - return cdpResponses, nil -} diff --git a/x/cdp/keeper/grpc_query_test.go b/x/cdp/keeper/grpc_query_test.go deleted file mode 100644 index d298d420..00000000 --- a/x/cdp/keeper/grpc_query_test.go +++ /dev/null @@ -1,284 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/cdp/keeper" - "github.com/0glabs/0g-chain/x/cdp/types" - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - "github.com/stretchr/testify/suite" -) - -type grpcQueryTestSuite struct { - suite.Suite - - tApp app.TestApp - ctx sdk.Context - keeper keeper.Keeper - queryServer types.QueryServer - addrs []sdk.AccAddress - now time.Time -} - -func (suite *grpcQueryTestSuite) SetupTest() { - suite.tApp = app.NewTestApp() - suite.tApp.InitializeFromGenesisStates( - NewPricefeedGenStateMulti(suite.tApp.AppCodec()), - NewCDPGenStateMulti(suite.tApp.AppCodec()), - ) - suite.ctx = suite.tApp.NewContext(true, tmprototypes.Header{}). - WithBlockTime(time.Now().UTC()) - suite.keeper = suite.tApp.GetCDPKeeper() - suite.queryServer = keeper.NewQueryServerImpl(suite.keeper) - - _, addrs := app.GeneratePrivKeyAddressPairs(5) - suite.addrs = addrs - - suite.now = time.Now().UTC() -} - -func (suite *grpcQueryTestSuite) addCdp() { - ak := suite.tApp.GetAccountKeeper() - pk := suite.tApp.GetPriceFeedKeeper() - - acc := ak.NewAccountWithAddress(suite.ctx, suite.addrs[0]) - err := suite.tApp.FundAccount(suite.ctx, acc.GetAddress(), cs(c("xrp", 200000000), c("btc", 500000000))) - suite.NoError(err) - - ak.SetAccount(suite.ctx, acc) - - err = pk.SetCurrentPrices(suite.ctx, "xrp:usd") - suite.NoError(err) - - ok := suite.keeper.UpdatePricefeedStatus(suite.ctx, "xrp:usd") - suite.True(ok) - - err = suite.keeper.AddCdp(suite.ctx, suite.addrs[0], c("xrp", 100000000), c("usdx", 10000000), "xrp-a") - suite.NoError(err) - - id := suite.keeper.GetNextCdpID(suite.ctx) - suite.Equal(uint64(2), id) - - tp := suite.keeper.GetTotalPrincipal(suite.ctx, "xrp-a", "usdx") - suite.Equal(i(10000000), tp) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryParams() { - res, err := suite.queryServer.Params(sdk.WrapSDKContext(suite.ctx), &types.QueryParamsRequest{}) - suite.Require().NoError(err) - - var expected types.GenesisState - defaultCdpState := NewCDPGenStateMulti(suite.tApp.AppCodec()) - suite.tApp.AppCodec().MustUnmarshalJSON(defaultCdpState[types.ModuleName], &expected) - - suite.Equal(expected.Params, res.Params, "params should equal test genesis state") -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryParams_Default() { - suite.keeper.SetParams(suite.ctx, types.DefaultParams()) - - res, err := suite.queryServer.Params(sdk.WrapSDKContext(suite.ctx), &types.QueryParamsRequest{}) - suite.Require().NoError(err) - suite.Empty(res.Params.CollateralParams) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryAccounts() { - res, err := suite.queryServer.Accounts(sdk.WrapSDKContext(suite.ctx), &types.QueryAccountsRequest{}) - suite.Require().NoError(err) - - ak := suite.tApp.GetAccountKeeper() - acc := ak.GetModuleAccount(suite.ctx, types.ModuleName) - liquidator := ak.GetModuleAccount(suite.ctx, types.LiquidatorMacc) - - suite.Len(res.Accounts, 2) - suite.Equal(acc, &res.Accounts[0], "accounts should include module account") - suite.Equal(liquidator, &res.Accounts[1], "accounts should include liquidator account") -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalPrincipal() { - suite.addCdp() - - res, err := suite.queryServer.TotalPrincipal(sdk.WrapSDKContext(suite.ctx), &types.QueryTotalPrincipalRequest{}) - suite.Require().NoError(err) - - suite.Len(res.TotalPrincipal, 4, "total principal should include all collateral params") - - suite.Contains(res.TotalPrincipal, types.TotalPrincipal{ - CollateralType: "xrp-a", - 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", sdkmath.NewInt(0)), - }, "total busd principal should be 0") -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalCollateral() { - suite.addCdp() - - res, err := suite.queryServer.TotalCollateral(sdk.WrapSDKContext(suite.ctx), &types.QueryTotalCollateralRequest{}) - suite.Require().NoError(err) - - 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", sdkmath.NewInt(100000000)), - }, "total collaterals should include added cdp") - suite.Contains(res.TotalCollateral, types.TotalCollateral{ - CollateralType: "busd-a", - Amount: sdk.NewCoin("busd", sdkmath.NewInt(0)), - }, "busd total collateral should be 0") -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryCdps() { - suite.addCdp() - - res, err := suite.queryServer.Cdps(sdk.WrapSDKContext(suite.ctx), &types.QueryCdpsRequest{ - CollateralType: "xrp-a", - Pagination: &query.PageRequest{ - Limit: 100, - }, - }) - suite.Require().NoError(err) - - suite.Len(res.Cdps, 1) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryCdps_InvalidCollateralType() { - suite.addCdp() - - _, err := suite.queryServer.Cdps(sdk.WrapSDKContext(suite.ctx), &types.QueryCdpsRequest{ - CollateralType: "kava-a", - }) - suite.Require().Error(err) - suite.Require().Equal("rpc error: code = InvalidArgument desc = invalid collateral type", err.Error()) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryCdp() { - suite.addCdp() - - tests := []struct { - giveName string - giveRequest types.QueryCdpRequest - wantAccepted bool - wantErr string - }{ - { - "valid", - types.QueryCdpRequest{ - CollateralType: "xrp-a", - Owner: suite.addrs[0].String(), - }, - true, - "", - }, - { - "invalid collateral", - types.QueryCdpRequest{ - CollateralType: "kava-a", - Owner: suite.addrs[0].String(), - }, - false, - "kava-a: invalid collateral for input collateral type", - }, - { - "missing owner", - types.QueryCdpRequest{ - CollateralType: "xrp-a", - }, - false, - "rpc error: code = InvalidArgument desc = invalid address", - }, - { - "invalid owner", - types.QueryCdpRequest{ - CollateralType: "xrp-a", - Owner: "invalid addr", - }, - false, - "rpc error: code = InvalidArgument desc = invalid address", - }, - } - - for _, tt := range tests { - suite.Run(tt.giveName, func() { - _, err := suite.queryServer.Cdp(sdk.WrapSDKContext(suite.ctx), &tt.giveRequest) - - if tt.wantAccepted { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - suite.Require().Equal(tt.wantErr, err.Error()) - } - }) - } -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryDeposits() { - suite.addCdp() - - tests := []struct { - giveName string - giveRequest *types.QueryDepositsRequest - wantContainsDeposit *types.Deposit - wantShouldErr bool - wantErr string - }{ - { - "valid", - &types.QueryDepositsRequest{ - CollateralType: "xrp-a", - Owner: suite.addrs[0].String(), - }, - &types.Deposit{ - CdpID: 1, - Depositor: suite.addrs[0], - Amount: sdk.NewCoin("xrp", sdkmath.NewInt(100000000)), - }, - false, - "", - }, - { - "invalid collateral type", - &types.QueryDepositsRequest{ - CollateralType: "kava-a", - Owner: suite.addrs[0].String(), - }, - nil, - true, - "kava-a: invalid collateral for input collateral type", - }, - { - "missing owner", - &types.QueryDepositsRequest{ - CollateralType: "xrp-a", - }, - nil, - true, - "rpc error: code = InvalidArgument desc = invalid address", - }, - } - - for _, tt := range tests { - suite.Run(tt.giveName, func() { - res, err := suite.queryServer.Deposits(sdk.WrapSDKContext(suite.ctx), tt.giveRequest) - - if tt.wantShouldErr { - suite.Error(err) - suite.Equal(tt.wantErr, err.Error()) - } else { - suite.NoError(err) - suite.Contains(res.Deposits, *tt.wantContainsDeposit) - } - }) - } -} - -func TestGrpcQueryTestSuite(t *testing.T) { - suite.Run(t, new(grpcQueryTestSuite)) -} diff --git a/x/cdp/keeper/hooks.go b/x/cdp/keeper/hooks.go deleted file mode 100644 index 2da62ee8..00000000 --- a/x/cdp/keeper/hooks.go +++ /dev/null @@ -1,23 +0,0 @@ -package keeper - -import ( - "github.com/0glabs/0g-chain/x/cdp/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// Implements StakingHooks interface -var _ types.CDPHooks = Keeper{} - -// AfterCDPCreated - call hook if registered -func (k Keeper) AfterCDPCreated(ctx sdk.Context, cdp types.CDP) { - if k.hooks != nil { - k.hooks.AfterCDPCreated(ctx, cdp) - } -} - -// BeforeCDPModified - call hook if registered -func (k Keeper) BeforeCDPModified(ctx sdk.Context, cdp types.CDP) { - if k.hooks != nil { - k.hooks.BeforeCDPModified(ctx, cdp) - } -} diff --git a/x/cdp/keeper/integration_test.go b/x/cdp/keeper/integration_test.go deleted file mode 100644 index d3c9c98e..00000000 --- a/x/cdp/keeper/integration_test.go +++ /dev/null @@ -1,320 +0,0 @@ -package keeper_test - -import ( - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/cdp/types" - pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" -) - -// Avoid cluttering test cases with long function names -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...) } - -func NewPricefeedGenState(cdc codec.JSONCodec, asset string, price sdk.Dec) app.GenesisState { - pfGenesis := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: asset + ":usd", BaseAsset: asset, QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: asset + ":usd", - OracleAddress: sdk.AccAddress{}, - Price: price, - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - return app.GenesisState{pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pfGenesis)} -} - -func NewCDPGenState(cdc codec.JSONCodec, asset string, liquidationRatio sdk.Dec) app.GenesisState { - cdpGenesis := types.GenesisState{ - Params: types.Params{ - GlobalDebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - SurplusAuctionThreshold: types.DefaultSurplusThreshold, - SurplusAuctionLot: types.DefaultSurplusLot, - DebtAuctionThreshold: types.DefaultDebtThreshold, - DebtAuctionLot: types.DefaultDebtLot, - LiquidationBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - CollateralParams: types.CollateralParams{ - { - Denom: asset, - Type: asset + "-a", - LiquidationRatio: liquidationRatio, - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(100), - SpotMarketID: asset + ":usd", - LiquidationMarketID: asset + ":usd", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(6), - }, - }, - DebtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: i(6), - DebtFloor: i(10000000), - }, - }, - StartingCdpID: types.DefaultCdpStartingID, - DebtDenom: types.DefaultDebtDenom, - GovDenom: types.DefaultGovDenom, - CDPs: types.CDPs{}, - PreviousAccumulationTimes: types.GenesisAccumulationTimes{ - types.NewGenesisAccumulationTime(asset+"-a", time.Time{}, sdk.OneDec()), - }, - TotalPrincipals: types.GenesisTotalPrincipals{ - types.NewGenesisTotalPrincipal(asset+"-a", sdk.ZeroInt()), - }, - } - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&cdpGenesis)} -} - -func NewPricefeedGenStateMulti(cdc codec.JSONCodec) app.GenesisState { - pfGenesis := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "btc:usd", BaseAsset: "btc", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "btc:usd:30", BaseAsset: "btc", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "xrp:usd", BaseAsset: "xrp", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "xrp:usd:30", BaseAsset: "xrp", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd:30", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "busd:usd", BaseAsset: "busd", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "busd:usd:30", BaseAsset: "busd", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "btc:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("8000.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "btc:usd:30", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("8000.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "xrp:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("0.25"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "xrp:usd:30", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("0.25"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("17.25"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "bnb:usd:30", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("17.25"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "busd:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.OneDec(), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "busd:usd:30", - OracleAddress: sdk.AccAddress{}, - Price: sdk.OneDec(), - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - return app.GenesisState{pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pfGenesis)} -} - -func NewCDPGenStateMulti(cdc codec.JSONCodec) app.GenesisState { - cdpGenesis := types.GenesisState{ - Params: types.Params{ - GlobalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - SurplusAuctionThreshold: types.DefaultSurplusThreshold, - SurplusAuctionLot: types.DefaultSurplusLot, - DebtAuctionThreshold: types.DefaultDebtThreshold, - DebtAuctionLot: types.DefaultDebtLot, - LiquidationBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - CollateralParams: types.CollateralParams{ - { - Denom: "xrp", - Type: "xrp-a", - LiquidationRatio: sdk.MustNewDecFromStr("2.0"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(7000000000), - SpotMarketID: "xrp:usd", - LiquidationMarketID: "xrp:usd:30", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(6), - }, - { - Denom: "btc", - Type: "btc-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000000782997609"), // %2.5 apr - LiquidationPenalty: d("0.025"), - AuctionSize: i(10000000), - SpotMarketID: "btc:usd", - LiquidationMarketID: "btc:usd:30", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(8), - }, - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd:30", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(8), - }, - { - Denom: "busd", - Type: "busd-a", - LiquidationRatio: d("1.01"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.OneDec(), // %0 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(10000000000), - SpotMarketID: "busd:usd", - LiquidationMarketID: "busd:usd:30", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(8), - }, - }, - DebtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: i(6), - DebtFloor: i(10000000), - }, - }, - StartingCdpID: types.DefaultCdpStartingID, - DebtDenom: types.DefaultDebtDenom, - GovDenom: types.DefaultGovDenom, - CDPs: types.CDPs{}, - PreviousAccumulationTimes: types.GenesisAccumulationTimes{ - types.NewGenesisAccumulationTime("btc-a", time.Time{}, sdk.OneDec()), - types.NewGenesisAccumulationTime("xrp-a", time.Time{}, sdk.OneDec()), - types.NewGenesisAccumulationTime("busd-a", time.Time{}, sdk.OneDec()), - types.NewGenesisAccumulationTime("bnb-a", time.Time{}, sdk.OneDec()), - }, - TotalPrincipals: types.GenesisTotalPrincipals{ - types.NewGenesisTotalPrincipal("btc-a", sdk.ZeroInt()), - types.NewGenesisTotalPrincipal("xrp-a", sdk.ZeroInt()), - types.NewGenesisTotalPrincipal("busd-a", sdk.ZeroInt()), - types.NewGenesisTotalPrincipal("bnb-a", sdk.ZeroInt()), - }, - } - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&cdpGenesis)} -} - -func NewCDPGenStateHighDebtLimit(cdc codec.JSONCodec) app.GenesisState { - cdpGenesis := types.GenesisState{ - Params: types.Params{ - GlobalDebtLimit: sdk.NewInt64Coin("usdx", 100000000000000), - SurplusAuctionThreshold: types.DefaultSurplusThreshold, - SurplusAuctionLot: types.DefaultSurplusLot, - DebtAuctionThreshold: types.DefaultDebtThreshold, - DebtAuctionLot: types.DefaultDebtLot, - LiquidationBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - CollateralParams: types.CollateralParams{ - { - Denom: "xrp", - Type: "xrp-a", - LiquidationRatio: sdk.MustNewDecFromStr("2.0"), - DebtLimit: sdk.NewInt64Coin("usdx", 50000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(7000000000), - SpotMarketID: "xrp:usd", - LiquidationMarketID: "xrp:usd", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(6), - }, - { - Denom: "btc", - Type: "btc-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 50000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000000782997609"), // %2.5 apr - LiquidationPenalty: d("0.025"), - AuctionSize: i(10000000), - SpotMarketID: "btc:usd", - LiquidationMarketID: "btc:usd", - KeeperRewardPercentage: d("0.01"), - CheckCollateralizationIndexCount: i(10), - ConversionFactor: i(8), - }, - }, - DebtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: i(6), - DebtFloor: i(10000000), - }, - }, - StartingCdpID: types.DefaultCdpStartingID, - DebtDenom: types.DefaultDebtDenom, - GovDenom: types.DefaultGovDenom, - CDPs: types.CDPs{}, - PreviousAccumulationTimes: types.GenesisAccumulationTimes{ - types.NewGenesisAccumulationTime("btc-a", time.Time{}, sdk.OneDec()), - types.NewGenesisAccumulationTime("xrp-a", time.Time{}, sdk.OneDec()), - }, - TotalPrincipals: types.GenesisTotalPrincipals{ - types.NewGenesisTotalPrincipal("btc-a", sdk.ZeroInt()), - types.NewGenesisTotalPrincipal("xrp-a", sdk.ZeroInt()), - }, - } - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&cdpGenesis)} -} - -func cdps() (cdps types.CDPs) { - _, addrs := app.GeneratePrivKeyAddressPairs(3) - 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 -} diff --git a/x/cdp/keeper/interest.go b/x/cdp/keeper/interest.go deleted file mode 100644 index d9c964ab..00000000 --- a/x/cdp/keeper/interest.go +++ /dev/null @@ -1,171 +0,0 @@ -package keeper - -import ( - "fmt" - "math" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/cdp/types" -) - -var scalingFactor = 1e18 - -// AccumulateInterest calculates the new interest that has accrued for the input collateral type based on the total amount of principal -// that has been created with that collateral type and the amount of time that has passed since interest was last accumulated -func (k Keeper) AccumulateInterest(ctx sdk.Context, ctype string) error { - previousAccrualTime, found := k.GetPreviousAccrualTime(ctx, ctype) - if !found { - k.SetPreviousAccrualTime(ctx, ctype, ctx.BlockTime()) - return nil - } - - timeElapsed := int64(math.RoundToEven( - ctx.BlockTime().Sub(previousAccrualTime).Seconds(), - )) - if timeElapsed == 0 { - return nil - } - - totalPrincipalPrior := k.GetTotalPrincipal(ctx, ctype, types.DefaultStableDenom) - if totalPrincipalPrior.IsZero() || totalPrincipalPrior.IsNegative() { - k.SetPreviousAccrualTime(ctx, ctype, ctx.BlockTime()) - return nil - } - - interestFactorPrior, foundInterestFactorPrior := k.GetInterestFactor(ctx, ctype) - if !foundInterestFactorPrior { - k.SetInterestFactor(ctx, ctype, sdk.OneDec()) - // set previous accrual time exit early because interest accumulated will be zero - k.SetPreviousAccrualTime(ctx, ctype, ctx.BlockTime()) - return nil - } - - borrowRateSpy := k.getFeeRate(ctx, ctype) - if borrowRateSpy.Equal(sdk.OneDec()) { - k.SetPreviousAccrualTime(ctx, ctype, ctx.BlockTime()) - return nil - } - 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 - return nil - } - err := k.MintDebtCoins(ctx, types.ModuleName, k.GetDebtDenom(ctx), sdk.NewCoin(types.DefaultStableDenom, interestAccumulated)) - if err != nil { - return err - } - - dp, found := k.GetDebtParam(ctx, types.DefaultStableDenom) - if !found { - panic(fmt.Sprintf("Debt parameters for %s not found", types.DefaultStableDenom)) - } - - newFeesSurplus := interestAccumulated - - // mint surplus coins to the liquidator module account. - if newFeesSurplus.IsPositive() { - err := k.bankKeeper.MintCoins(ctx, types.LiquidatorMacc, sdk.NewCoins(sdk.NewCoin(dp.Denom, newFeesSurplus))) - if err != nil { - return err - } - } - - interestFactorNew := interestFactorPrior.Mul(interestFactor) - totalPrincipalNew := totalPrincipalPrior.Add(interestAccumulated) - - k.SetTotalPrincipal(ctx, ctype, types.DefaultStableDenom, totalPrincipalNew) - k.SetInterestFactor(ctx, ctype, interestFactorNew) - k.SetPreviousAccrualTime(ctx, ctype, ctx.BlockTime()) - - return nil -} - -// 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 sdkmath.Int) sdk.Dec { - scalingFactorUint := sdk.NewUint(uint64(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()) - - // Convert seconds elapsed to uint (*not scaled*) - secondsElapsedUint := sdkmath.NewUintFromBigInt(secondsElapsed.BigInt()) - - // Calculate the interest factor as a uint scaled by 1e18 - interestFactorMantissa := sdkmath.RelativePow(interestMantissa, secondsElapsedUint, scalingFactorUint) - - // Convert interest factor to an unscaled sdk.Dec - return sdk.NewDecFromBigInt(interestFactorMantissa.BigInt()).QuoInt(scalingFactorInt) -} - -// SynchronizeInterest updates the input cdp object to reflect the current accumulated interest, updates the cdp state in the store, -// and returns the updated cdp object -func (k Keeper) SynchronizeInterest(ctx sdk.Context, cdp types.CDP) types.CDP { - globalInterestFactor, found := k.GetInterestFactor(ctx, cdp.Type) - if !found { - k.SetInterestFactor(ctx, cdp.Type, sdk.OneDec()) - cdp.InterestFactor = sdk.OneDec() - cdp.FeesUpdated = ctx.BlockTime() - if err := k.SetCDP(ctx, cdp); err != nil { - panic(err) - } - return cdp - } - - accumulatedInterest := k.CalculateNewInterest(ctx, cdp) - prevAccrualTime, found := k.GetPreviousAccrualTime(ctx, cdp.Type) - if !found { - return cdp - } - if accumulatedInterest.IsZero() { - // accumulated interest is zero if apy is zero or are if the total fees for all cdps round to zero - if cdp.FeesUpdated.Equal(prevAccrualTime) { - // if all fees are rounding to zero, don't update FeesUpdated - return cdp - } - // if apy is zero, we need to update FeesUpdated - cdp.FeesUpdated = prevAccrualTime - if err := k.SetCDP(ctx, cdp); err != nil { - panic(err) - } - } - - cdp.AccumulatedFees = cdp.AccumulatedFees.Add(accumulatedInterest) - cdp.FeesUpdated = prevAccrualTime - cdp.InterestFactor = globalInterestFactor - collateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Type, cdp.GetTotalPrincipal()) - if err := k.UpdateCdpAndCollateralRatioIndex(ctx, cdp, collateralToDebtRatio); err != nil { - panic(err) - } - - return cdp -} - -// CalculateNewInterest returns the amount of interest that has accrued to the cdp since its interest was last synchronized -func (k Keeper) CalculateNewInterest(ctx sdk.Context, cdp types.CDP) sdk.Coin { - globalInterestFactor, found := k.GetInterestFactor(ctx, cdp.Type) - if !found { - return sdk.NewCoin(cdp.AccumulatedFees.Denom, sdk.ZeroInt()) - } - cdpInterestFactor := globalInterestFactor.Quo(cdp.InterestFactor) - if cdpInterestFactor.Equal(sdk.OneDec()) { - return sdk.NewCoin(cdp.AccumulatedFees.Denom, sdk.ZeroInt()) - } - accumulatedInterest := sdk.NewDecFromInt(cdp.GetTotalPrincipal().Amount).Mul(cdpInterestFactor).RoundInt().Sub(cdp.GetTotalPrincipal().Amount) - return sdk.NewCoin(cdp.AccumulatedFees.Denom, accumulatedInterest) -} - -// SynchronizeInterestForRiskyCDPs synchronizes the interest for the slice of cdps with the lowest collateral:debt ratio -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) - k.SynchronizeInterest(ctx, cdp) - } - return nil -} diff --git a/x/cdp/keeper/interest_test.go b/x/cdp/keeper/interest_test.go deleted file mode 100644 index eed54598..00000000 --- a/x/cdp/keeper/interest_test.go +++ /dev/null @@ -1,735 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/stretchr/testify/suite" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/cdp/keeper" - "github.com/0glabs/0g-chain/x/cdp/types" -) - -type InterestTestSuite struct { - suite.Suite - - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context -} - -func (suite *InterestTestSuite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - cdc := tApp.AppCodec() - tApp.InitializeFromGenesisStates( - NewPricefeedGenStateMulti(cdc), - NewCDPGenStateMulti(cdc), - ) - keeper := tApp.GetCDPKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper -} - -func (suite *InterestTestSuite) TestCalculateInterestFactor() { - type args struct { - perSecondInterestRate sdk.Dec - timeElapsed sdkmath.Int - expectedValue sdk.Dec - } - - type test struct { - name string - args args - } - - oneYearInSeconds := int64(31536000) - - testCases := []test{ - { - "1 year", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("1.191463614477847370"), - }, - }, - { - "10 year", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds * 10), - expectedValue: sdk.MustNewDecFromStr("5.765113233897391189"), - }, - }, - { - "1 month", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds / 12), - expectedValue: sdk.MustNewDecFromStr("1.014705619075717373"), - }, - }, - { - "1 day", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds / 365), - expectedValue: sdk.MustNewDecFromStr("1.000480067194057924"), - }, - }, - { - "1 year: low interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000000555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("1.017656545925063632"), - }, - }, - { - "1 year, lower interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000000055"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("1.001735985079841390"), - }, - }, - { - "1 year, lowest interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000000005"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("1.000157692432076670"), - }, - }, - { - "1 year: high interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000055555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("5.766022095987868825"), - }, - }, - { - "1 year: higher interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000555555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("40628388.864535408465693310"), - }, - }, - // If we raise the per second interest rate too much we'll cause an integer overflow. - // For example, perSecondInterestRate: '1.000005555555' will cause a panic. - { - "1 year: highest interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000001555555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("2017093013158200407564.613502861572552603"), - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - interestFactor := keeper.CalculateInterestFactor(tc.args.perSecondInterestRate, tc.args.timeElapsed) - suite.Require().Equal(tc.args.expectedValue, interestFactor) - }) - } -} - -func (suite *InterestTestSuite) TestAccumulateInterest() { - type args struct { - ctype string - initialTime time.Time - totalPrincipal sdkmath.Int - timeElapsed int - expectedTotalPrincipal sdkmath.Int - expectedLastAccrualTime time.Time - } - - type test struct { - name string - args args - } - oneYearInSeconds := 31536000 - - testCases := []test{ - { - "1 year", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - totalPrincipal: sdkmath.NewInt(100000000000000), - timeElapsed: oneYearInSeconds, - expectedTotalPrincipal: sdkmath.NewInt(105000000000012), - expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * oneYearInSeconds)), - }, - }, - { - "1 year - zero principal", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - totalPrincipal: sdk.ZeroInt(), - timeElapsed: oneYearInSeconds, - expectedTotalPrincipal: sdk.ZeroInt(), - expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * oneYearInSeconds)), - }, - }, - { - "1 month", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - totalPrincipal: sdkmath.NewInt(100000000000000), - timeElapsed: 86400 * 30, - expectedTotalPrincipal: sdkmath.NewInt(100401820189198), - expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 86400 * 30)), - }, - }, - { - "1 month - interest rounds to zero", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - totalPrincipal: sdkmath.NewInt(10), - timeElapsed: 86400 * 30, - expectedTotalPrincipal: sdkmath.NewInt(10), - expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - }, - }, - { - "7 seconds", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - totalPrincipal: sdkmath.NewInt(100000000000000), - timeElapsed: 7, - expectedTotalPrincipal: sdkmath.NewInt(100000001082988), - expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 7)), - }, - }, - { - "7 seconds - interest rounds to zero", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - totalPrincipal: sdkmath.NewInt(30000000), - timeElapsed: 7, - expectedTotalPrincipal: sdkmath.NewInt(30000000), - expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - }, - }, - { - "7 seconds - zero interest", - args{ - ctype: "busd-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - totalPrincipal: sdkmath.NewInt(100000000000000), - timeElapsed: 7, - expectedTotalPrincipal: sdkmath.NewInt(100000000000000), - expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 7)), - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.ctx = suite.ctx.WithBlockTime(tc.args.initialTime) - suite.keeper.SetTotalPrincipal(suite.ctx, tc.args.ctype, types.DefaultStableDenom, tc.args.totalPrincipal) - suite.keeper.SetPreviousAccrualTime(suite.ctx, tc.args.ctype, suite.ctx.BlockTime()) - suite.keeper.SetInterestFactor(suite.ctx, tc.args.ctype, sdk.OneDec()) - - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - err := suite.keeper.AccumulateInterest(suite.ctx, tc.args.ctype) - suite.Require().NoError(err) - - actualTotalPrincipal := suite.keeper.GetTotalPrincipal(suite.ctx, tc.args.ctype, types.DefaultStableDenom) - suite.Require().Equal(tc.args.expectedTotalPrincipal, actualTotalPrincipal) - actualAccrualTime, _ := suite.keeper.GetPreviousAccrualTime(suite.ctx, tc.args.ctype) - suite.Require().Equal(tc.args.expectedLastAccrualTime, actualAccrualTime) - }) - } -} - -// TestSynchronizeInterest tests the functionality of synchronizing the accumulated interest for CDPs -func (suite *InterestTestSuite) TestSynchronizeInterest() { - type args struct { - ctype string - initialTime time.Time - initialCollateral sdk.Coin - initialPrincipal sdk.Coin - timeElapsed int - expectedFees sdk.Coin - expectedFeesUpdatedTime time.Time - } - - type test struct { - name string - args args - } - - oneYearInSeconds := 31536000 - testCases := []test{ - { - "1 year", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 100000000000), - timeElapsed: oneYearInSeconds, - expectedFees: c("usdx", 5000000000), - expectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * oneYearInSeconds)), - }, - }, - { - "1 month", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 100000000000), - timeElapsed: 86400 * 30, - expectedFees: c("usdx", 401820189), - expectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 86400 * 30)), - }, - }, - { - "7 seconds", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 100000000000), - timeElapsed: 7, - expectedFees: c("usdx", 1083), - expectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 7)), - }, - }, - { - "7 seconds - zero apy", - args{ - ctype: "busd-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialCollateral: c("busd", 10000000000000), - initialPrincipal: c("usdx", 10000000000), - timeElapsed: 7, - expectedFees: c("usdx", 0), - expectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 7)), - }, - }, - { - "7 seconds - fees round to zero", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialCollateral: c("bnb", 1000000000), - initialPrincipal: c("usdx", 10000000), - timeElapsed: 7, - expectedFees: c("usdx", 0), - expectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - suite.ctx = suite.ctx.WithBlockTime(tc.args.initialTime) - - // setup account state - _, addrs := app.GeneratePrivKeyAddressPairs(1) - ak := suite.app.GetAccountKeeper() - // setup the first account - acc := ak.NewAccountWithAddress(suite.ctx, addrs[0]) - ak.SetAccount(suite.ctx, acc) - bk := suite.app.GetBankKeeper() - - err := bk.MintCoins(suite.ctx, types.ModuleName, cs(tc.args.initialCollateral)) - suite.Require().NoError(err) - err = bk.SendCoinsFromModuleToAccount(suite.ctx, types.ModuleName, addrs[0], cs(tc.args.initialCollateral)) - suite.Require().NoError(err) - - // setup pricefeed - pk := suite.app.GetPriceFeedKeeper() - _, err = pk.SetPrice(suite.ctx, sdk.AccAddress{}, "bnb:usd", d("17.25"), tc.args.expectedFeesUpdatedTime.Add(time.Second)) - suite.NoError(err) - _, err = pk.SetPrice(suite.ctx, sdk.AccAddress{}, "busd:usd", d("1"), tc.args.expectedFeesUpdatedTime.Add(time.Second)) - suite.NoError(err) - - // setup cdp state - suite.keeper.SetPreviousAccrualTime(suite.ctx, tc.args.ctype, suite.ctx.BlockTime()) - suite.keeper.SetInterestFactor(suite.ctx, tc.args.ctype, sdk.OneDec()) - err = suite.keeper.AddCdp(suite.ctx, addrs[0], tc.args.initialCollateral, tc.args.initialPrincipal, tc.args.ctype) - suite.Require().NoError(err) - - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - err = suite.keeper.AccumulateInterest(suite.ctx, tc.args.ctype) - suite.Require().NoError(err) - - cdp, found := suite.keeper.GetCDP(suite.ctx, tc.args.ctype, 1) - suite.Require().True(found) - - cdp = suite.keeper.SynchronizeInterest(suite.ctx, cdp) - - suite.Require().Equal(tc.args.expectedFees, cdp.AccumulatedFees) - suite.Require().Equal(tc.args.expectedFeesUpdatedTime, cdp.FeesUpdated) - }) - } -} - -func (suite *InterestTestSuite) TestMultipleCDPInterest() { - type args struct { - ctype string - initialTime time.Time - blockInterval int - numberOfBlocks int - initialCDPCollateral sdk.Coin - initialCDPPrincipal sdk.Coin - numberOfCdps int - expectedFeesPerCDP sdk.Coin - expectedTotalPrincipalPerCDP sdk.Coin - expectedFeesUpdatedTime time.Time - expectedTotalPrincipal sdkmath.Int - expectedDebtBalance sdkmath.Int - expectedStableBalance sdkmath.Int - expectedSumOfCDPPrincipal sdkmath.Int - } - - type test struct { - name string - args args - } - - testCases := []test{ - { - "1 block", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - blockInterval: 7, - numberOfBlocks: 1, - initialCDPCollateral: c("bnb", 10000000000), - initialCDPPrincipal: c("usdx", 500000000), - numberOfCdps: 100, - expectedFeesPerCDP: c("usdx", 5), - expectedTotalPrincipalPerCDP: c("usdx", 500000005), - expectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 7)), - expectedTotalPrincipal: i(50000000541), - expectedDebtBalance: i(50000000541), - expectedStableBalance: i(50000000541), - expectedSumOfCDPPrincipal: i(50000000500), - }, - }, - { - "100 blocks", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - blockInterval: 7, - numberOfBlocks: 100, - initialCDPCollateral: c("bnb", 10000000000), - initialCDPPrincipal: c("usdx", 500000000), - numberOfCdps: 100, - expectedFeesPerCDP: c("usdx", 541), - expectedTotalPrincipalPerCDP: c("usdx", 500000541), - expectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 7 * 100)), - expectedTotalPrincipal: i(50000054100), - expectedDebtBalance: i(50000054100), - expectedStableBalance: i(50000054100), - expectedSumOfCDPPrincipal: i(50000054100), - }, - }, - { - "10000 blocks", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - blockInterval: 7, - numberOfBlocks: 10000, - initialCDPCollateral: c("bnb", 10000000000), - initialCDPPrincipal: c("usdx", 500000000), - numberOfCdps: 100, - expectedFeesPerCDP: c("usdx", 54152), - expectedTotalPrincipalPerCDP: c("usdx", 500054152), - expectedFeesUpdatedTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 7 * 10000)), - expectedTotalPrincipal: i(50005418990), - expectedDebtBalance: i(50005418990), - expectedStableBalance: i(50005418990), - expectedSumOfCDPPrincipal: i(50005415200), - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - suite.ctx = suite.ctx.WithBlockTime(tc.args.initialTime) - - // setup pricefeed - pk := suite.app.GetPriceFeedKeeper() - _, err := pk.SetPrice(suite.ctx, sdk.AccAddress{}, "bnb:usd", d("17.25"), tc.args.expectedFeesUpdatedTime.Add(time.Second)) - suite.NoError(err) - - // setup cdp state - suite.keeper.SetPreviousAccrualTime(suite.ctx, tc.args.ctype, suite.ctx.BlockTime()) - suite.keeper.SetInterestFactor(suite.ctx, tc.args.ctype, sdk.OneDec()) - - // setup account state - _, addrs := app.GeneratePrivKeyAddressPairs(tc.args.numberOfCdps) - for j := 0; j < tc.args.numberOfCdps; j++ { - ak := suite.app.GetAccountKeeper() - // setup the first account - acc := ak.NewAccountWithAddress(suite.ctx, addrs[j]) - ak.SetAccount(suite.ctx, acc) - bk := suite.app.GetBankKeeper() - err := bk.MintCoins(suite.ctx, types.ModuleName, cs(tc.args.initialCDPCollateral)) - suite.Require().NoError(err) - err = bk.SendCoinsFromModuleToAccount(suite.ctx, types.ModuleName, addrs[j], cs(tc.args.initialCDPCollateral)) - suite.Require().NoError(err) - err = suite.keeper.AddCdp(suite.ctx, addrs[j], tc.args.initialCDPCollateral, tc.args.initialCDPPrincipal, tc.args.ctype) - suite.Require().NoError(err) - } - - // run a number of blocks where CDPs are not synchronized - for j := 0; j < tc.args.numberOfBlocks; j++ { - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.blockInterval)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - err := suite.keeper.AccumulateInterest(suite.ctx, tc.args.ctype) - suite.Require().NoError(err) - } - - bk := suite.app.GetBankKeeper() - debtSupply := bk.GetSupply(suite.ctx, types.DefaultDebtDenom) - usdxSupply := bk.GetSupply(suite.ctx, types.DefaultStableDenom) - totalPrincipal := suite.keeper.GetTotalPrincipal(suite.ctx, tc.args.ctype, types.DefaultStableDenom) - - suite.Require().Equal(tc.args.expectedDebtBalance, debtSupply.Amount) - suite.Require().Equal(tc.args.expectedStableBalance, usdxSupply.Amount) - suite.Require().Equal(tc.args.expectedTotalPrincipal, totalPrincipal) - - sumOfCDPPrincipal := sdk.ZeroInt() - - for j := 0; j < tc.args.numberOfCdps; j++ { - cdp, found := suite.keeper.GetCDP(suite.ctx, tc.args.ctype, uint64(j+1)) - suite.Require().True(found) - cdp = suite.keeper.SynchronizeInterest(suite.ctx, cdp) - suite.Require().Equal(tc.args.expectedFeesPerCDP, cdp.AccumulatedFees) - suite.Require().Equal(tc.args.expectedTotalPrincipalPerCDP, cdp.GetTotalPrincipal()) - suite.Require().Equal(tc.args.expectedFeesUpdatedTime, cdp.FeesUpdated) - sumOfCDPPrincipal = sumOfCDPPrincipal.Add(cdp.GetTotalPrincipal().Amount) - } - - suite.Require().Equal(tc.args.expectedSumOfCDPPrincipal, sumOfCDPPrincipal) - }) - } -} - -// TestSynchronizeInterest tests the functionality of synchronizing the accumulated interest for CDPs -func (suite *InterestTestSuite) TestCalculateCDPInterest() { - type args struct { - ctype string - initialTime time.Time - initialCollateral sdk.Coin - initialPrincipal sdk.Coin - timeElapsed int - expectedFees sdk.Coin - } - - type test struct { - name string - args args - } - - oneYearInSeconds := 31536000 - testCases := []test{ - { - "1 year", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 100000000000), - timeElapsed: oneYearInSeconds, - expectedFees: c("usdx", 5000000000), - }, - }, - { - "1 month", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 100000000000), - timeElapsed: 86400 * 30, - expectedFees: c("usdx", 401820189), - }, - }, - { - "7 seconds", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 100000000000), - timeElapsed: 7, - expectedFees: c("usdx", 1083), - }, - }, - { - "7 seconds - fees round to zero", - args{ - ctype: "bnb-a", - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialCollateral: c("bnb", 1000000000), - initialPrincipal: c("usdx", 10000000), - timeElapsed: 7, - expectedFees: c("usdx", 0), - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - suite.ctx = suite.ctx.WithBlockTime(tc.args.initialTime) - - // setup account state - _, addrs := app.GeneratePrivKeyAddressPairs(1) - ak := suite.app.GetAccountKeeper() - // setup the first account - acc := ak.NewAccountWithAddress(suite.ctx, addrs[0]) - ak.SetAccount(suite.ctx, acc) - bk := suite.app.GetBankKeeper() - err := bk.MintCoins(suite.ctx, types.ModuleName, cs(tc.args.initialCollateral)) - suite.Require().NoError(err) - err = bk.SendCoinsFromModuleToAccount(suite.ctx, types.ModuleName, addrs[0], cs(tc.args.initialCollateral)) - suite.Require().NoError(err) - - // setup pricefeed - pk := suite.app.GetPriceFeedKeeper() - _, err = pk.SetPrice(suite.ctx, sdk.AccAddress{}, "bnb:usd", d("17.25"), tc.args.initialTime.Add(time.Duration(int(time.Second)*tc.args.timeElapsed))) - suite.Require().NoError(err) - - // setup cdp state - suite.keeper.SetPreviousAccrualTime(suite.ctx, tc.args.ctype, suite.ctx.BlockTime()) - suite.keeper.SetInterestFactor(suite.ctx, tc.args.ctype, sdk.OneDec()) - err = suite.keeper.AddCdp(suite.ctx, addrs[0], tc.args.initialCollateral, tc.args.initialPrincipal, tc.args.ctype) - suite.Require().NoError(err) - - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - err = suite.keeper.AccumulateInterest(suite.ctx, tc.args.ctype) - suite.Require().NoError(err) - - cdp, found := suite.keeper.GetCDP(suite.ctx, tc.args.ctype, 1) - suite.Require().True(found) - - newInterest := suite.keeper.CalculateNewInterest(suite.ctx, cdp) - - suite.Require().Equal(tc.args.expectedFees, newInterest) - }) - } -} - -func (suite *InterestTestSuite) TestSyncInterestForRiskyCDPs() { - type args struct { - ctype string - numberCdps int - slice int - initialCollateral sdk.Coin - minPrincipal sdk.Coin - principalIncrement sdk.Coin - initialTime time.Time - timeElapsed int - expectedCDPs int - } - - type test struct { - name string - args args - } - - oneYearInSeconds := 31536000 - testCases := []test{ - { - "1 year", - args{ - ctype: "bnb-a", - numberCdps: 20, - slice: 10, - initialCollateral: c("bnb", 100000000000), - minPrincipal: c("usdx", 100000000), - principalIncrement: c("usdx", 10000000), - initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - timeElapsed: oneYearInSeconds, - expectedCDPs: 10, - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - suite.ctx = suite.ctx.WithBlockTime(tc.args.initialTime) - // setup account state - _, addrs := app.GeneratePrivKeyAddressPairs(tc.args.numberCdps) - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - for _, addr := range addrs { - acc := ak.NewAccountWithAddress(suite.ctx, addr) - ak.SetAccount(suite.ctx, acc) - err := bk.MintCoins(suite.ctx, types.ModuleName, cs(tc.args.initialCollateral)) - suite.Require().NoError(err) - err = bk.SendCoinsFromModuleToAccount(suite.ctx, types.ModuleName, addr, cs(tc.args.initialCollateral)) - suite.Require().NoError(err) - } - // setup pricefeed - pk := suite.app.GetPriceFeedKeeper() - _, err := pk.SetPrice(suite.ctx, sdk.AccAddress{}, "bnb:usd", d("20.0"), tc.args.initialTime.Add(time.Duration(int(time.Second)*tc.args.timeElapsed))) - suite.Require().NoError(err) - - // setup cdp state - suite.keeper.SetPreviousAccrualTime(suite.ctx, tc.args.ctype, suite.ctx.BlockTime()) - suite.keeper.SetInterestFactor(suite.ctx, tc.args.ctype, sdk.OneDec()) - for j, addr := range addrs { - initialPrincipal := tc.args.minPrincipal.Add(c("usdx", int64(j)*tc.args.principalIncrement.Amount.Int64())) - err := suite.keeper.AddCdp(suite.ctx, addr, tc.args.initialCollateral, initialPrincipal, tc.args.ctype) - suite.Require().NoError(err) - } - - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - err = suite.keeper.AccumulateInterest(suite.ctx, tc.args.ctype) - suite.Require().NoError(err) - - err = suite.keeper.SynchronizeInterestForRiskyCDPs(suite.ctx, i(int64(tc.args.slice)), sdk.MaxSortableDec, tc.args.ctype) - suite.Require().NoError(err) - - cdpsUpdatedCount := 0 - - for _, addr := range addrs { - cdp, found := suite.keeper.GetCdpByOwnerAndCollateralType(suite.ctx, addr, tc.args.ctype) - suite.Require().True(found) - if cdp.FeesUpdated.Equal(suite.ctx.BlockTime()) { - cdpsUpdatedCount += 1 - } - } - suite.Require().Equal(tc.args.expectedCDPs, cdpsUpdatedCount) - }) - } -} - -func TestInterestTestSuite(t *testing.T) { - suite.Run(t, new(InterestTestSuite)) -} diff --git a/x/cdp/keeper/keeper.go b/x/cdp/keeper/keeper.go deleted file mode 100644 index 22f56d7e..00000000 --- a/x/cdp/keeper/keeper.go +++ /dev/null @@ -1,223 +0,0 @@ -package keeper - -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" - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - - "github.com/0glabs/0g-chain/x/cdp/types" -) - -// Keeper keeper for the cdp module -type Keeper struct { - key storetypes.StoreKey - cdc codec.Codec - paramSubspace paramtypes.Subspace - pricefeedKeeper types.PricefeedKeeper - auctionKeeper types.AuctionKeeper - bankKeeper types.BankKeeper - accountKeeper types.AccountKeeper - hooks types.CDPHooks - maccPerms map[string][]string -} - -// NewKeeper creates a new keeper -func NewKeeper(cdc codec.Codec, key storetypes.StoreKey, paramstore paramtypes.Subspace, pfk types.PricefeedKeeper, - ak types.AuctionKeeper, bk types.BankKeeper, ack types.AccountKeeper, maccs map[string][]string, -) Keeper { - if !paramstore.HasKeyTable() { - paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) - } - - return Keeper{ - key: key, - cdc: cdc, - paramSubspace: paramstore, - pricefeedKeeper: pfk, - auctionKeeper: ak, - bankKeeper: bk, - accountKeeper: ack, - hooks: nil, - maccPerms: maccs, - } -} - -// SetHooks adds hooks to the keeper. -func (k *Keeper) SetHooks(hooks types.CDPHooks) *Keeper { - if k.hooks != nil { - panic("cannot set cdp hooks twice") - } - k.hooks = hooks - return k -} - -// CdpDenomIndexIterator returns an sdk.Iterator for all cdps with matching collateral denom -func (k Keeper) CdpDenomIndexIterator(ctx sdk.Context, collateralType string) sdk.Iterator { - store := prefix.NewStore(ctx.KVStore(k.key), types.CdpKeyPrefix) - return sdk.KVStorePrefixIterator(store, types.DenomIterKey(collateralType)) -} - -// CdpCollateralRatioIndexIterator returns an sdk.Iterator for all cdps that have collateral denom -// matching denom and collateral:debt ratio LESS THAN targetRatio -func (k Keeper) CdpCollateralRatioIndexIterator(ctx sdk.Context, collateralType string, targetRatio sdk.Dec) sdk.Iterator { - store := prefix.NewStore(ctx.KVStore(k.key), types.CollateralRatioIndexPrefix) - return store.Iterator(types.CollateralRatioIterKey(collateralType, sdk.ZeroDec()), types.CollateralRatioIterKey(collateralType, targetRatio)) -} - -// IterateAllCdps iterates over all cdps and performs a callback function -func (k Keeper) IterateAllCdps(ctx sdk.Context, cb func(cdp types.CDP) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.CdpKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var cdp types.CDP - k.cdc.MustUnmarshal(iterator.Value(), &cdp) - - if cb(cdp) { - break - } - } -} - -// IterateCdpsByCollateralType iterates over cdps with matching denom and performs a callback function -func (k Keeper) IterateCdpsByCollateralType(ctx sdk.Context, collateralType string, cb func(cdp types.CDP) (stop bool)) { - iterator := k.CdpDenomIndexIterator(ctx, collateralType) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var cdp types.CDP - k.cdc.MustUnmarshal(iterator.Value(), &cdp) - if cb(cdp) { - break - } - } -} - -// IterateCdpsByCollateralRatio iterate over cdps with collateral denom equal to denom and -// collateral:debt ratio LESS THAN targetRatio and performs a callback function. -func (k Keeper) IterateCdpsByCollateralRatio(ctx sdk.Context, collateralType string, targetRatio sdk.Dec, cb func(cdp types.CDP) (stop bool)) { - iterator := k.CdpCollateralRatioIndexIterator(ctx, collateralType, targetRatio) - - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - _, id, _ := types.SplitCollateralRatioKey(iterator.Key()) - cdp, found := k.GetCDP(ctx, collateralType, id) - if !found { - panic(fmt.Sprintf("cdp %d does not exist", id)) - } - if cb(cdp) { - break - } - - } -} - -// 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 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) - count = count.Add(sdk.OneInt()) - return count.GTE(cutoffCount) - }) - return cdps -} - -// GetPreviousAccrualTime returns the last time an individual market accrued interest -func (k Keeper) GetPreviousAccrualTime(ctx sdk.Context, ctype string) (time.Time, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousAccrualTimePrefix) - bz := store.Get([]byte(ctype)) - if bz == nil { - return time.Time{}, false - } - var previousAccrualTime time.Time - if err := previousAccrualTime.UnmarshalBinary(bz); err != nil { - panic(err) - } - return previousAccrualTime, true -} - -// SetPreviousAccrualTime sets the most recent accrual time for a particular market -func (k Keeper) SetPreviousAccrualTime(ctx sdk.Context, ctype string, previousAccrualTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousAccrualTimePrefix) - bz, err := previousAccrualTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set([]byte(ctype), bz) -} - -// GetInterestFactor returns the current interest factor for an individual collateral type -func (k Keeper) GetInterestFactor(ctx sdk.Context, ctype string) (sdk.Dec, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.InterestFactorPrefix) - bz := store.Get([]byte(ctype)) - if bz == nil { - return sdk.ZeroDec(), false - } - var interestFactor sdk.Dec - if err := interestFactor.Unmarshal(bz); err != nil { - panic(err) - } - return interestFactor, true -} - -// SetInterestFactor sets the current interest factor for an individual collateral type -func (k Keeper) SetInterestFactor(ctx sdk.Context, ctype string, interestFactor sdk.Dec) { - store := prefix.NewStore(ctx.KVStore(k.key), types.InterestFactorPrefix) - bz, err := interestFactor.Marshal() - if err != nil { - panic(err) - } - store.Set([]byte(ctype), bz) -} - -// IncrementTotalPrincipal increments the total amount of debt that has been drawn with that collateral type -func (k Keeper) IncrementTotalPrincipal(ctx sdk.Context, collateralType string, principal sdk.Coin) { - total := k.GetTotalPrincipal(ctx, collateralType, principal.Denom) - total = total.Add(principal.Amount) - k.SetTotalPrincipal(ctx, collateralType, principal.Denom, total) -} - -// DecrementTotalPrincipal decrements the total amount of debt that has been drawn for a particular collateral type -func (k Keeper) DecrementTotalPrincipal(ctx sdk.Context, collateralType string, principal sdk.Coin) { - total := k.GetTotalPrincipal(ctx, collateralType, principal.Denom) - // NOTE: negative total principal can happen in tests due to rounding errors - // in fee calculation - total = sdk.MaxInt(total.Sub(principal.Amount), sdk.ZeroInt()) - k.SetTotalPrincipal(ctx, collateralType, principal.Denom, total) -} - -// 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 sdkmath.Int) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PrincipalKeyPrefix) - bz := store.Get([]byte(collateralType + principalDenom)) - if bz == nil { - k.SetTotalPrincipal(ctx, collateralType, principalDenom, sdk.ZeroInt()) - return sdk.ZeroInt() - } - if err := total.Unmarshal(bz); err != nil { - panic(err) - } - return total -} - -// 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 sdkmath.Int) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PrincipalKeyPrefix) - _, found := k.GetCollateral(ctx, collateralType) - if !found { - panic(fmt.Sprintf("collateral not found: %s", collateralType)) - } - bz, err := total.Marshal() - if err != nil { - panic(err) - } - store.Set([]byte(collateralType+principalDenom), bz) -} diff --git a/x/cdp/keeper/keeper_bench_test.go b/x/cdp/keeper/keeper_bench_test.go deleted file mode 100644 index 896e55fc..00000000 --- a/x/cdp/keeper/keeper_bench_test.go +++ /dev/null @@ -1,147 +0,0 @@ -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" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/cdp/keeper" - "github.com/0glabs/0g-chain/x/cdp/types" -) - -// saving the result to a module level variable ensures the compiler doesn't optimize the test away -var coinsResult sdk.Coins -var coinResult sdk.Coin - -// Note - the iteration benchmarks take a long time to stabilize, to get stable results use: -// go test -benchmem -bench ^(BenchmarkAccountIteration)$ -benchtime 60s -timeout 2h -// go test -benchmem -bench ^(BenchmarkCdpIteration)$ -benchtime 60s -timeout 2h - -func BenchmarkAccountIteration(b *testing.B) { - benchmarks := []struct { - name string - numberAccounts int - coins bool - }{ - {name: "10000 Accounts, No Coins", numberAccounts: 10000, coins: false}, - {name: "100000 Accounts, No Coins", numberAccounts: 100000, coins: false}, - {name: "1000000 Accounts, No Coins", numberAccounts: 1000000, coins: false}, - {name: "10000 Accounts, With Coins", numberAccounts: 10000, coins: true}, - {name: "100000 Accounts, With Coins", numberAccounts: 100000, coins: true}, - {name: "1000000 Accounts, With Coins", numberAccounts: 1000000, coins: true}, - } - coins := sdk.Coins{ - sdk.NewCoin("xrp", sdkmath.NewInt(1000000000)), - sdk.NewCoin("usdx", sdkmath.NewInt(1000000000)), - } - - for _, bm := range benchmarks { - b.Run(bm.name, func(b *testing.B) { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - ak := tApp.GetAccountKeeper() - bk := tApp.GetBankKeeper() - - tApp.InitializeFromGenesisStates() - for i := 0; i < bm.numberAccounts; i++ { - arr := []byte{byte((i & 0xFF0000) >> 16), byte((i & 0xFF00) >> 8), byte(i & 0xFF)} - addr := sdk.AccAddress(arr) - acc := ak.NewAccountWithAddress(ctx, addr) - if bm.coins { - if err := tApp.FundAccount(ctx, acc.GetAddress(), coins); err != nil { - panic(err) - } - } - ak.SetAccount(ctx, acc) - } - // reset timer ensures we don't count setup time - b.ResetTimer() - for i := 0; i < b.N; i++ { - ak.IterateAccounts(ctx, - func(acc authtypes.AccountI) (stop bool) { - coins := bk.GetAllBalances(ctx, acc.GetAddress()) - coinsResult = coins - return false - }) - } - }) - } -} - -func createCdps(n int) (app.TestApp, sdk.Context, keeper.Keeper) { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - cdc := tApp.AppCodec() - - _, addrs := app.GeneratePrivKeyAddressPairs(n) - coins := cs(c("btc", 100000000)) - authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs) - tApp.InitializeFromGenesisStates( - authGS, - NewPricefeedGenStateMulti(cdc), - NewCDPGenStateMulti(cdc), - ) - cdpKeeper := tApp.GetCDPKeeper() - for i := 0; i < n; i++ { - err := cdpKeeper.AddCdp(ctx, addrs[i], coins[0], c("usdx", 100000000), "btc-a") - if err != nil { - panic("failed to create cdp") - } - } - return tApp, ctx, cdpKeeper -} - -func BenchmarkCdpIteration(b *testing.B) { - benchmarks := []struct { - name string - numberCdps int - }{ - {"1000 Cdps", 1000}, - {"10000 Cdps", 10000}, - {"100000 Cdps", 100000}, - } - for _, bm := range benchmarks { - b.Run(bm.name, func(b *testing.B) { - _, ctx, cdpKeeper := createCdps(bm.numberCdps) - b.ResetTimer() - for i := 0; i < b.N; i++ { - cdpKeeper.IterateAllCdps(ctx, func(c types.CDP) (stop bool) { - coinResult = c.Principal - return false - }) - } - }) - } -} - -var errResult error - -func BenchmarkCdpCreation(b *testing.B) { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - cdc := tApp.AppCodec() - - _, addrs := app.GeneratePrivKeyAddressPairs(b.N) - coins := cs(c("btc", 100000000)) - authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs) - tApp.InitializeFromGenesisStates( - authGS, - NewPricefeedGenStateMulti(cdc), - NewCDPGenStateMulti(cdc), - ) - cdpKeeper := tApp.GetCDPKeeper() - b.ResetTimer() - for i := 0; i < b.N; i++ { - err := cdpKeeper.AddCdp(ctx, addrs[i], coins[0], c("usdx", 100000000), "btc-a") - if err != nil { - b.Error("unexpected error") - } - errResult = err - } -} diff --git a/x/cdp/keeper/keeper_test.go b/x/cdp/keeper/keeper_test.go deleted file mode 100644 index 1b71c54f..00000000 --- a/x/cdp/keeper/keeper_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package keeper_test - -import ( - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/cdp/keeper" -) - -type KeeperTestSuite struct { - suite.Suite - - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context -} - -func (suite *KeeperTestSuite) SetupTest() { - suite.ResetChain() -} - -func (suite *KeeperTestSuite) ResetChain() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - keeper := tApp.GetCDPKeeper() - - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper -} diff --git a/x/cdp/keeper/migrations.go b/x/cdp/keeper/migrations.go deleted file mode 100644 index 9dc818cf..00000000 --- a/x/cdp/keeper/migrations.go +++ /dev/null @@ -1,23 +0,0 @@ -package keeper - -import ( - v2 "github.com/0glabs/0g-chain/x/cdp/migrations/v2" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// Migrator is a struct for handling in-place store migrations. -type Migrator struct { - keeper Keeper -} - -// NewMigrator returns a new Migrator. -func NewMigrator(keeper Keeper) Migrator { - return Migrator{ - keeper: keeper, - } -} - -// Migrate1to2 migrates from version 1 to 2. -func (m Migrator) Migrate1to2(ctx sdk.Context) error { - return v2.MigrateStore(ctx, m.keeper.paramSubspace) -} diff --git a/x/cdp/keeper/msg_server.go b/x/cdp/keeper/msg_server.go deleted file mode 100644 index 20d68fc2..00000000 --- a/x/cdp/keeper/msg_server.go +++ /dev/null @@ -1,175 +0,0 @@ -package keeper - -import ( - "context" - - "github.com/0glabs/0g-chain/x/cdp/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the cdp MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -func (k msgServer) CreateCDP(goCtx context.Context, msg *types.MsgCreateCDP) (*types.MsgCreateCDPResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - err = k.keeper.AddCdp(ctx, sender, msg.Collateral, msg.Principal, msg.CollateralType) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - ), - ) - - id, _ := k.keeper.GetCdpID(ctx, sender, msg.CollateralType) - return &types.MsgCreateCDPResponse{CdpID: id}, nil -} - -func (k msgServer) Deposit(goCtx context.Context, msg *types.MsgDeposit) (*types.MsgDepositResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - owner, err := sdk.AccAddressFromBech32(msg.Owner) - if err != nil { - return nil, err - } - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - - err = k.keeper.DepositCollateral(ctx, owner, depositor, msg.Collateral, msg.CollateralType) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Depositor), - ), - ) - return &types.MsgDepositResponse{}, nil -} - -func (k msgServer) Withdraw(goCtx context.Context, msg *types.MsgWithdraw) (*types.MsgWithdrawResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - owner, err := sdk.AccAddressFromBech32(msg.Owner) - if err != nil { - return nil, err - } - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - - err = k.keeper.WithdrawCollateral(ctx, owner, depositor, msg.Collateral, msg.CollateralType) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Depositor), - ), - ) - return &types.MsgWithdrawResponse{}, nil -} - -func (k msgServer) DrawDebt(goCtx context.Context, msg *types.MsgDrawDebt) (*types.MsgDrawDebtResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - err = k.keeper.AddPrincipal(ctx, sender, msg.CollateralType, msg.Principal) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - ), - ) - return &types.MsgDrawDebtResponse{}, nil -} - -func (k msgServer) RepayDebt(goCtx context.Context, msg *types.MsgRepayDebt) (*types.MsgRepayDebtResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - err = k.keeper.RepayPrincipal(ctx, sender, msg.CollateralType, msg.Payment) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - ), - ) - return &types.MsgRepayDebtResponse{}, nil -} - -func (k msgServer) Liquidate(goCtx context.Context, msg *types.MsgLiquidate) (*types.MsgLiquidateResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - keeper, err := sdk.AccAddressFromBech32(msg.Keeper) - if err != nil { - return nil, err - } - - borrower, err := sdk.AccAddressFromBech32(msg.Borrower) - if err != nil { - return nil, err - } - - err = k.keeper.AttemptKeeperLiquidation(ctx, keeper, borrower, msg.CollateralType) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Keeper), - ), - ) - return &types.MsgLiquidateResponse{}, nil -} diff --git a/x/cdp/keeper/params.go b/x/cdp/keeper/params.go deleted file mode 100644 index fab467fc..00000000 --- a/x/cdp/keeper/params.go +++ /dev/null @@ -1,101 +0,0 @@ -package keeper - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/cdp/types" -) - -// GetParams returns the params from the store -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - var p types.Params - k.paramSubspace.GetParamSetIfExists(ctx, &p) - return p -} - -// SetParams sets params on the store -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSubspace.SetParamSet(ctx, ¶ms) -} - -// GetCollateral returns the collateral param with corresponding denom -func (k Keeper) GetCollateral(ctx sdk.Context, collateralType string) (types.CollateralParam, bool) { - params := k.GetParams(ctx) - for _, cp := range params.CollateralParams { - if cp.Type == collateralType { - return cp, true - } - } - return types.CollateralParam{}, false -} - -// GetCollateralTypes returns an array of collateral types -func (k Keeper) GetCollateralTypes(ctx sdk.Context) []string { - params := k.GetParams(ctx) - var denoms []string - for _, cp := range params.CollateralParams { - denoms = append(denoms, cp.Type) - } - return denoms -} - -// GetDebtParam returns the debt param with matching denom -func (k Keeper) GetDebtParam(ctx sdk.Context, denom string) (types.DebtParam, bool) { - dp := k.GetParams(ctx).DebtParam - if dp.Denom == denom { - return dp, true - } - return types.DebtParam{}, false -} - -func (k Keeper) getSpotMarketID(ctx sdk.Context, collateralType string) string { - cp, found := k.GetCollateral(ctx, collateralType) - if !found { - panic(fmt.Sprintf("collateral not found: %s", collateralType)) - } - return cp.SpotMarketID -} - -func (k Keeper) getliquidationMarketID(ctx sdk.Context, collateralType string) string { - cp, found := k.GetCollateral(ctx, collateralType) - if !found { - panic(fmt.Sprintf("collateral not found: %s", collateralType)) - } - return cp.LiquidationMarketID -} - -func (k Keeper) getLiquidationRatio(ctx sdk.Context, collateralType string) sdk.Dec { - cp, found := k.GetCollateral(ctx, collateralType) - if !found { - panic(fmt.Sprintf("collateral not found: %s", collateralType)) - } - return cp.LiquidationRatio -} - -func (k Keeper) getLiquidationPenalty(ctx sdk.Context, collateralType string) sdk.Dec { - cp, found := k.GetCollateral(ctx, collateralType) - if !found { - panic(fmt.Sprintf("collateral not found: %s", collateralType)) - } - return cp.LiquidationPenalty -} - -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)) - } - return cp.AuctionSize -} - -// GetFeeRate returns the per second fee rate for the input denom -func (k Keeper) getFeeRate(ctx sdk.Context, collateralType string) (fee sdk.Dec) { - collalateralParam, found := k.GetCollateral(ctx, collateralType) - if !found { - panic(fmt.Sprintf("could not get fee rate for %s, collateral not found", collateralType)) - } - return collalateralParam.StabilityFee -} diff --git a/x/cdp/keeper/querier.go b/x/cdp/keeper/querier.go deleted file mode 100644 index 8f5b83d9..00000000 --- a/x/cdp/keeper/querier.go +++ /dev/null @@ -1,154 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/client" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/cdp/types" -) - -// FilterCDPs queries the store for all CDPs that match query params -func FilterCDPs(ctx sdk.Context, k Keeper, params types.QueryCdpsParams) (types.AugmentedCDPs, error) { - var matchCollateralType, matchOwner, matchID, matchRatio types.CDPs - - // match cdp owner (if supplied) - if len(params.Owner) > 0 { - denoms := k.GetCollateralTypes(ctx) - for _, denom := range denoms { - cdp, found := k.GetCdpByOwnerAndCollateralType(ctx, params.Owner, denom) - if found { - matchOwner = append(matchOwner, cdp) - } - } - } - - // match cdp collateral denom (if supplied) - if len(params.CollateralType) > 0 { - // if owner is specified only iterate over already matched cdps for efficiency - if len(params.Owner) > 0 { - for _, cdp := range matchOwner { - if cdp.Type == params.CollateralType { - matchCollateralType = append(matchCollateralType, cdp) - } - } - } else { - _, found := k.GetCollateral(ctx, params.CollateralType) - if !found { - return nil, fmt.Errorf("invalid collateral type") - } - matchCollateralType = k.GetAllCdpsByCollateralType(ctx, params.CollateralType) - } - } - - // match cdp ID (if supplied) - if params.ID != 0 { - denoms := k.GetCollateralTypes(ctx) - for _, denom := range denoms { - cdp, found := k.GetCDP(ctx, denom, params.ID) - if found { - matchID = append(matchID, cdp) - } - } - } - - // match cdp ratio (if supplied) - if !params.Ratio.IsNil() && params.Ratio.GT(sdk.ZeroDec()) { - denoms := k.GetCollateralTypes(ctx) - for _, denom := range denoms { - ratio, err := k.CalculateCollateralizationRatioFromAbsoluteRatio(ctx, denom, params.Ratio, "liquidation") - if err != nil { - continue - } - cdpsUnderRatio := k.GetAllCdpsByCollateralTypeAndRatio(ctx, denom, ratio) - matchRatio = append(matchRatio, cdpsUnderRatio...) - } - } - - var commonCDPs types.CDPs - // If no params specified, fetch all CDPs - if params.CollateralType == "" && len(params.Owner) == 0 && params.ID == 0 && params.Ratio.Equal(sdk.ZeroDec()) { - commonCDPs = k.GetAllCdps(ctx) - } - - // Find the intersection of any matched CDPs - if params.CollateralType != "" { - if len(matchCollateralType) == 0 { - return nil, nil - } - - commonCDPs = matchCollateralType - } - - if len(params.Owner) > 0 { - if len(matchCollateralType) > 0 { - if len(commonCDPs) > 0 { - commonCDPs = FindIntersection(commonCDPs, matchOwner) - } else { - commonCDPs = matchOwner - } - } else { - commonCDPs = matchOwner - } - } - - if params.ID != 0 { - if len(matchID) == 0 { - return nil, nil - } - - if len(commonCDPs) > 0 { - commonCDPs = FindIntersection(commonCDPs, matchID) - } else { - commonCDPs = matchID - } - } - - if !params.Ratio.IsNil() && params.Ratio.GT(sdk.ZeroDec()) { - if len(matchRatio) == 0 { - return nil, nil - } - - if len(commonCDPs) > 0 { - commonCDPs = FindIntersection(commonCDPs, matchRatio) - } else { - commonCDPs = matchRatio - } - } - - // Load augmented CDPs - var augmentedCDPs types.AugmentedCDPs - for _, cdp := range commonCDPs { - augmentedCDP := k.LoadAugmentedCDP(ctx, cdp) - augmentedCDPs = append(augmentedCDPs, augmentedCDP) - } - - // Apply page and limit params - start, end := client.Paginate(len(augmentedCDPs), params.Page, params.Limit, 100) - if start < 0 || end < 0 { - return nil, nil - } - - return augmentedCDPs[start:end], nil -} - -// FindIntersection finds the intersection of two CDP arrays in linear time complexity O(n + n) -func FindIntersection(x types.CDPs, y types.CDPs) types.CDPs { - cdpSet := make(types.CDPs, 0) - cdpMap := make(map[uint64]bool) - - for i := 0; i < len(x); i++ { - cdp := x[i] - cdpMap[cdp.ID] = true - } - - for i := 0; i < len(y); i++ { - cdp := y[i] - if _, found := cdpMap[cdp.ID]; found { - cdpSet = append(cdpSet, cdp) - } - } - - return cdpSet -} diff --git a/x/cdp/keeper/seize.go b/x/cdp/keeper/seize.go deleted file mode 100644 index 856ad2f2..00000000 --- a/x/cdp/keeper/seize.go +++ /dev/null @@ -1,170 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/cdp/types" -) - -// AttemptKeeperLiquidation liquidates the cdp with the input collateral type and owner if it is below the required collateralization ratio -// if the cdp is liquidated, the keeper that sent the transaction is rewarded a percentage of the collateral according to that collateral types' -// keeper reward percentage. -func (k Keeper) AttemptKeeperLiquidation(ctx sdk.Context, keeper, owner sdk.AccAddress, collateralType string) error { - cdp, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType) - if !found { - return errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", owner, collateralType) - } - k.hooks.BeforeCDPModified(ctx, cdp) - cdp = k.SynchronizeInterest(ctx, cdp) - - err := k.ValidateLiquidation(ctx, cdp.Collateral, cdp.Type, cdp.Principal, cdp.AccumulatedFees) - if err != nil { - return err - } - cdp, err = k.payoutKeeperLiquidationReward(ctx, keeper, cdp) - if err != nil { - return err - } - return k.SeizeCollateral(ctx, cdp) -} - -// SeizeCollateral liquidates the collateral in the input cdp. -// the following operations are performed: -// 1. Collateral for all deposits is sent from the cdp module to the liquidator module account -// 2. The liquidation penalty is applied -// 3. Debt coins are sent from the cdp module to the liquidator module account -// 4. The total amount of principal outstanding for that collateral type is decremented -// (this is the equivalent of saying that fees are no longer accumulated by a cdp once it gets liquidated) -func (k Keeper) SeizeCollateral(ctx sdk.Context, cdp types.CDP) error { - // Calculate the previous collateral ratio - oldCollateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Type, cdp.GetTotalPrincipal()) - - // Move debt coins from cdp to liquidator account - deposits := k.GetDeposits(ctx, cdp.ID) - debt := cdp.GetTotalPrincipal().Amount - modAccountDebt := k.getModAccountDebt(ctx, types.ModuleName) - debt = sdk.MinInt(debt, modAccountDebt) - debtCoin := sdk.NewCoin(k.GetDebtDenom(ctx), debt) - err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, types.LiquidatorMacc, sdk.NewCoins(debtCoin)) - if err != nil { - return err - } - - // liquidate deposits and send collateral from cdp to liquidator - for _, dep := range deposits { - if err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, types.LiquidatorMacc, sdk.NewCoins(dep.Amount)); err != nil { - return err - } - - k.DeleteDeposit(ctx, dep.CdpID, dep.Depositor) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeCdpLiquidation, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf("%d", cdp.ID)), - sdk.NewAttribute(types.AttributeKeyDeposit, dep.String()), - ), - ) - } - - err = k.AuctionCollateral(ctx, deposits, cdp.Type, debt, cdp.Principal.Denom) - if err != nil { - return err - } - - // Decrement total principal for this collateral type - coinsToDecrement := cdp.GetTotalPrincipal() - k.DecrementTotalPrincipal(ctx, cdp.Type, coinsToDecrement) - - // Delete CDP from state - k.RemoveCdpOwnerIndex(ctx, cdp) - k.RemoveCdpCollateralRatioIndex(ctx, cdp.Type, cdp.ID, oldCollateralToDebtRatio) - return k.DeleteCDP(ctx, cdp) -} - -// 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 sdkmath.Int) error { - price, err := k.pricefeedKeeper.GetCurrentPrice(ctx, marketID) - if err != nil { - return err - } - priceDivLiqRatio := price.Price.Quo(liquidationRatio) - if priceDivLiqRatio.IsZero() { - priceDivLiqRatio = sdk.SmallestDec() - } - // price = $0.5 - // liquidation ratio = 1.5 - // normalizedRatio = (1/(0.5/1.5)) = 3 - normalizedRatio := sdk.OneDec().Quo(priceDivLiqRatio) - cdpsToLiquidate := k.GetSliceOfCDPsByRatioAndType(ctx, count, normalizedRatio, collateralType) - for _, c := range cdpsToLiquidate { - k.hooks.BeforeCDPModified(ctx, c) - err := k.SeizeCollateral(ctx, c) - if err != nil { - return err - } - } - return nil -} - -// ApplyLiquidationPenalty multiplies the input debt amount by the liquidation penalty -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() -} - -// ValidateLiquidation validate that adding the input principal puts the cdp below the liquidation ratio -func (k Keeper) ValidateLiquidation(ctx sdk.Context, collateral sdk.Coin, collateralType string, principal sdk.Coin, fees sdk.Coin) error { - collateralizationRatio, err := k.CalculateCollateralizationRatio(ctx, collateral, collateralType, principal, fees, liquidation) - if err != nil { - return err - } - liquidationRatio := k.getLiquidationRatio(ctx, collateralType) - if collateralizationRatio.GTE(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) sdkmath.Int { - macc := k.accountKeeper.GetModuleAccount(ctx, accountName) - return k.bankKeeper.GetBalance(ctx, macc.GetAddress(), k.GetDebtDenom(ctx)).Amount -} - -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{}, errorsmod.Wrapf(types.ErrInvalidCollateral, "%s", cdp.Type) - } - reward := sdk.NewDecFromInt(cdp.Collateral.Amount).Mul(collateralParam.KeeperRewardPercentage).RoundInt() - rewardCoin := sdk.NewCoin(cdp.Collateral.Denom, reward) - paidReward := false - deposits := k.GetDeposits(ctx, cdp.ID) - for _, dep := range deposits { - if dep.Amount.IsGTE(rewardCoin) { - dep.Amount = dep.Amount.Sub(rewardCoin) - k.SetDeposit(ctx, dep) - paidReward = true - break - } - } - if !paidReward { - return cdp, nil - } - err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, keeper, sdk.NewCoins(rewardCoin)) - if err != nil { - return types.CDP{}, err - } - cdp.Collateral = cdp.Collateral.Sub(rewardCoin) - ratio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Type, cdp.GetTotalPrincipal()) - err = k.UpdateCdpAndCollateralRatioIndex(ctx, cdp, ratio) - if err != nil { - return types.CDP{}, err - } - return cdp, nil -} diff --git a/x/cdp/keeper/seize_test.go b/x/cdp/keeper/seize_test.go deleted file mode 100644 index 566dac42..00000000 --- a/x/cdp/keeper/seize_test.go +++ /dev/null @@ -1,576 +0,0 @@ -package keeper_test - -import ( - "errors" - "fmt" - "math/rand" - "strings" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" - - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/0glabs/0g-chain/app" - auctiontypes "github.com/0glabs/0g-chain/x/auction/types" - "github.com/0glabs/0g-chain/x/cdp/keeper" - "github.com/0glabs/0g-chain/x/cdp/types" -) - -type SeizeTestSuite struct { - suite.Suite - - keeper keeper.Keeper - addrs []sdk.AccAddress - app app.TestApp - cdps types.CDPs - ctx sdk.Context - liquidations liquidationTracker -} - -type liquidationTracker struct { - xrp []uint64 - btc []uint64 - debt int64 -} - -func (suite *SeizeTestSuite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now(), ChainID: app.TestChainId}) - tracker := liquidationTracker{} - coins := cs(c("btc", 100000000), c("xrp", 10000000000)) - _, addrs := app.GeneratePrivKeyAddressPairs(100) - - authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs) - tApp.InitializeFromGenesisStates( - authGS, - NewPricefeedGenStateMulti(tApp.AppCodec()), - NewCDPGenStateMulti(tApp.AppCodec()), - ) - suite.ctx = ctx - suite.app = tApp - suite.keeper = tApp.GetCDPKeeper() - suite.cdps = types.CDPs{} - suite.addrs = addrs - suite.liquidations = tracker -} - -func (suite *SeizeTestSuite) createCdps() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - cdps := make(types.CDPs, 100) - _, addrs := app.GeneratePrivKeyAddressPairs(100) - tracker := liquidationTracker{} - coins := cs(c("btc", 100000000), c("xrp", 10000000000)) - - authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs) - tApp.InitializeFromGenesisStates( - authGS, - NewPricefeedGenStateMulti(tApp.AppCodec()), - NewCDPGenStateMulti(tApp.AppCodec()), - ) - - suite.ctx = ctx - suite.app = tApp - suite.keeper = tApp.GetCDPKeeper() - randSource := rand.New(rand.NewSource(int64(777))) - for j := 0; j < 100; j++ { - collateral := "xrp" - amount := 10000000000 - debt := simulation.RandIntBetween(randSource, 750000000, 1249000000) - if j%2 == 0 { - collateral = "btc" - amount = 100000000 - debt = simulation.RandIntBetween(randSource, 2700000000, 5332000000) - if debt >= 4000000000 { - tracker.btc = append(tracker.btc, uint64(j+1)) - tracker.debt += int64(debt) - } - } else { - if debt >= 1000000000 { - tracker.xrp = append(tracker.xrp, uint64(j+1)) - tracker.debt += int64(debt) - } - } - err := suite.keeper.AddCdp(suite.ctx, addrs[j], c(collateral, int64(amount)), c("usdx", int64(debt)), collateral+"-a") - suite.NoError(err) - c, f := suite.keeper.GetCDP(suite.ctx, collateral+"-a", uint64(j+1)) - suite.True(f) - cdps[j] = c - } - - suite.cdps = cdps - suite.addrs = addrs - suite.liquidations = tracker -} - -func (suite *SeizeTestSuite) setPrice(price sdk.Dec, market string) { - pfKeeper := suite.app.GetPriceFeedKeeper() - - _, err := pfKeeper.SetPrice(suite.ctx, sdk.AccAddress{}, market, price, suite.ctx.BlockTime().Add(time.Hour*3)) - suite.NoError(err) - err = pfKeeper.SetCurrentPrices(suite.ctx, market) - suite.NoError(err) - pp, err := pfKeeper.GetCurrentPrice(suite.ctx, market) - suite.NoError(err) - suite.Equal(price, pp.Price) -} - -func (suite *SeizeTestSuite) TestSeizeCollateral() { - suite.createCdps() - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - - cdp, found := suite.keeper.GetCDP(suite.ctx, "xrp-a", uint64(2)) - suite.True(found) - - p := cdp.Principal.Amount - cl := cdp.Collateral.Amount - - tpb := suite.keeper.GetTotalPrincipal(suite.ctx, "xrp-a", "usdx") - err := suite.keeper.SeizeCollateral(suite.ctx, cdp) - suite.NoError(err) - - tpa := suite.keeper.GetTotalPrincipal(suite.ctx, "xrp-a", "usdx") - suite.Equal(tpb.Sub(tpa), p) - - auctionKeeper := suite.app.GetAuctionKeeper() - - _, found = auctionKeeper.GetAuction(suite.ctx, auctiontypes.DefaultNextAuctionID) - suite.True(found) - - auctionMacc := ak.GetModuleAccount(suite.ctx, auctiontypes.ModuleName) - suite.Equal(cs(c("debt", p.Int64()), c("xrp", cl.Int64())), bk.GetAllBalances(suite.ctx, auctionMacc.GetAddress())) - - acc := ak.GetAccount(suite.ctx, suite.addrs[1]) - suite.Equal(p.Int64(), bk.GetBalance(suite.ctx, acc.GetAddress(), "usdx").Amount.Int64()) - err = suite.keeper.WithdrawCollateral(suite.ctx, suite.addrs[1], suite.addrs[1], c("xrp", 10), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrCdpNotFound)) -} - -func (suite *SeizeTestSuite) TestSeizeCollateralMultiDeposit() { - suite.createCdps() - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - - _, found := suite.keeper.GetCDP(suite.ctx, "xrp-a", uint64(2)) - suite.True(found) - - err := suite.keeper.DepositCollateral(suite.ctx, suite.addrs[1], suite.addrs[0], c("xrp", 6999000000), "xrp-a") - suite.NoError(err) - - cdp, found := suite.keeper.GetCDP(suite.ctx, "xrp-a", uint64(2)) - suite.True(found) - - deposits := suite.keeper.GetDeposits(suite.ctx, cdp.ID) - suite.Equal(2, len(deposits)) - - p := cdp.Principal.Amount - cl := cdp.Collateral.Amount - tpb := suite.keeper.GetTotalPrincipal(suite.ctx, "xrp-a", "usdx") - err = suite.keeper.SeizeCollateral(suite.ctx, cdp) - suite.NoError(err) - - tpa := suite.keeper.GetTotalPrincipal(suite.ctx, "xrp-a", "usdx") - suite.Equal(tpb.Sub(tpa), p) - - auctionMacc := ak.GetModuleAccount(suite.ctx, auctiontypes.ModuleName) - suite.Equal(cs(c("debt", p.Int64()), c("xrp", cl.Int64())), bk.GetAllBalances(suite.ctx, auctionMacc.GetAddress())) - - acc := ak.GetAccount(suite.ctx, suite.addrs[1]) - suite.Equal(p.Int64(), bk.GetBalance(suite.ctx, acc.GetAddress(), "usdx").Amount.Int64()) - err = suite.keeper.WithdrawCollateral(suite.ctx, suite.addrs[1], suite.addrs[1], c("xrp", 10), "xrp-a") - suite.Require().True(errors.Is(err, types.ErrCdpNotFound)) -} - -func (suite *SeizeTestSuite) TestLiquidateCdps() { - suite.createCdps() - ak := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - acc := ak.GetModuleAccount(suite.ctx, types.ModuleName) - - originalXrpCollateral := bk.GetBalance(suite.ctx, acc.GetAddress(), "xrp").Amount - suite.setPrice(d("0.2"), "xrp:usd") - p, found := suite.keeper.GetCollateral(suite.ctx, "xrp-a") - suite.True(found) - - err := suite.keeper.LiquidateCdps(suite.ctx, "xrp:usd", "xrp-a", p.LiquidationRatio, p.CheckCollateralizationIndexCount) - suite.NoError(err) - - acc = ak.GetModuleAccount(suite.ctx, types.ModuleName) - finalXrpCollateral := bk.GetBalance(suite.ctx, acc.GetAddress(), "xrp").Amount - seizedXrpCollateral := originalXrpCollateral.Sub(finalXrpCollateral) - xrpLiquidations := int(seizedXrpCollateral.Quo(i(10000000000)).Int64()) - suite.Equal(10, xrpLiquidations) -} - -func (suite *SeizeTestSuite) TestApplyLiquidationPenalty() { - penalty := suite.keeper.ApplyLiquidationPenalty(suite.ctx, "xrp-a", i(1000)) - suite.Equal(i(50), penalty) - penalty = suite.keeper.ApplyLiquidationPenalty(suite.ctx, "btc-a", i(1000)) - suite.Equal(i(25), penalty) - penalty = suite.keeper.ApplyLiquidationPenalty(suite.ctx, "xrp-a", i(675760172)) - suite.Equal(i(33788009), penalty) - suite.Panics(func() { suite.keeper.ApplyLiquidationPenalty(suite.ctx, "lol-a", i(1000)) }) -} - -func (suite *SeizeTestSuite) TestKeeperLiquidation() { - type args struct { - ctype string - blockTime time.Time - initialPrice sdk.Dec - finalPrice sdk.Dec - finalTwapPrice sdk.Dec - collateral sdk.Coin - principal sdk.Coin - expectedKeeperCoins sdk.Coins // additional coins (if any) the borrower address should have after successfully liquidating position - expectedAuctions []auctiontypes.Auction // the auctions we should expect to find have been started - } - - type errArgs struct { - expectLiquidate bool - contains string - } - - type test struct { - name string - args args - errArgs errArgs - } - - // Set up auction constants - layout := "2006-01-02T15:04:05.000Z" - endTimeStr := "9000-01-01T00:00:00.000Z" - endTime, _ := time.Parse(layout, endTimeStr) - addr, _ := sdk.AccAddressFromBech32("kava1ze7y9qwdddejmy7jlw4cymqqlt2wh05yhwmrv2") - - testCases := []test{ - { - "valid liquidation", - args{ - ctype: "btc-a", - blockTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialPrice: d("20000.00"), - finalPrice: d("19000.0"), - finalTwapPrice: d("19000.0"), - collateral: c("btc", 10000000), - principal: c("usdx", 1333330000), - expectedKeeperCoins: cs(c("btc", 100100000), c("xrp", 10000000000)), - expectedAuctions: []auctiontypes.Auction{ - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 1, - Initiator: "liquidator", - Lot: c("btc", 9900000), - Bidder: nil, - Bid: c("usdx", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: c("debt", 1333330000), - MaxBid: c("usdx", 1366663250), - LotReturns: auctiontypes.WeightedAddresses{ - Addresses: []sdk.AccAddress{addr}, - Weights: []sdkmath.Int{sdkmath.NewInt(9900000)}, - }, - }, - }, - }, - errArgs{ - true, - "", - }, - }, - { - "valid liquidation - twap market liquidateable but not spot", - args{ - ctype: "btc-a", - blockTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialPrice: d("20000.00"), - // spot price does not liquidates - finalPrice: d("21000.0"), - // twap / liquidation price does liquidate - finalTwapPrice: d("19000.0"), - collateral: c("btc", 10000000), - principal: c("usdx", 1333330000), - expectedKeeperCoins: cs(c("btc", 100100000), c("xrp", 10000000000)), - expectedAuctions: []auctiontypes.Auction{ - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 1, - Initiator: "liquidator", - Lot: c("btc", 9900000), - Bidder: nil, - Bid: c("usdx", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: c("debt", 1333330000), - MaxBid: c("usdx", 1366663250), - LotReturns: auctiontypes.WeightedAddresses{ - Addresses: []sdk.AccAddress{addr}, - Weights: []sdkmath.Int{sdkmath.NewInt(9900000)}, - }, - }, - }, - }, - errArgs{ - true, - "", - }, - }, - { - "invalid - not below collateralization ratio", - args{ - ctype: "btc-a", - blockTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialPrice: d("20000.00"), - finalPrice: d("21000.0"), - finalTwapPrice: d("21000.0"), - collateral: c("btc", 10000000), - principal: c("usdx", 1333330000), - expectedKeeperCoins: cs(), - expectedAuctions: []auctiontypes.Auction{}, - }, - errArgs{ - false, - "collateral ratio not below liquidation ratio", - }, - }, - { - "invalid - spot market liquidateable but not twap", - args{ - ctype: "btc-a", - blockTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialPrice: d("20000.00"), - // spot price liquidates - finalPrice: d("19000.0"), - // twap / liquidation price does not liquidate - finalTwapPrice: d("21000.0"), - collateral: c("btc", 10000000), - principal: c("usdx", 1333330000), - expectedKeeperCoins: cs(), - expectedAuctions: []auctiontypes.Auction{}, - }, - errArgs{ - false, - "collateral ratio not below liquidation ratio", - }, - }, - { - "invalid - collateralization ratio equal to liquidation ratio", - args{ - ctype: "xrp-a", - blockTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - initialPrice: d("1.00"), // we are allowed to create a cdp with an exact ratio - finalPrice: d("1.00"), - finalTwapPrice: d("1.00"), // and it should not be able to be liquidated - collateral: c("xrp", 100000000), - principal: c("usdx", 50000000), - expectedKeeperCoins: cs(), - expectedAuctions: []auctiontypes.Auction{}, - }, - errArgs{ - false, - "collateral ratio not below liquidation ratio", - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - spotMarket := fmt.Sprintf("%s:usd", tc.args.collateral.Denom) - liquidationMarket := fmt.Sprintf("%s:30", spotMarket) - - // setup pricefeed - pk := suite.app.GetPriceFeedKeeper() - _, err := pk.SetPrice(suite.ctx, sdk.AccAddress{}, spotMarket, tc.args.initialPrice, suite.ctx.BlockTime().Add(time.Hour*24)) - suite.Require().NoError(err) - err = pk.SetCurrentPrices(suite.ctx, spotMarket) - suite.Require().NoError(err) - - // setup cdp state - suite.keeper.SetPreviousAccrualTime(suite.ctx, tc.args.ctype, suite.ctx.BlockTime()) - suite.keeper.SetInterestFactor(suite.ctx, tc.args.ctype, sdk.OneDec()) - err = suite.keeper.AddCdp(suite.ctx, suite.addrs[0], tc.args.collateral, tc.args.principal, tc.args.ctype) - suite.Require().NoError(err) - - // update pricefeed - // spot market - _, err = pk.SetPrice(suite.ctx, sdk.AccAddress{}, spotMarket, tc.args.finalPrice, suite.ctx.BlockTime().Add(time.Hour*24)) - suite.Require().NoError(err) - // liquidate market - _, err = pk.SetPrice(suite.ctx, sdk.AccAddress{}, liquidationMarket, tc.args.finalTwapPrice, suite.ctx.BlockTime().Add(time.Hour*24)) - suite.Require().NoError(err) - - err = pk.SetCurrentPrices(suite.ctx, spotMarket) - suite.Require().NoError(err) - err = pk.SetCurrentPrices(suite.ctx, liquidationMarket) - suite.Require().NoError(err) - - _, found := suite.keeper.GetCdpByOwnerAndCollateralType(suite.ctx, suite.addrs[0], tc.args.ctype) - suite.Require().True(found) - - err = suite.keeper.AttemptKeeperLiquidation(suite.ctx, suite.addrs[1], suite.addrs[0], tc.args.ctype) - - if tc.errArgs.expectLiquidate { - suite.Require().NoError(err) - - _, found = suite.keeper.GetCdpByOwnerAndCollateralType(suite.ctx, suite.addrs[0], tc.args.ctype) - suite.Require().False(found) - - ak := suite.app.GetAuctionKeeper() - auctions := ak.GetAllAuctions(suite.ctx) - suite.Require().Equal(tc.args.expectedAuctions, auctions) - - ack := suite.app.GetAccountKeeper() - bk := suite.app.GetBankKeeper() - keeper := ack.GetAccount(suite.ctx, suite.addrs[1]) - suite.Require().Equal(tc.args.expectedKeeperCoins, bk.GetAllBalances(suite.ctx, keeper.GetAddress())) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *SeizeTestSuite) TestBeginBlockerLiquidation() { - type args struct { - ctype string - blockTime time.Time - initialPrice sdk.Dec - finalPrice sdk.Dec - collaterals sdk.Coins - principals sdk.Coins - expectedAuctions []auctiontypes.Auction // the auctions we should expect to find have been started - } - type errArgs struct { - expectLiquidate bool - contains string - } - type test struct { - name string - args args - errArgs errArgs - } - // Set up auction constants - layout := "2006-01-02T15:04:05.000Z" - endTimeStr := "9000-01-01T00:00:00.000Z" - endTime, _ := time.Parse(layout, endTimeStr) - addr, _ := sdk.AccAddressFromBech32("kava1ze7y9qwdddejmy7jlw4cymqqlt2wh05yhwmrv2") - - testCases := []test{ - { - "1 liquidation", - args{ - "btc-a", - time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - d("20000.00"), - d("10000.00"), - sdk.Coins{c("btc", 10000000), c("btc", 10000000)}, - sdk.Coins{c("usdx", 1000000000), c("usdx", 500000000)}, - []auctiontypes.Auction{ - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 1, - Initiator: "liquidator", - Lot: c("btc", 10000000), - Bidder: nil, - Bid: c("usdx", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: c("debt", 1000000000), - MaxBid: c("usdx", 1025000000), - LotReturns: auctiontypes.WeightedAddresses{ - Addresses: []sdk.AccAddress{addr}, - Weights: []sdkmath.Int{sdkmath.NewInt(10000000)}, - }, - }, - }, - }, - errArgs{ - true, - "", - }, - }, - { - "no liquidation", - args{ - "btc-a", - time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - d("20000.00"), - d("10000.00"), - sdk.Coins{c("btc", 10000000), c("btc", 10000000)}, - sdk.Coins{c("usdx", 500000000), c("usdx", 500000000)}, - []auctiontypes.Auction{}, - }, - errArgs{ - false, - "collateral ratio not below liquidation ratio", - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - // setup pricefeed - pk := suite.app.GetPriceFeedKeeper() - _, err := pk.SetPrice(suite.ctx, sdk.AccAddress{}, "btc:usd", tc.args.initialPrice, suite.ctx.BlockTime().Add(time.Hour*24)) - suite.Require().NoError(err) - err = pk.SetCurrentPrices(suite.ctx, "btc:usd") - suite.Require().NoError(err) - - // setup cdp state - suite.keeper.SetPreviousAccrualTime(suite.ctx, tc.args.ctype, suite.ctx.BlockTime()) - suite.keeper.SetInterestFactor(suite.ctx, tc.args.ctype, sdk.OneDec()) - - for idx, col := range tc.args.collaterals { - err := suite.keeper.AddCdp(suite.ctx, suite.addrs[idx], col, tc.args.principals[idx], tc.args.ctype) - suite.Require().NoError(err) - } - - // update pricefeed - _, err = pk.SetPrice(suite.ctx, sdk.AccAddress{}, "btc:usd", tc.args.finalPrice, suite.ctx.BlockTime().Add(time.Hour*24)) - suite.Require().NoError(err) - err = pk.SetCurrentPrices(suite.ctx, "btc:usd") - suite.Require().NoError(err) - - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{Header: suite.ctx.BlockHeader()}) - ak := suite.app.GetAuctionKeeper() - auctions := ak.GetAllAuctions(suite.ctx) - if tc.errArgs.expectLiquidate { - suite.Require().Equal(tc.args.expectedAuctions, auctions) - for _, a := range auctions { - ca := a.(*auctiontypes.CollateralAuction) - _, found := suite.keeper.GetCdpByOwnerAndCollateralType(suite.ctx, ca.LotReturns.Addresses[0], tc.args.ctype) - suite.Require().False(found) - } - } else { - suite.Require().Equal(0, len(auctions)) - for idx := range tc.args.collaterals { - _, found := suite.keeper.GetCdpByOwnerAndCollateralType(suite.ctx, suite.addrs[idx], tc.args.ctype) - suite.Require().True(found) - } - } - }) - } -} - -func TestSeizeTestSuite(t *testing.T) { - suite.Run(t, new(SeizeTestSuite)) -} diff --git a/x/cdp/migrations/v2/store.go b/x/cdp/migrations/v2/store.go deleted file mode 100644 index 1a84e0cc..00000000 --- a/x/cdp/migrations/v2/store.go +++ /dev/null @@ -1,22 +0,0 @@ -package v2 - -import ( - "github.com/0glabs/0g-chain/x/cdp/types" - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -// MigrateStore performs in-place store migrations for consensus version 2 -// V2 adds the begin_blocker_execution_block_interval param to parameters. -func MigrateStore(ctx sdk.Context, paramstore paramtypes.Subspace) error { - migrateParamsStore(ctx, paramstore) - return nil -} - -// migrateParamsStore ensures the param key table exists and has the begin_blocker_execution_block_interval property -func migrateParamsStore(ctx sdk.Context, paramstore paramtypes.Subspace) { - if !paramstore.HasKeyTable() { - paramstore.WithKeyTable(types.ParamKeyTable()) - } - paramstore.Set(ctx, types.KeyBeginBlockerExecutionBlockInterval, types.DefaultBeginBlockerExecutionBlockInterval) -} diff --git a/x/cdp/migrations/v2/store_test.go b/x/cdp/migrations/v2/store_test.go deleted file mode 100644 index 206ef5a5..00000000 --- a/x/cdp/migrations/v2/store_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package v2_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - - v2cdp "github.com/0glabs/0g-chain/x/cdp/migrations/v2" - "github.com/0glabs/0g-chain/x/cdp/types" -) - -func TestStoreMigrationAddsKeyTableIncludingNewParam(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig() - cdpKey := sdk.NewKVStoreKey(types.ModuleName) - tcdpKey := sdk.NewTransientStoreKey("transient_test") - ctx := testutil.DefaultContext(cdpKey, tcdpKey) - paramstore := paramtypes.NewSubspace(encCfg.Codec, encCfg.Amino, cdpKey, tcdpKey, types.ModuleName) - - // Check param doesn't exist before - require.False(t, paramstore.Has(ctx, types.KeyBeginBlockerExecutionBlockInterval)) - - // Run migrations. - err := v2cdp.MigrateStore(ctx, paramstore) - require.NoError(t, err) - - // Make sure the new params are set. - require.True(t, paramstore.Has(ctx, types.KeyBeginBlockerExecutionBlockInterval)) - // Assert the value is what we expect - result := types.DefaultBeginBlockerExecutionBlockInterval - paramstore.Get(ctx, types.KeyBeginBlockerExecutionBlockInterval, &result) - require.Equal(t, result, types.DefaultBeginBlockerExecutionBlockInterval) -} - -func TestStoreMigrationSetsNewParamOnExistingKeyTable(t *testing.T) { - encCfg := moduletestutil.MakeTestEncodingConfig() - cdpKey := sdk.NewKVStoreKey(types.ModuleName) - tcdpKey := sdk.NewTransientStoreKey("transient_test") - ctx := testutil.DefaultContext(cdpKey, tcdpKey) - paramstore := paramtypes.NewSubspace(encCfg.Codec, encCfg.Amino, cdpKey, tcdpKey, types.ModuleName) - paramstore.WithKeyTable(types.ParamKeyTable()) - - // expect it to have key table - require.True(t, paramstore.HasKeyTable()) - // expect it to not have new param - require.False(t, paramstore.Has(ctx, types.KeyBeginBlockerExecutionBlockInterval)) - - // Run migrations. - err := v2cdp.MigrateStore(ctx, paramstore) - require.NoError(t, err) - - // Make sure the new params are set. - require.True(t, paramstore.Has(ctx, types.KeyBeginBlockerExecutionBlockInterval)) - - // Assert the value is what we expect - result := types.DefaultBeginBlockerExecutionBlockInterval - paramstore.Get(ctx, types.KeyBeginBlockerExecutionBlockInterval, &result) - require.Equal(t, result, types.DefaultBeginBlockerExecutionBlockInterval) -} diff --git a/x/cdp/module.go b/x/cdp/module.go deleted file mode 100644 index 401c4b48..00000000 --- a/x/cdp/module.go +++ /dev/null @@ -1,155 +0,0 @@ -package cdp - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/0glabs/0g-chain/x/cdp/client/cli" - "github.com/0glabs/0g-chain/x/cdp/keeper" - "github.com/0glabs/0g-chain/x/cdp/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// ConsensusVersion defines the current module consensus version. -const ConsensusVersion = 2 - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name get module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis returns default genesis state as raw bytes for the cdp -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - gs := types.DefaultGenesisState() - return cdc.MustMarshalJSON(&gs) -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - err := cdc.UnmarshalJSON(bz, &gs) - if err != nil { - return err - } - return gs.Validate() -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the gov module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return ConsensusVersion -} - -// GetTxCmd returns the root tx command for the cdp module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns the root query command for the auction module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -//____________________________________________________________________________ - -// AppModule app module type -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper - pricefeedKeeper types.PricefeedKeeper - bankKeeper types.BankKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, accountKeeper types.AccountKeeper, pricefeedKeeper types.PricefeedKeeper, bankKeeper types.BankKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: accountKeeper, - pricefeedKeeper: pricefeedKeeper, - bankKeeper: bankKeeper, - } -} - -// Name module name -func (AppModule) Name() string { - return types.ModuleName -} - -// RegisterInvariants register module invariants -func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) - - m := keeper.NewMigrator(am.keeper) - if err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2); err != nil { - panic(fmt.Sprintf("failed to migrate x/cdp from version 1 to 2: %v", err)) - } -} - -// InitGenesis module init-genesis -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { - var genState types.GenesisState - // Initialize global index to index in genesis state - cdc.MustUnmarshalJSON(gs, &genState) - - InitGenesis(ctx, am.keeper, am.pricefeedKeeper, am.accountKeeper, genState) - return []abci.ValidatorUpdate{} -} - -// ExportGenesis module export genesis -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(&gs) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) { - BeginBlocker(ctx, req, am.keeper) -} - -// EndBlock module end-block -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/cdp/spec/01_concepts.md b/x/cdp/spec/01_concepts.md deleted file mode 100644 index 7e8876f9..00000000 --- a/x/cdp/spec/01_concepts.md +++ /dev/null @@ -1,86 +0,0 @@ - - -# Concepts - -## Collateralized Debt Positions - -CDPs enable the creation of a stable asset by collateralization with another on chain asset. - -A CDP is scoped to one collateral type. It has one primary owner, and a set of "depositors". The depositors can deposit and withdraw collateral to the CDP. The owner can draw stable assets (creating debt), deposit and withdraw collateral, and repay stable assets to cancel the debt. - -Once created, stable assets are free to be transferred between users, but a CDP owner must repay their debt to get their collateral back. - -User interactions with this module: - -- create a new CDP by depositing a supported coin as collateral and minting debt -- deposit to a CDP controlled by a different owner address -- withdraw deposited collateral, if it doesn't put the CDP below the liquidation ratio -- issue stable coins from this CDP (up to a fraction of the value of the collateral) -- repay debt by paying back stable coins (including paying any fees accrued) -- remove collateral and close CDP - -Module interactions: - -- fees for all CDPs are updated each block -- the value of fees (surplus) is divded between users, via the savings rate, and owners of the governance token, via burning governance tokens proportional to surplus -- the value of an asset that is supported for CDPs is determined by querying an external pricefeed -- if the price of an asset puts a CDP below the liquidation ratio, the CDP is liquidated -- liquidated collateral is divided into lots and sent to an external auction module -- collateral that is returned from the auction module is returned to the account that deposited that collateral -- if auctions do not recover the desired amount of debt, debt auctions are triggered after a certain threshold of global debt is reached -- surplus auctions are triggered after a certain threshold of surplus is triggered - -## Liquidation & Stability System - -In the event of a decrease in the price of the collateral, the total value of all collateral in CDPs may drop below the value of all the issued stable assets. This undesirable event is countered through two mechanisms: - -**CDP Liquidations** The ratio of collateral value to debt value in each CDP is monitored. When this drops too low the collateral and debt is automatically seized by the system. The collateral is sold off through an auction to bring in stable asset which is burned against the seized debt. The price used to determine liquidation is controlled by the `LiquidationMarketID` parameter, which can be the same as the `SpotMarketID` or use a different calculation of price, such as a time-weighted average. - -**Debt Auctions** In extreme cases where liquidations fail to raise enough to cover the seized debt, another mechanism kicks in: Debt Auctions. System governance tokens are minted and sold through auction to raise enough stable asset to cover the remaining debt. The governors of the system represent the lenders of last resort. - -The system monitors the state of CDPs and debt and triggers these auctions as needed. - -## Internal Debt Tracking - -Users incur debt when they draw new stable assets from their CDP. Within the system this debt is tracked in the form of a "debt coin" stored internally in the module's accounts. Every time a stable coin is created a corresponding debt coin is created. Likewise when debt is repaid stable coin and internal debt coin are burned. - -The cdp module uses two module accounts - one to hold debt coins associated with active CDPs, and another (the "liquidator" account) to hold debt from CDPS that have been seized by the system. - -## Fees - -When a user repays stable asset withdrawn from a CDP, they must also pay a fee. - -This is calculated according to the amount of stable asset withdrawn and the time withdrawn for. Like interest on a loan, fees grow at a compounding percentage of original debt. - -Fees create incentives to open or close CDPs and can be changed by governance to help keep the system functioning through changing market conditions. - -A further fee is applied on liquidation of a CDP. Normally when the collateral is sold to cover the debt, any excess not sold is returned to the CDP holder. The liquidation fee reduces the amount of excess collateral returned, representing a cut that the system takes. - -Fees accumulate to the system and are split between the savings rate and surplus. Fees accumulated by the savings rate are distributed directly to holders of stable coins at a specified frequency. Savings rate distributions are proportional to tokens held. For example, if an account holds 1% of all stable coins, they will receive 1% of the savings rate distribution. Fees accumulated as surplus are automatically sold at auction for governance token once a certain threshold is reached. The governance tokens raised at auction are then burned, acting as incentive for safe governance of the system. - -## Governance - -The cdp module's behavior is controlled through several parameters which are updated through a governance mechanism. These parameters are listed in [Parameters](04_params.md). - -Governance is important for actions such as: - -- enabling CDPs to be created with new collateral assets -- changing fee rates to incentivize behavior -- increasing the debt ceiling to allow more stable asset to be created -- increasing/decreasing the savings rate to promote stability of the debt asset - -## Dependency: supply - -The CDP module relies on a supply keeper to move assets between its module accounts and user accounts. - -## Dependency: pricefeed - -The CDP module needs to know the current price of collateral assets in order to determine if CDPs are under collateralized. This is provided by a "pricefeed" module that returns a price for a given collateral in units (usually US Dollars) which are the target for the stable asset. The status of the pricefeed for each collateral is checked at the beginning of each block. In the event that the pricefeed does not return a price for a collateral asset: - -1. Liquidation of CDPs is suspended until a price is reported -2. Accumulation of fees is suspended until a price is reported -3. Deposits and withdrawals of collateral are suspended until a price is reported -4. Creation of new CDPs is suspended until a price is reported -5. Drawing of additional debt off of existing CDPs is suspended until a price is reported diff --git a/x/cdp/spec/02_state.md b/x/cdp/spec/02_state.md deleted file mode 100644 index bdf36744..00000000 --- a/x/cdp/spec/02_state.md +++ /dev/null @@ -1,78 +0,0 @@ - - -# State - -For detail on the state tracked by the cdp module see the types package. In particular [keys.go](../types/keys.go) describes how state is stored in the key-value store. - -## Module Accounts - -The cdp module account controls two module accounts: - -**CDP Account:** Stores the deposited cdp collateral, and the debt coins for the debt in all the cdps. - -**Liquidator Account:** Stores debt coins that have been seized by the system, and any stable asset that has been raised through auctions. - -## CDP - -A CDP is a struct representing a debt position owned by one address. It has one collateral type and records the debt that has been drawn and how much fees should be repaid. - -Only an owner is authorized to draw or repay debt, but anyone can deposit collateral to a CDP. Deposits are scoped per address and are recorded separately in `Deposit` types. Depositors are free to withdraw their collateral provided it does not put the CDP below the liquidation ratio. - -The CDP's collateral always equal to the total of the deposits. - -```go -type CDP struct { - ID uint64 - Owner sdk.AccAddress - Type string - Collateral sdk.Coin - Principal sdk.Coin - AccumulatedFees sdk.Coin - FeesUpdated time.Time - InterestFactor sdk.Dec -} -``` - -CDPs are stored with three database indexes for faster lookup: - -- by collateral ratio - to look up cdps that are close to the liquidation ratio -- by collateral denom - to look up cdps with a particular collateral asset -- by owner index - to look up cdps that an address is the owner of - -## Deposit - -A Deposit is a struct recording collateral added to a CDP by one address. The address only has authorization to change their deposited amount (provided it does not put the CDP below the liquidation ratio). - -```go -type Deposit struct { - CdpID uint64 - Depositor sdk.AccAddress - Amount sdk.Coin -} -``` - -## Params - -Module parameters controlled by governance. See [Parameters](04_params.md) for details. - -## NextCDPID - -A global counter used to create unique CDP ids. - -## DebtDenom - -The name of the internal debt coin. Its value can be configured at genesis. - -## GovDenom - -The name of the internal governance coin. Its value can be configured at genesis. - -## Total Principle - -Sum of all non seized debt plus accumulated fees. - -## Previous Savings Distribution Time - -A record of the last block time when the savings rate was distributed diff --git a/x/cdp/spec/03_messages.md b/x/cdp/spec/03_messages.md deleted file mode 100644 index 1fe7fd02..00000000 --- a/x/cdp/spec/03_messages.md +++ /dev/null @@ -1,145 +0,0 @@ - - -# Messages - -Users can submit various messages to the cdp module which trigger state changes detailed below. - -## CreateCDP - -CreateCDP sets up and stores a new CDP, adding collateral from the sender, and drawing `Principle` debt. - -```go -type MsgCreateCDP struct { - Sender sdk.AccAddress - Collateral sdk.Coin - Principal sdk.Coin -} -``` - -State changes: - -- a new CDP is created, `Sender` becomes CDP owner -- collateral taken from `Sender` and sent to cdp module account, new `Deposit` created -- `Principal` stable coins are minted and sent to `Sender` -- equal amount of internal debt coins created and stored in cdp module account - -## Deposit - -Deposit adds collateral to a CDP in the form of a deposit. Collateral is taken from `Depositor`. - -```go -type MsgDeposit struct { - Owner sdk.AccAddress - Depositor sdk.AccAddress - Collateral sdk.Coin -} -``` - -State Changes: - -- `Collateral` taken from depositor and sent to cdp module account -- the depositor's `Deposit` struct is updated or a new one created -- cdp fees are updated (see below) - -## Withdraw - -Withdraw removes collateral from a CDP, provided it would not put the CDP under the liquidation ratio. Collateral is removed from one deposit only. - -```go -type MsgWithdraw struct { - Owner sdk.AccAddress - Depositor sdk.AccAddress - Collateral sdk.Coin -} -``` - -State Changes: - -- `Collateral` coins are sent from the cdp module account to `Depositor` -- `Collateral` amount of coins subtracted from the `Deposit` struct. If the amount is now zero, the struct is deleted - -## DrawDebt - -DrawDebt creates debt in a CDP, minting new stable asset which is sent to the sender. - -```go -type MsgDrawDebt struct { - Sender sdk.AccAddress - CdpDenom string - Principal sdk.Coin -} -``` - -State Changes: - -- mint `Principal` coins and send them to `Sender`, updating the CDP's `Principal` field -- mint equal amount of internal debt coins and store in the module account -- increment total principal for principal denom - -## RepayDebt - -RepayDebt removes some debt from a CDP and burns the corresponding amount of stable asset from the sender. If all debt is repaid, the collateral is returned to depositors and the cdp is removed from the store - -```go -type MsgRepayDebt struct { - Sender sdk.AccAddress - CdpDenom string - Payment sdk.Coin -} -``` - -State Changes: - -- burn `Payment` coins taken from `Sender`, updating the CDP by reducing `Principal` field by `Paymment` -- burn an equal amount of internal debt coins -- decrement total principal for payment denom -- if fees and principal are zero, return collateral to depositors and delete the CDP struct: - - For each deposit, send coins from the cdp module account to the depositor, and delete the deposit struct from store. - -## Liquidate - -Liquidate enables Keepers to liquidate a Borrower's CDP. If the CDP is below its Loan-to-Value obligations, the CDP's deposits are seized: a small percentage of the seized funds are sent to the Keeper with the rest auctioned off to recover the CDP's outstanding borrowed amount. Any deposited funds leftover that weren't needed to cover the Borrower's debts are returned to the Borrower. - -Note: In kava v0.21.x and below, CDP's that have a collateral ratio exactly equal to the liquidation ratio can be liquidated through this method. - -```go -// MsgLiquidate attempts to liquidate a borrower's cdp -type MsgLiquidate struct { - Keeper sdk.AccAddress `json:"keeper" yaml:"keeper"` - Borrower sdk.AccAddress `json:"borrower" yaml:"borrower"` - CollateralType string `json:"collateral_type" yaml:"collateral_type"` -} -``` - -State Changes: - -- the CDP's outstanding interest is synchronized so that the deposit and borrow amount are accurate -- the liquidation attempt is validated by comparing the CDP's current collateralization ratio to its liquidation ratio -- the `Keeper` is paid out a percentage of the liquidated position; the exact percentage is specified in the module's params -- the CDP's deposits are seized and used to start an `Auction` to recover the CDP's outstanding borrowed funds -- the module's `TotalPrincipal` for the CDP's collateral type is decremented by the CDP's `Principal` -- the CDP is deleted from the store and removed from the liquidation index - -## Fees - -At the beginning of each block, fees accumulated since the last update are calculated and added on. - -``` -feesAccumulated = (outstandingDebt * (feeRate^periods)) - outstandingDebt -``` - -where: - -- `outstandingDebt` is the CDP's `Principal` plus `AccumulatedFees` -- `periods` is the number of seconds since last fee update -- `feeRate` is the per second debt interest rate - -Fees are divided between surplus and savings rate. For example, if the savings rate is 0.95, 95% of all fees go towards the savings rate and 5% go to surplus. - -In the event that the rounded value of `feesAccumulated` is zero, fees are not updated, and the `FeesUpdated` value on the CDP struct is not updated. When a sufficient number of periods have passed such that the rounded value is no longer zero, fees will be updated. - -## Database Indexes - -When CDPs are update by the above messages the database indexes are also updated. diff --git a/x/cdp/spec/04_params.md b/x/cdp/spec/04_params.md deleted file mode 100644 index 70e4b16c..00000000 --- a/x/cdp/spec/04_params.md +++ /dev/null @@ -1,42 +0,0 @@ - - -# Parameters - -The cdp module contains the following parameters: - -| Key | Type | Example | Description | -|------------------------------|-------------------------|------------------------------------|------------------------------------------------------------------| -| CollateralParams | array (CollateralParam) | [{see below}] | array of params for each enabled collateral type | -| DebtParams | DebtParam | `{see below}` | array of params for each enabled pegged asset | -| GlobalDebtLimit | coin | `{"denom":"usdx","amount":"1000"}` | maximum pegged assets that can be minted across the whole system | -| SavingsDistributionFrequency | string (int) | "84600" | number of seconds between distribution of the savings rate | -| GlobalDebtLimit | coin | `{"denom":"usdx","amount":"1000"}` | maximum pegged assets that can be minted across the whole system | -| DebtAuctionThreshold | string (int) | "100000000000" | amount of system debt before a debt auction is triggered | -| SurplusAuctionThreshold | string (int) | "100000000000" | amount of system surplus before a surplus auction is triggered | -| DebtAuctionLot | string (int) | "10000000000" | amount of debt that each debt auction will attempt to recoup | -| SurplusAuctionLot | string (int) | "10000000000" | amount of surplus that will be sold at each surplus auction | - -Each CollateralParam has the following parameters: - -| Key | Type | Example | Description | -|---------------------|---------------|--------------------------------------------|-------------------------------------------------------------------------------| -| Denom | string | "bnb" | collateral coin denom | -| LiquidationRatio | string (dec) | "1.500000000000000000" | the ratio under which a cdp with this collateral type will be liquidated | -| DebtLimit | coin | `{"denom":"bnb","amount":"1000000000000"}` | maximum pegged asset that can be minted backed by this collateral type | -| StabilityFee | string (dec) | "1.000000001547126" | per second fee | -| Prefix | number (byte) | "34" | identifier used in store keys - **must** be unique across collateral types | -| SpotMarketID | string | "bnb:usd" | price feed identifier for the spot price of this collateral type | -| LiquidationMarketID | string | "bnb:usd:30" | price feed identifier for the liquidation price of this collateral type | -| ConversionFactor | string (int) | "6" | 10^_ multiplier for external (BTC1.50) to internal (150000000) representation | - -DebtParam has the following parameters: - -| Key | Type | Example | Description | -|------------------|--------------|------------|------------------------------------------------------------------------------------------------------------| -| Denom | string | "usdx" | pegged asset coin denom | -| ReferenceAsset | string | "USD" | asset this asset is pegged to, informational purposes only | -| ConversionFactor | string (int) | "6" | 10^_ multiplier to go from external amount (say $1.50) to internal representation of that amount (1500000) | -| DebtFloor | string (int) | "10000000" | minimum amount of debt that a CDP can contain | -| SavingsRate | string (dec) | "0.95" | the percentage of accumulated fees that go towards the savings rate | diff --git a/x/cdp/spec/05_events.md b/x/cdp/spec/05_events.md deleted file mode 100644 index d001d496..00000000 --- a/x/cdp/spec/05_events.md +++ /dev/null @@ -1,68 +0,0 @@ - - -# Events - -The cdp module emits the following events: - -## Handlers - -### MsgCreateCDP - -| Type | Attribute Key | Attribute Value | -|-------------|---------------|--------------------| -| message | module | cdp | -| message | sender | `{sender address}' | -| create_cdp | cdp_id | `{cdp id}' | -| cdp_deposit | cdp_id | `{cdp id}' | -| cdp_deposit | amount | `{deposit amount}' | -| cdp_draw | cdp_id | `{cdp id}' | -| cdp_draw | amount | `{draw amount}' | - -### MsgWithdraw - -| Type | Attribute Key | Attribute Value | -|---------|--------------- |-----------------------| -| message | cdp_withdrawal | `{collateral amount}' | -| message | cdp_id | `{cdp_id}' | -| message | module | cdp | -| message | sender | `{sender address}' | - -### MsgDeposit - -| Type | Attribute Key | Attribute Value | -|-------------|---------------|--------------------| -| message | module | cdp | -| message | sender | `{sender address}' | -| cdp_deposit | cdp_id | `{cdp id}' | -| cdp_deposit | amount | `{deposit amount}' | - -### MsgDrawDebt - -| Type | Attribute Key | Attribute Value | -|----------|---------------|--------------------| -| message | module | cdp | -| message | sender | `{sender address}' | -| cdp_draw | cdp_id | `{cdp id}' | -| cdp_draw | amount | `{draw amount}' | - -### MsgRepayDebt - -| Type | Attribute Key | Attribute Value | -|---------------|---------------|----------------------| -| cdp_repayment | amount | `{repayment amount}' | -| cdp_repayment | cdp_id | `{cdp id}' | -| cdp_close | cdp_id | `{cdp id}' | -| message | module | cdp | -| message | sender | `{sender address}' | - -## BeginBlock - -| Type | Attribute Key | Attribute Value | -|-------------------------|---------------|---------------------| -| cdp_liquidation | module | cdp | -| cdp_liquidation | cdp_id | `{cdp id}' | -| cdp_liquidation | deposit | `{deposit}' | -| cdp_begin_blocker_error | module | cdp | -| cdp_begin_blocker_error | error_message | `{error}' | diff --git a/x/cdp/spec/06_begin_block.md b/x/cdp/spec/06_begin_block.md deleted file mode 100644 index cae98e21..00000000 --- a/x/cdp/spec/06_begin_block.md +++ /dev/null @@ -1,46 +0,0 @@ - - -# Begin Block - -At the start of every block the BeginBlock of the cdp module: - -- updates the status of the pricefeed for each collateral asset -- If the pricefeed is active (reporting a price): - - updates fees for CDPs - - liquidates CDPs under the collateral ratio -- nets out system debt and, if necessary, starts auctions to re-balance it -- pays out the savings rate if sufficient time has past -- records the last savings rate distribution, if one occurred - -## Update Fees - -- The total fees accumulated since the last block for each CDP are calculated. -- If the fee amount is non-zero: - - Set the updated value for fees - - Set the fees updated time for the CDP to the current block time - - An equal amount of debt coins are minted and sent to the system's CDP module account. - - An equal amount of stable asset coins are minted and sent to the system's liquidator module account - - Increment total principal. - -## Liquidate CDP - -- Get every cdp that is under the liquidation ratio for its collateral type. -- For each cdp: - - Remove all collateral and internal debt coins from cdp and deposits and delete it. Send the coins to the liquidator module account. - - Start auctions of a fixed size from this collateral (with any remainder in a smaller sized auction), sending collateral and debt coins to the auction module account. - - Decrement total principal. - -## Net Out System Debt, Re-Balance - -- Burn the maximum possible equal amount of debt and stable asset from the liquidator module account. -- If there is enough debt remaining for an auction, start one. -- If there is enough surplus stable asset, minus surplus reserved for the savings rate, remaining for an auction, start one. -- Otherwise do nothing, leave debt/surplus to accumulate over subsequent blocks. - -## Distribute Surplus Stable Asset According to the Savings Rate - -- If `SavingsDistributionFrequency` seconds have elapsed since the previous distribution, the savings rate is applied to all accounts that hold stable asset. -- Each account that holds stable asset is distributed a ratable portion of the surplus that is apportioned to the savings rate. -- If distribution occurred, the time of the distribution is recorded. diff --git a/x/cdp/spec/README.md b/x/cdp/spec/README.md deleted file mode 100644 index 225f2d01..00000000 --- a/x/cdp/spec/README.md +++ /dev/null @@ -1,25 +0,0 @@ - - -# `cdp` - -## Table of Contents - -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Parameters](04_params.md)** -5. **[Events](05_events.md)** -6. **[BeginBlock](06_begin_block.md)** - -## Overview - -The `x/cdp` module stores and manages Collateralized Debt Positions (or CDPs). - -A CDP enables the creation of a stable asset pegged to an external price (usually US Dollar) by collateralization with another asset. Collateral is locked in a CDP and new stable asset can be minted up to some fraction of the value of the collateral. To unlock the collateral, the debt must be repaid by returning some stable asset to the CDP at which point it will be burned and the collateral unlocked. - -Pegged assets remain fully collateralized by the value locked in CDPs. In the event of price changes, this collateral can be seized and sold off in auctions by the system to reclaim and reduce the supply of stable assets. diff --git a/x/cdp/types/cdp.go b/x/cdp/types/cdp.go deleted file mode 100644 index df38a9b3..00000000 --- a/x/cdp/types/cdp.go +++ /dev/null @@ -1,205 +0,0 @@ -package types - -import ( - "errors" - "fmt" - "strings" - "time" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// NewCDP creates a new CDP object -func NewCDP(id uint64, owner sdk.AccAddress, collateral sdk.Coin, collateralType string, principal sdk.Coin, time time.Time, interestFactor sdk.Dec) CDP { - fees := sdk.NewCoin(principal.Denom, sdk.ZeroInt()) - return CDP{ - ID: id, - Owner: owner, - Type: collateralType, - Collateral: collateral, - Principal: principal, - AccumulatedFees: fees, - FeesUpdated: time, - InterestFactor: interestFactor, - } -} - -// NewCDPWithFees creates a new CDP object, for use during migration -func NewCDPWithFees(id uint64, owner sdk.AccAddress, collateral sdk.Coin, collateralType string, principal, fees sdk.Coin, time time.Time, interestFactor sdk.Dec) CDP { - return CDP{ - ID: id, - Owner: owner, - Type: collateralType, - Collateral: collateral, - Principal: principal, - AccumulatedFees: fees, - FeesUpdated: time, - InterestFactor: interestFactor, - } -} - -// Validate performs a basic validation of the CDP fields. -func (cdp CDP) Validate() error { - if cdp.ID == 0 { - return errors.New("cdp id cannot be 0") - } - if cdp.Owner.Empty() { - return errors.New("cdp owner cannot be empty") - } - if !cdp.Collateral.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "collateral %s", cdp.Collateral) - } - if !cdp.Principal.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "principal %s", cdp.Principal) - } - if !cdp.AccumulatedFees.IsValid() { - 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") - } - if strings.TrimSpace(cdp.Type) == "" { - return fmt.Errorf("cdp type cannot be empty") - } - return nil -} - -// GetTotalPrincipal returns the total principle for the cdp -func (cdp CDP) GetTotalPrincipal() sdk.Coin { - return cdp.Principal.Add(cdp.AccumulatedFees) -} - -// GetNormalizedPrincipal returns the total cdp principal divided by the interest factor. -// -// Multiplying the normalized principal by the current global factor gives the current debt (ie including all interest, ie a synced cdp). -// The normalized principal is effectively how big the principal would have been if it had been borrowed at time 0 and not touched since. -// -// An error is returned if the cdp interest factor is in an invalid state. -func (cdp CDP) GetNormalizedPrincipal() (sdk.Dec, error) { - unsyncedDebt := cdp.GetTotalPrincipal().Amount - if cdp.InterestFactor.LT(sdk.OneDec()) { - return sdk.Dec{}, fmt.Errorf("interest factor '%s' must be ≥ 1", cdp.InterestFactor) - } - return sdk.NewDecFromInt(unsyncedDebt).Quo(cdp.InterestFactor), nil -} - -// CDPs a collection of CDP objects -type CDPs []CDP - -// Validate validates each CDP -func (cdps CDPs) Validate() error { - for _, cdp := range cdps { - if err := cdp.Validate(); err != nil { - return err - } - } - return nil -} - -// AugmentedCDP provides additional information about an active CDP. -// This is only used for the legacy querier and legacy rest endpoints. -type AugmentedCDP struct { - CDP `json:"cdp" yaml:"cdp"` - CollateralValue sdk.Coin `json:"collateral_value" yaml:"collateral_value"` // collateral's market value in debt coin - CollateralizationRatio sdk.Dec `json:"collateralization_ratio" yaml:"collateralization_ratio"` // current collateralization ratio -} - -// NewAugmentedCDP creates a new AugmentedCDP object -func NewAugmentedCDP(cdp CDP, collateralValue sdk.Coin, collateralizationRatio sdk.Dec) AugmentedCDP { - augmentedCDP := AugmentedCDP{ - CDP: CDP{ - ID: cdp.ID, - Owner: cdp.Owner, - Type: cdp.Type, - Collateral: cdp.Collateral, - Principal: cdp.Principal, - AccumulatedFees: cdp.AccumulatedFees, - FeesUpdated: cdp.FeesUpdated, - InterestFactor: cdp.InterestFactor, - }, - CollateralValue: collateralValue, - CollateralizationRatio: collateralizationRatio, - } - return augmentedCDP -} - -// String implements fmt.stringer -func (augCDP AugmentedCDP) String() string { - return strings.TrimSpace(fmt.Sprintf(`AugmentedCDP: - Owner: %s - ID: %d - Collateral Type: %s - Collateral: %s - Collateral Value: %s - Principal: %s - Fees: %s - Fees Last Updated: %s - Interest Factor: %s - Collateralization ratio: %s`, - augCDP.Owner, - augCDP.ID, - augCDP.Type, - augCDP.Collateral, - augCDP.CollateralValue, - augCDP.Principal, - augCDP.AccumulatedFees, - augCDP.FeesUpdated, - augCDP.InterestFactor, - augCDP.CollateralizationRatio, - )) -} - -// AugmentedCDPs a collection of AugmentedCDP objects -type AugmentedCDPs []AugmentedCDP - -// String implements stringer -func (augcdps AugmentedCDPs) String() string { - out := "" - for _, augcdp := range augcdps { - out += augcdp.String() + "\n" - } - return out -} - -// NewCDPResponse creates a new CDPResponse object -func NewCDPResponse(cdp CDP, collateralValue sdk.Coin, collateralizationRatio sdk.Dec) CDPResponse { - return CDPResponse{ - ID: cdp.ID, - Owner: cdp.Owner.String(), - Type: cdp.Type, - Collateral: cdp.Collateral, - Principal: cdp.Principal, - AccumulatedFees: cdp.AccumulatedFees, - FeesUpdated: cdp.FeesUpdated, - InterestFactor: cdp.InterestFactor.String(), - CollateralValue: collateralValue, - CollateralizationRatio: collateralizationRatio.String(), - } -} - -// CDPResponses a collection of CDPResponse objects -type CDPResponses []CDPResponse - -// TotalPrincipals a collection of TotalPrincipal objects -type TotalPrincipals []TotalPrincipal - -// TotalPrincipal returns a new TotalPrincipal -func NewTotalPrincipal(collateralType string, amount sdk.Coin) TotalPrincipal { - return TotalPrincipal{ - CollateralType: collateralType, - Amount: amount, - } -} - -// TotalCollaterals a collection of TotalCollateral objects -type TotalCollaterals []TotalCollateral - -// TotalCollateral returns a new TotalCollateral -func NewTotalCollateral(collateralType string, amount sdk.Coin) TotalCollateral { - return TotalCollateral{ - CollateralType: collateralType, - Amount: amount, - } -} diff --git a/x/cdp/types/cdp.pb.go b/x/cdp/types/cdp.pb.go deleted file mode 100644 index 87f0190d..00000000 --- a/x/cdp/types/cdp.pb.go +++ /dev/null @@ -1,1528 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/cdp/v1beta1/cdp.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// CDP defines the state of a single collateralized debt position. -type CDP struct { - ID uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` - Owner github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,2,opt,name=owner,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"owner,omitempty"` - Type string `protobuf:"bytes,3,opt,name=type,proto3" json:"type,omitempty"` - Collateral types.Coin `protobuf:"bytes,4,opt,name=collateral,proto3" json:"collateral"` - Principal types.Coin `protobuf:"bytes,5,opt,name=principal,proto3" json:"principal"` - AccumulatedFees types.Coin `protobuf:"bytes,6,opt,name=accumulated_fees,json=accumulatedFees,proto3" json:"accumulated_fees"` - FeesUpdated time.Time `protobuf:"bytes,7,opt,name=fees_updated,json=feesUpdated,proto3,stdtime" json:"fees_updated"` - InterestFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,8,opt,name=interest_factor,json=interestFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"interest_factor"` -} - -func (m *CDP) Reset() { *m = CDP{} } -func (m *CDP) String() string { return proto.CompactTextString(m) } -func (*CDP) ProtoMessage() {} -func (*CDP) Descriptor() ([]byte, []int) { - return fileDescriptor_68a9ab097fb7be40, []int{0} -} -func (m *CDP) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CDP) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CDP.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CDP) XXX_Merge(src proto.Message) { - xxx_messageInfo_CDP.Merge(m, src) -} -func (m *CDP) XXX_Size() int { - return m.Size() -} -func (m *CDP) XXX_DiscardUnknown() { - xxx_messageInfo_CDP.DiscardUnknown(m) -} - -var xxx_messageInfo_CDP proto.InternalMessageInfo - -// Deposit defines an amount of coins deposited by an account to a cdp -type Deposit struct { - CdpID uint64 `protobuf:"varint,1,opt,name=cdp_id,json=cdpId,proto3" json:"cdp_id,omitempty"` - Depositor github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,2,opt,name=depositor,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"depositor,omitempty"` - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *Deposit) Reset() { *m = Deposit{} } -func (m *Deposit) String() string { return proto.CompactTextString(m) } -func (*Deposit) ProtoMessage() {} -func (*Deposit) Descriptor() ([]byte, []int) { - return fileDescriptor_68a9ab097fb7be40, []int{1} -} -func (m *Deposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Deposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Deposit.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Deposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_Deposit.Merge(m, src) -} -func (m *Deposit) XXX_Size() int { - return m.Size() -} -func (m *Deposit) XXX_DiscardUnknown() { - xxx_messageInfo_Deposit.DiscardUnknown(m) -} - -var xxx_messageInfo_Deposit proto.InternalMessageInfo - -// TotalPrincipal defines the total principal of a given collateral type -type TotalPrincipal struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Amount types.Coin `protobuf:"bytes,2,opt,name=amount,proto3" json:"amount"` -} - -func (m *TotalPrincipal) Reset() { *m = TotalPrincipal{} } -func (m *TotalPrincipal) String() string { return proto.CompactTextString(m) } -func (*TotalPrincipal) ProtoMessage() {} -func (*TotalPrincipal) Descriptor() ([]byte, []int) { - return fileDescriptor_68a9ab097fb7be40, []int{2} -} -func (m *TotalPrincipal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TotalPrincipal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TotalPrincipal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TotalPrincipal) XXX_Merge(src proto.Message) { - xxx_messageInfo_TotalPrincipal.Merge(m, src) -} -func (m *TotalPrincipal) XXX_Size() int { - return m.Size() -} -func (m *TotalPrincipal) XXX_DiscardUnknown() { - xxx_messageInfo_TotalPrincipal.DiscardUnknown(m) -} - -var xxx_messageInfo_TotalPrincipal proto.InternalMessageInfo - -// TotalCollateral defines the total collateral of a given collateral type -type TotalCollateral struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Amount types.Coin `protobuf:"bytes,2,opt,name=amount,proto3" json:"amount"` -} - -func (m *TotalCollateral) Reset() { *m = TotalCollateral{} } -func (m *TotalCollateral) String() string { return proto.CompactTextString(m) } -func (*TotalCollateral) ProtoMessage() {} -func (*TotalCollateral) Descriptor() ([]byte, []int) { - return fileDescriptor_68a9ab097fb7be40, []int{3} -} -func (m *TotalCollateral) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TotalCollateral) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TotalCollateral.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TotalCollateral) XXX_Merge(src proto.Message) { - xxx_messageInfo_TotalCollateral.Merge(m, src) -} -func (m *TotalCollateral) XXX_Size() int { - return m.Size() -} -func (m *TotalCollateral) XXX_DiscardUnknown() { - xxx_messageInfo_TotalCollateral.DiscardUnknown(m) -} - -var xxx_messageInfo_TotalCollateral proto.InternalMessageInfo - -// OwnerCDPIndex defines the cdp ids for a single cdp owner -type OwnerCDPIndex struct { - CdpIDs []uint64 `protobuf:"varint,1,rep,packed,name=cdp_ids,json=cdpIds,proto3" json:"cdp_ids,omitempty"` -} - -func (m *OwnerCDPIndex) Reset() { *m = OwnerCDPIndex{} } -func (m *OwnerCDPIndex) String() string { return proto.CompactTextString(m) } -func (*OwnerCDPIndex) ProtoMessage() {} -func (*OwnerCDPIndex) Descriptor() ([]byte, []int) { - return fileDescriptor_68a9ab097fb7be40, []int{4} -} -func (m *OwnerCDPIndex) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *OwnerCDPIndex) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_OwnerCDPIndex.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *OwnerCDPIndex) XXX_Merge(src proto.Message) { - xxx_messageInfo_OwnerCDPIndex.Merge(m, src) -} -func (m *OwnerCDPIndex) XXX_Size() int { - return m.Size() -} -func (m *OwnerCDPIndex) XXX_DiscardUnknown() { - xxx_messageInfo_OwnerCDPIndex.DiscardUnknown(m) -} - -var xxx_messageInfo_OwnerCDPIndex proto.InternalMessageInfo - -func init() { - proto.RegisterType((*CDP)(nil), "kava.cdp.v1beta1.CDP") - proto.RegisterType((*Deposit)(nil), "kava.cdp.v1beta1.Deposit") - proto.RegisterType((*TotalPrincipal)(nil), "kava.cdp.v1beta1.TotalPrincipal") - proto.RegisterType((*TotalCollateral)(nil), "kava.cdp.v1beta1.TotalCollateral") - proto.RegisterType((*OwnerCDPIndex)(nil), "kava.cdp.v1beta1.OwnerCDPIndex") -} - -func init() { proto.RegisterFile("kava/cdp/v1beta1/cdp.proto", fileDescriptor_68a9ab097fb7be40) } - -var fileDescriptor_68a9ab097fb7be40 = []byte{ - // 617 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x54, 0x41, 0x6f, 0xd3, 0x30, - 0x14, 0xae, 0xbb, 0x36, 0x5b, 0xbd, 0xb1, 0x4e, 0x06, 0xa1, 0xac, 0x87, 0xa4, 0x1a, 0x12, 0xf4, - 0xd2, 0x64, 0x03, 0x24, 0x2e, 0x20, 0xb4, 0x34, 0x1a, 0x94, 0x0b, 0x53, 0x34, 0x2e, 0x1c, 0xa8, - 0x5c, 0xdb, 0xcd, 0xa2, 0xa5, 0x71, 0x14, 0xbb, 0x63, 0xfb, 0x11, 0x48, 0xfb, 0x31, 0xfb, 0x11, - 0x3b, 0x70, 0x98, 0x76, 0x42, 0x1c, 0x0a, 0x74, 0xff, 0x82, 0x13, 0xb2, 0x93, 0x2e, 0x3d, 0x16, - 0x09, 0x4e, 0xf1, 0x7b, 0xcf, 0xdf, 0xf7, 0x5e, 0xde, 0xf7, 0x25, 0xb0, 0x75, 0x82, 0x4f, 0xb1, - 0x4b, 0x68, 0xea, 0x9e, 0xee, 0x0d, 0x99, 0xc4, 0x7b, 0xea, 0xec, 0xa4, 0x19, 0x97, 0x1c, 0x6d, - 0xa9, 0x9a, 0xa3, 0xe2, 0xa2, 0xd6, 0xb2, 0x08, 0x17, 0x63, 0x2e, 0xdc, 0x21, 0x16, 0xac, 0x04, - 0xf0, 0x28, 0xc9, 0x11, 0xad, 0xed, 0xbc, 0x3e, 0xd0, 0x91, 0x9b, 0x07, 0x45, 0xe9, 0x41, 0xc8, - 0x43, 0x9e, 0xe7, 0xd5, 0xa9, 0xc8, 0xda, 0x21, 0xe7, 0x61, 0xcc, 0x5c, 0x1d, 0x0d, 0x27, 0x23, - 0x57, 0x46, 0x63, 0x26, 0x24, 0x1e, 0x17, 0x33, 0xec, 0x7c, 0xa9, 0xc1, 0x95, 0x9e, 0x7f, 0x88, - 0x1e, 0xc2, 0x6a, 0x44, 0x4d, 0xd0, 0x06, 0x9d, 0x9a, 0x67, 0xcc, 0xa6, 0x76, 0xb5, 0xef, 0x07, - 0xd5, 0x88, 0xa2, 0x4f, 0xb0, 0xce, 0x3f, 0x27, 0x2c, 0x33, 0xab, 0x6d, 0xd0, 0xd9, 0xf0, 0xde, - 0xfe, 0x9e, 0xda, 0xdd, 0x30, 0x92, 0xc7, 0x93, 0xa1, 0x43, 0xf8, 0xb8, 0x18, 0xa1, 0x78, 0x74, - 0x05, 0x3d, 0x71, 0xe5, 0x79, 0xca, 0x84, 0xb3, 0x4f, 0xc8, 0x3e, 0xa5, 0x19, 0x13, 0xe2, 0xe6, - 0xb2, 0x7b, 0xbf, 0x18, 0xb4, 0xc8, 0x78, 0xe7, 0x92, 0x89, 0x20, 0xa7, 0x45, 0x08, 0xd6, 0x14, - 0xc2, 0x5c, 0x69, 0x83, 0x4e, 0x23, 0xd0, 0x67, 0xf4, 0x1a, 0x42, 0xc2, 0xe3, 0x18, 0x4b, 0x96, - 0xe1, 0xd8, 0xac, 0xb5, 0x41, 0x67, 0xfd, 0xe9, 0xb6, 0x53, 0x90, 0xa8, 0xd5, 0xcc, 0xf7, 0xe5, - 0xf4, 0x78, 0x94, 0x78, 0xb5, 0xab, 0xa9, 0x5d, 0x09, 0x16, 0x20, 0xe8, 0x15, 0x6c, 0xa4, 0x59, - 0x94, 0x90, 0x28, 0xc5, 0xb1, 0x59, 0x5f, 0x0e, 0x5f, 0x22, 0xd0, 0x3b, 0xb8, 0x85, 0x09, 0x99, - 0x8c, 0x27, 0x8a, 0x8f, 0x0e, 0x46, 0x8c, 0x09, 0xd3, 0x58, 0x8e, 0xa5, 0xb9, 0x00, 0x3c, 0x60, - 0x4c, 0xa0, 0x37, 0x70, 0x43, 0xe1, 0x07, 0x93, 0x94, 0xaa, 0x9c, 0xb9, 0xaa, 0x79, 0x5a, 0x4e, - 0xae, 0x8b, 0x33, 0xd7, 0xc5, 0x39, 0x9a, 0xeb, 0xe2, 0xad, 0x29, 0xa2, 0x8b, 0x1f, 0x36, 0x08, - 0xd6, 0x15, 0xf2, 0x43, 0x0e, 0x44, 0x0c, 0x36, 0xa3, 0x44, 0xb2, 0x8c, 0x09, 0x39, 0x18, 0x61, - 0x22, 0x79, 0x66, 0xae, 0xa9, 0x9d, 0x79, 0x2f, 0xd5, 0xfd, 0xef, 0x53, 0xfb, 0xf1, 0x12, 0xb2, - 0xf8, 0x8c, 0xdc, 0x5c, 0x76, 0x61, 0xf1, 0x12, 0x3e, 0x23, 0xc1, 0xe6, 0x9c, 0xf4, 0x40, 0x73, - 0xee, 0x7c, 0x05, 0x70, 0xd5, 0x67, 0x29, 0x17, 0x91, 0x44, 0x6d, 0x68, 0x10, 0x9a, 0x0e, 0xee, - 0x7c, 0xd1, 0x98, 0x4d, 0xed, 0x7a, 0x8f, 0xa6, 0x7d, 0x3f, 0xa8, 0x13, 0x9a, 0xf6, 0x29, 0x1a, - 0xc1, 0x06, 0xcd, 0x2f, 0xf3, 0xdc, 0x21, 0x8d, 0x7f, 0xe8, 0x90, 0x92, 0x1a, 0xbd, 0x80, 0x06, - 0x1e, 0xf3, 0x49, 0x22, 0xb5, 0x4f, 0x96, 0xd0, 0xa1, 0xb8, 0xbe, 0x93, 0xc1, 0xcd, 0x23, 0x2e, - 0x71, 0x7c, 0x78, 0x27, 0xee, 0x13, 0xd8, 0x2c, 0x9d, 0x32, 0xd0, 0xde, 0x03, 0xda, 0x7b, 0x9b, - 0x65, 0xfa, 0x48, 0xb9, 0xb0, 0xec, 0x59, 0xfd, 0xbb, 0x9e, 0x02, 0x36, 0x75, 0xcf, 0x5e, 0x69, - 0xc8, 0xff, 0xdf, 0xf4, 0x39, 0xbc, 0xf7, 0x5e, 0x7d, 0x50, 0x3d, 0xff, 0xb0, 0x9f, 0x50, 0x76, - 0x86, 0x1e, 0xc1, 0xd5, 0x5c, 0x3c, 0x61, 0x82, 0xf6, 0x4a, 0xa7, 0xe6, 0xc1, 0xd9, 0xd4, 0x36, - 0xb4, 0x7a, 0x22, 0x30, 0xb4, 0x7c, 0xc2, 0xf3, 0xaf, 0x7e, 0x59, 0x95, 0xab, 0x99, 0x05, 0xae, - 0x67, 0x16, 0xf8, 0x39, 0xb3, 0xc0, 0xc5, 0xad, 0x55, 0xb9, 0xbe, 0xb5, 0x2a, 0xdf, 0x6e, 0xad, - 0xca, 0xc7, 0x45, 0x47, 0xed, 0x86, 0x31, 0x1e, 0x0a, 0x77, 0x37, 0xec, 0x92, 0x63, 0x1c, 0x25, - 0xee, 0x99, 0xfe, 0xa7, 0x69, 0x29, 0x87, 0x86, 0x76, 0xf1, 0xb3, 0x3f, 0x01, 0x00, 0x00, 0xff, - 0xff, 0xac, 0x93, 0x62, 0xcb, 0xec, 0x04, 0x00, 0x00, -} - -func (m *CDP) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CDP) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CDP) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.InterestFactor.Size() - i -= size - if _, err := m.InterestFactor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintCdp(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - n1, err1 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.FeesUpdated, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.FeesUpdated):]) - if err1 != nil { - return 0, err1 - } - i -= n1 - i = encodeVarintCdp(dAtA, i, uint64(n1)) - i-- - dAtA[i] = 0x3a - { - size, err := m.AccumulatedFees.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintCdp(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size, err := m.Principal.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintCdp(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.Collateral.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintCdp(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - if len(m.Type) > 0 { - i -= len(m.Type) - copy(dAtA[i:], m.Type) - i = encodeVarintCdp(dAtA, i, uint64(len(m.Type))) - i-- - dAtA[i] = 0x1a - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintCdp(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if m.ID != 0 { - i = encodeVarintCdp(dAtA, i, uint64(m.ID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *Deposit) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Deposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Deposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintCdp(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintCdp(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0x12 - } - if m.CdpID != 0 { - i = encodeVarintCdp(dAtA, i, uint64(m.CdpID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *TotalPrincipal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TotalPrincipal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TotalPrincipal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintCdp(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintCdp(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *TotalCollateral) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TotalCollateral) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TotalCollateral) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintCdp(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintCdp(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *OwnerCDPIndex) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *OwnerCDPIndex) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *OwnerCDPIndex) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CdpIDs) > 0 { - dAtA9 := make([]byte, len(m.CdpIDs)*10) - var j8 int - for _, num := range m.CdpIDs { - for num >= 1<<7 { - dAtA9[j8] = uint8(uint64(num)&0x7f | 0x80) - num >>= 7 - j8++ - } - dAtA9[j8] = uint8(num) - j8++ - } - i -= j8 - copy(dAtA[i:], dAtA9[:j8]) - i = encodeVarintCdp(dAtA, i, uint64(j8)) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintCdp(dAtA []byte, offset int, v uint64) int { - offset -= sovCdp(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *CDP) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.ID != 0 { - n += 1 + sovCdp(uint64(m.ID)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovCdp(uint64(l)) - } - l = len(m.Type) - if l > 0 { - n += 1 + l + sovCdp(uint64(l)) - } - l = m.Collateral.Size() - n += 1 + l + sovCdp(uint64(l)) - l = m.Principal.Size() - n += 1 + l + sovCdp(uint64(l)) - l = m.AccumulatedFees.Size() - n += 1 + l + sovCdp(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.FeesUpdated) - n += 1 + l + sovCdp(uint64(l)) - l = m.InterestFactor.Size() - n += 1 + l + sovCdp(uint64(l)) - return n -} - -func (m *Deposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CdpID != 0 { - n += 1 + sovCdp(uint64(m.CdpID)) - } - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovCdp(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovCdp(uint64(l)) - return n -} - -func (m *TotalPrincipal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovCdp(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovCdp(uint64(l)) - return n -} - -func (m *TotalCollateral) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovCdp(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovCdp(uint64(l)) - return n -} - -func (m *OwnerCDPIndex) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.CdpIDs) > 0 { - l = 0 - for _, e := range m.CdpIDs { - l += sovCdp(uint64(e)) - } - n += 1 + sovCdp(uint64(l)) + l - } - return n -} - -func sovCdp(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozCdp(x uint64) (n int) { - return sovCdp(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *CDP) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CDP: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CDP: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - m.ID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = append(m.Owner[:0], dAtA[iNdEx:postIndex]...) - if m.Owner == nil { - m.Owner = []byte{} - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Type = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Collateral", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Collateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Principal", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Principal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AccumulatedFees", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.AccumulatedFees.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FeesUpdated", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.FeesUpdated, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InterestFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.InterestFactor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipCdp(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthCdp - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Deposit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Deposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Deposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CdpID", wireType) - } - m.CdpID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CdpID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = github_com_cosmos_cosmos_sdk_types.AccAddress(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipCdp(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthCdp - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TotalPrincipal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TotalPrincipal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TotalPrincipal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipCdp(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthCdp - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TotalCollateral) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TotalCollateral: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TotalCollateral: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipCdp(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthCdp - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *OwnerCDPIndex) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: OwnerCDPIndex: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: OwnerCDPIndex: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType == 0 { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CdpIDs = append(m.CdpIDs, v) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthCdp - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthCdp - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - var count int - for _, integer := range dAtA[iNdEx:postIndex] { - if integer < 128 { - count++ - } - } - elementCount = count - if elementCount != 0 && len(m.CdpIDs) == 0 { - m.CdpIDs = make([]uint64, 0, elementCount) - } - for iNdEx < postIndex { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCdp - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CdpIDs = append(m.CdpIDs, v) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field CdpIDs", wireType) - } - default: - iNdEx = preIndex - skippy, err := skipCdp(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthCdp - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipCdp(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowCdp - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowCdp - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowCdp - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthCdp - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupCdp - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthCdp - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthCdp = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowCdp = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupCdp = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/cdp/types/cdp_test.go b/x/cdp/types/cdp_test.go deleted file mode 100644 index 24f454c7..00000000 --- a/x/cdp/types/cdp_test.go +++ /dev/null @@ -1,243 +0,0 @@ -package types_test - -import ( - "math/rand" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/cometbft/cometbft/crypto/secp256k1" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/0glabs/0g-chain/x/cdp/types" -) - -type CdpValidationSuite struct { - suite.Suite - - addrs []sdk.AccAddress -} - -func (suite *CdpValidationSuite) SetupTest() { - r := rand.New(rand.NewSource(12345)) - privkeySeed := make([]byte, 15) - r.Read(privkeySeed) - addr := sdk.AccAddress(secp256k1.GenPrivKeySecp256k1(privkeySeed).PubKey().Address()) - suite.addrs = []sdk.AccAddress{addr} -} - -func (suite *CdpValidationSuite) TestCdpValidation() { - type errArgs struct { - expectPass bool - msg string - } - testCases := []struct { - name string - cdp types.CDP - errArgs errArgs - }{ - { - name: "valid cdp", - cdp: types.NewCDP(1, suite.addrs[0], sdk.NewInt64Coin("bnb", 100000), "bnb-a", sdk.NewInt64Coin("usdx", 100000), tmtime.Now(), sdk.OneDec()), - errArgs: errArgs{ - expectPass: true, - msg: "", - }, - }, - { - name: "invalid cdp id", - cdp: types.NewCDP(0, suite.addrs[0], sdk.NewInt64Coin("bnb", 100000), "bnb-a", sdk.NewInt64Coin("usdx", 100000), tmtime.Now(), sdk.OneDec()), - errArgs: errArgs{ - expectPass: false, - msg: "cdp id cannot be 0", - }, - }, - { - name: "invalid collateral", - 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", - }, - }, - { - name: "invalid principal", - 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", - }, - }, - { - name: "invalid fees", - 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", - }, - }, - { - name: "invalid fees updated", - 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", - }, - }, - { - name: "invalid type", - 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", - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - err := tc.cdp.Validate() - if tc.errArgs.expectPass { - suite.Require().NoError(err, tc.name) - } else { - suite.Require().Error(err, tc.name) - suite.Require().Equal(err.Error(), tc.errArgs.msg) - } - }) - } -} - -func (suite *CdpValidationSuite) TestDepositValidation() { - type errArgs struct { - expectPass bool - msg string - } - testCases := []struct { - name string - deposit types.Deposit - errArgs errArgs - }{ - { - name: "valid deposit", - deposit: types.NewDeposit(1, suite.addrs[0], sdk.NewInt64Coin("bnb", 1000000)), - errArgs: errArgs{ - expectPass: true, - msg: "", - }, - }, - { - name: "invalid cdp id", - deposit: types.NewDeposit(0, suite.addrs[0], sdk.NewInt64Coin("bnb", 1000000)), - errArgs: errArgs{ - expectPass: false, - msg: "deposit's cdp id cannot be 0", - }, - }, - { - name: "empty depositor", - deposit: types.NewDeposit(1, sdk.AccAddress{}, sdk.NewInt64Coin("bnb", 1000000)), - errArgs: errArgs{ - expectPass: false, - msg: "depositor cannot be empty", - }, - }, - { - name: "invalid deposit coins", - 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", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - err := tc.deposit.Validate() - if tc.errArgs.expectPass { - suite.Require().NoError(err, tc.name) - } else { - suite.Require().Error(err, tc.name) - suite.Require().Equal(err.Error(), tc.errArgs.msg) - } - }) - } -} - -func (suite *CdpValidationSuite) TestCdpGetTotalPrinciple() { - principal := sdk.Coin{"usdx", sdkmath.NewInt(100500)} - accumulatedFees := sdk.Coin{"usdx", sdkmath.NewInt(25000)} - - cdp := types.CDP{Principal: principal, AccumulatedFees: accumulatedFees} - - suite.Require().Equal(cdp.GetTotalPrincipal(), principal.Add(accumulatedFees)) -} - -func (suite *CdpValidationSuite) TestCDPGetNormalizedPrincipal() { - type expectedErr struct { - expectPass bool - contains string - } - testCases := []struct { - name string - cdp types.CDP - expected sdk.Dec - expectedErr expectedErr - }{ - { - name: "principal + fees is divided by factor correctly", - cdp: types.CDP{ - Principal: sdk.NewInt64Coin("usdx", 1e9), - AccumulatedFees: sdk.NewInt64Coin("usdx", 1e6), - InterestFactor: sdk.MustNewDecFromStr("2"), - }, - expected: sdk.MustNewDecFromStr("500500000"), - expectedErr: expectedErr{ - expectPass: true, - }, - }, - { - name: "factor < 1 returns error", - cdp: types.CDP{ - Principal: sdk.NewInt64Coin("usdx", 1e9), - AccumulatedFees: sdk.NewInt64Coin("usdx", 1e6), - InterestFactor: sdk.MustNewDecFromStr("0.999999999999999999"), - }, - expectedErr: expectedErr{ - contains: "must be ≥ 1", - }, - }, - { - name: "0 factor returns error rather than div by 0 panic", - cdp: types.CDP{ - Principal: sdk.NewInt64Coin("usdx", 1e9), - AccumulatedFees: sdk.NewInt64Coin("usdx", 1e6), - InterestFactor: sdk.MustNewDecFromStr("0"), - }, - expectedErr: expectedErr{ - contains: "must be ≥ 1", - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - np, err := tc.cdp.GetNormalizedPrincipal() - - if tc.expectedErr.expectPass { - suite.Require().NoError(err, tc.name) - suite.Equal(tc.expected, np) - } else { - suite.Require().Error(err, tc.name) - suite.Contains(err.Error(), tc.expectedErr.contains) - } - }) - } -} - -func TestCdpValidationSuite(t *testing.T) { - suite.Run(t, new(CdpValidationSuite)) -} diff --git a/x/cdp/types/codec.go b/x/cdp/types/codec.go deleted file mode 100644 index 08066e63..00000000 --- a/x/cdp/types/codec.go +++ /dev/null @@ -1,48 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the -// governance module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgCreateCDP{}, "cdp/MsgCreateCDP", nil) - cdc.RegisterConcrete(&MsgDeposit{}, "cdp/MsgDeposit", nil) - cdc.RegisterConcrete(&MsgWithdraw{}, "cdp/MsgWithdraw", nil) - cdc.RegisterConcrete(&MsgDrawDebt{}, "cdp/MsgDrawDebt", nil) - cdc.RegisterConcrete(&MsgRepayDebt{}, "cdp/MsgRepayDebt", nil) - cdc.RegisterConcrete(&MsgLiquidate{}, "cdp/MsgLiquidate", nil) -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgCreateCDP{}, - &MsgDeposit{}, - &MsgWithdraw{}, - &MsgDrawDebt{}, - &MsgRepayDebt{}, - &MsgLiquidate{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/cdp/types/deposit.go b/x/cdp/types/deposit.go deleted file mode 100644 index 5104ffcc..00000000 --- a/x/cdp/types/deposit.go +++ /dev/null @@ -1,63 +0,0 @@ -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" -) - -// NewDeposit creates a new Deposit object -func NewDeposit(cdpID uint64, depositor sdk.AccAddress, amount sdk.Coin) Deposit { - return Deposit{cdpID, depositor, amount} -} - -// Validate performs a basic validation of the deposit fields. -func (d Deposit) Validate() error { - if d.CdpID == 0 { - return errors.New("deposit's cdp id cannot be 0") - } - if d.Depositor.Empty() { - return errors.New("depositor cannot be empty") - } - if !d.Amount.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "deposit %s", d.Amount) - } - return nil -} - -// Deposits a collection of Deposit objects -type Deposits []Deposit - -// Validate validates each deposit -func (ds Deposits) Validate() error { - for _, d := range ds { - if err := d.Validate(); err != nil { - return err - } - } - return nil -} - -// Equals returns whether two deposits are equal. -func (d Deposit) Equals(comp Deposit) bool { - return d.Depositor.Equals(comp.Depositor) && d.CdpID == comp.CdpID && d.Amount.IsEqual(comp.Amount) -} - -// Empty returns whether a deposit is empty. -func (d Deposit) Empty() bool { - return d.Equals(Deposit{}) -} - -// SumCollateral returns the total amount of collateral in the input deposits -func (ds Deposits) SumCollateral() (sum sdkmath.Int) { - sum = sdk.ZeroInt() - for _, d := range ds { - if !d.Amount.IsZero() { - sum = sum.Add(d.Amount.Amount) - } - } - return -} diff --git a/x/cdp/types/errors.go b/x/cdp/types/errors.go deleted file mode 100644 index da31d130..00000000 --- a/x/cdp/types/errors.go +++ /dev/null @@ -1,52 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -// DONTCOVER - -var ( - // ErrCdpAlreadyExists error for duplicate cdps - ErrCdpAlreadyExists = errorsmod.Register(ModuleName, 2, "cdp already exists") - // ErrInvalidCollateralLength error for invalid collateral input length - ErrInvalidCollateralLength = errorsmod.Register(ModuleName, 3, "only one collateral type per cdp") - // ErrCollateralNotSupported error for unsupported collateral - ErrCollateralNotSupported = errorsmod.Register(ModuleName, 4, "collateral not supported") - // ErrDebtNotSupported error for unsupported debt - ErrDebtNotSupported = errorsmod.Register(ModuleName, 5, "debt not supported") - // ErrExceedsDebtLimit error for attempted draws that 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 = errorsmod.Register(ModuleName, 7, "proposed collateral ratio is below liquidation ratio") - // ErrCdpNotFound error cdp not found - ErrCdpNotFound = errorsmod.Register(ModuleName, 8, "cdp not found") - // ErrDepositNotFound error for deposit not found - ErrDepositNotFound = errorsmod.Register(ModuleName, 9, "deposit not found") - // ErrInvalidDeposit error for invalid deposit - ErrInvalidDeposit = errorsmod.Register(ModuleName, 10, "invalid deposit") - // ErrInvalidPayment error for invalid payment - ErrInvalidPayment = errorsmod.Register(ModuleName, 11, "invalid payment") - // ErrDepositNotAvailable error for withdrawing deposits in liquidation - ErrDepositNotAvailable = errorsmod.Register(ModuleName, 12, "deposit in liquidation") - // ErrInvalidWithdrawAmount error for invalid withdrawal amount - ErrInvalidWithdrawAmount = errorsmod.Register(ModuleName, 13, "withdrawal amount exceeds deposit") - // ErrCdpNotAvailable error for depositing to a 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 = errorsmod.Register(ModuleName, 15, "proposed cdp debt is below minimum") - // ErrLoadingAugmentedCDP error loading augmented cdp - ErrLoadingAugmentedCDP = errorsmod.Register(ModuleName, 16, "augmented cdp could not be loaded from cdp") - // ErrInvalidDebtRequest error for invalid principal input length - ErrInvalidDebtRequest = errorsmod.Register(ModuleName, 17, "only one principal type per cdp") - // ErrDenomPrefixNotFound error for 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 = 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 = errorsmod.Register(ModuleName, 20, "invalid collateral for input collateral type") - // ErrAccountNotFound error for when no account is found for an input address - ErrAccountNotFound = errorsmod.Register(ModuleName, 21, "account not found") - // ErrInsufficientBalance error for when an account does not have enough funds - ErrInsufficientBalance = errorsmod.Register(ModuleName, 22, "insufficient balance") - // ErrNotLiquidatable error for when an cdp is not liquidatable - ErrNotLiquidatable = errorsmod.Register(ModuleName, 23, "cdp collateral ratio not below liquidation ratio") -) diff --git a/x/cdp/types/events.go b/x/cdp/types/events.go deleted file mode 100644 index 793fe55a..00000000 --- a/x/cdp/types/events.go +++ /dev/null @@ -1,18 +0,0 @@ -package types - -// Event types for cdp module -const ( - EventTypeCreateCdp = "create_cdp" - EventTypeCdpDeposit = "cdp_deposit" - EventTypeCdpDraw = "cdp_draw" - EventTypeCdpRepay = "cdp_repayment" - EventTypeCdpClose = "cdp_close" - EventTypeCdpWithdrawal = "cdp_withdrawal" - EventTypeCdpLiquidation = "cdp_liquidation" - EventTypeBeginBlockerFatal = "cdp_begin_block_error" - - AttributeKeyCdpID = "cdp_id" - AttributeKeyDeposit = "deposit" - AttributeValueCategory = "cdp" - AttributeKeyError = "error_message" -) diff --git a/x/cdp/types/expected_keepers.go b/x/cdp/types/expected_keepers.go deleted file mode 100644 index c3db9ac4..00000000 --- a/x/cdp/types/expected_keepers.go +++ /dev/null @@ -1,62 +0,0 @@ -package types - -import ( - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - pftypes "github.com/0glabs/0g-chain/x/pricefeed/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" -) - -// BankKeeper defines the expected bank keeper for module accounts -type BankKeeper interface { - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error - MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error - BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error - - GetSupply(ctx sdk.Context, denom string) sdk.Coin - GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins -} - -var _ BankKeeper = (bankkeeper.Keeper)(nil) - -// PricefeedKeeper defines the expected interface for the pricefeed -type PricefeedKeeper interface { - GetCurrentPrice(sdk.Context, string) (pftypes.CurrentPrice, error) - GetParams(sdk.Context) pftypes.Params - // These are used for testing TODO replace mockApp with keeper in tests to remove these - SetParams(sdk.Context, pftypes.Params) - SetPrice(sdk.Context, sdk.AccAddress, string, sdk.Dec, time.Time) (pftypes.PostedPrice, error) - SetCurrentPrices(sdk.Context, string) error -} - -// AuctionKeeper expected interface for the auction keeper -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 []sdkmath.Int, debt sdk.Coin) (uint64, error) -} - -// AccountKeeper expected interface for the account keeper -type AccountKeeper interface { - GetModuleAddress(name string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, name string) authtypes.ModuleAccountI - // TODO remove with genesis 2-phases refactor https://github.com/cosmos/cosmos-sdk/issues/2862 - SetModuleAccount(sdk.Context, authtypes.ModuleAccountI) - - IterateAccounts(ctx sdk.Context, cb func(account authtypes.AccountI) (stop bool)) - GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI -} - -// CDPHooks event hooks for other keepers to run code in response to CDP modifications -type CDPHooks interface { - AfterCDPCreated(ctx sdk.Context, cdp CDP) - BeforeCDPModified(ctx sdk.Context, cdp CDP) -} diff --git a/x/cdp/types/genesis.go b/x/cdp/types/genesis.go deleted file mode 100644 index cf51b7a2..00000000 --- a/x/cdp/types/genesis.go +++ /dev/null @@ -1,138 +0,0 @@ -package types - -import ( - "fmt" - "strings" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// NewGenesisState returns a new genesis state -func NewGenesisState(params Params, cdps CDPs, deposits Deposits, startingCdpID uint64, - debtDenom, govDenom string, prevAccumTimes GenesisAccumulationTimes, - totalPrincipals GenesisTotalPrincipals, -) GenesisState { - return GenesisState{ - Params: params, - CDPs: cdps, - Deposits: deposits, - StartingCdpID: startingCdpID, - DebtDenom: debtDenom, - GovDenom: govDenom, - PreviousAccumulationTimes: prevAccumTimes, - TotalPrincipals: totalPrincipals, - } -} - -// DefaultGenesisState returns a default genesis state -func DefaultGenesisState() GenesisState { - return NewGenesisState( - DefaultParams(), - CDPs{}, - Deposits{}, - DefaultCdpStartingID, - DefaultDebtDenom, - DefaultGovDenom, - GenesisAccumulationTimes{}, - GenesisTotalPrincipals{}, - ) -} - -// Validate performs basic validation of genesis data returning an -// error for any failed validation criteria. -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - - if err := gs.CDPs.Validate(); err != nil { - return err - } - - if err := gs.Deposits.Validate(); err != nil { - return err - } - - if err := gs.PreviousAccumulationTimes.Validate(); err != nil { - return err - } - - if err := gs.TotalPrincipals.Validate(); err != nil { - return err - } - - if err := sdk.ValidateDenom(gs.DebtDenom); err != nil { - return fmt.Errorf(fmt.Sprintf("debt denom invalid: %v", err)) - } - - if err := sdk.ValidateDenom(gs.GovDenom); err != nil { - return fmt.Errorf(fmt.Sprintf("gov denom invalid: %v", err)) - } - - return nil -} - -// NewGenesisTotalPrincipal returns a new GenesisTotalPrincipal -func NewGenesisTotalPrincipal(ctype string, principal sdkmath.Int) GenesisTotalPrincipal { - return GenesisTotalPrincipal{ - CollateralType: ctype, - TotalPrincipal: principal, - } -} - -// GenesisTotalPrincipals slice of GenesisTotalPrincipal -type GenesisTotalPrincipals []GenesisTotalPrincipal - -// Validate performs validation of GenesisTotalPrincipal -func (gtp GenesisTotalPrincipal) Validate() error { - if strings.TrimSpace(gtp.CollateralType) == "" { - return fmt.Errorf("collateral type cannot be empty") - } - - if gtp.TotalPrincipal.IsNegative() { - return fmt.Errorf("total principal should be positive, is %s for %s", gtp.TotalPrincipal, gtp.CollateralType) - } - return nil -} - -// Validate performs validation of GenesisTotalPrincipals -func (gtps GenesisTotalPrincipals) Validate() error { - for _, gtp := range gtps { - if err := gtp.Validate(); err != nil { - return err - } - } - return nil -} - -// NewGenesisAccumulationTime returns a new GenesisAccumulationTime -func NewGenesisAccumulationTime(ctype string, prevTime time.Time, factor sdk.Dec) GenesisAccumulationTime { - return GenesisAccumulationTime{ - CollateralType: ctype, - PreviousAccumulationTime: prevTime, - InterestFactor: factor, - } -} - -// Validate performs validation of GenesisAccumulationTime -func (gat GenesisAccumulationTime) Validate() error { - if gat.InterestFactor.LT(sdk.OneDec()) { - return fmt.Errorf("interest factor should be ≥ 1.0, is %s for %s", gat.InterestFactor, gat.CollateralType) - } - return nil -} - -// GenesisAccumulationTimes slice of GenesisAccumulationTime -type GenesisAccumulationTimes []GenesisAccumulationTime - -// Validate performs validation of GenesisAccumulationTimes -func (gats GenesisAccumulationTimes) Validate() error { - for _, gat := range gats { - if err := gat.Validate(); err != nil { - return err - } - } - return nil -} diff --git a/x/cdp/types/genesis.pb.go b/x/cdp/types/genesis.pb.go deleted file mode 100644 index b9a5d937..00000000 --- a/x/cdp/types/genesis.pb.go +++ /dev/null @@ -1,2838 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/cdp/v1beta1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// GenesisState defines the cdp module's genesis state. -type GenesisState struct { - // params defines all the parameters of the module. - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - CDPs CDPs `protobuf:"bytes,2,rep,name=cdps,proto3,castrepeated=CDPs" json:"cdps"` - Deposits Deposits `protobuf:"bytes,3,rep,name=deposits,proto3,castrepeated=Deposits" json:"deposits"` - StartingCdpID uint64 `protobuf:"varint,4,opt,name=starting_cdp_id,json=startingCdpId,proto3" json:"starting_cdp_id,omitempty"` - DebtDenom string `protobuf:"bytes,5,opt,name=debt_denom,json=debtDenom,proto3" json:"debt_denom,omitempty"` - GovDenom string `protobuf:"bytes,6,opt,name=gov_denom,json=govDenom,proto3" json:"gov_denom,omitempty"` - PreviousAccumulationTimes GenesisAccumulationTimes `protobuf:"bytes,7,rep,name=previous_accumulation_times,json=previousAccumulationTimes,proto3,castrepeated=GenesisAccumulationTimes" json:"previous_accumulation_times"` - TotalPrincipals GenesisTotalPrincipals `protobuf:"bytes,8,rep,name=total_principals,json=totalPrincipals,proto3,castrepeated=GenesisTotalPrincipals" json:"total_principals"` -} - -func (m *GenesisState) Reset() { *m = GenesisState{} } -func (m *GenesisState) String() string { return proto.CompactTextString(m) } -func (*GenesisState) ProtoMessage() {} -func (*GenesisState) Descriptor() ([]byte, []int) { - return fileDescriptor_e4494a90aaab0034, []int{0} -} -func (m *GenesisState) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisState) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisState.Merge(m, src) -} -func (m *GenesisState) XXX_Size() int { - return m.Size() -} -func (m *GenesisState) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisState.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisState proto.InternalMessageInfo - -func (m *GenesisState) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -func (m *GenesisState) GetCDPs() CDPs { - if m != nil { - return m.CDPs - } - return nil -} - -func (m *GenesisState) GetDeposits() Deposits { - if m != nil { - return m.Deposits - } - return nil -} - -func (m *GenesisState) GetStartingCdpID() uint64 { - if m != nil { - return m.StartingCdpID - } - return 0 -} - -func (m *GenesisState) GetDebtDenom() string { - if m != nil { - return m.DebtDenom - } - return "" -} - -func (m *GenesisState) GetGovDenom() string { - if m != nil { - return m.GovDenom - } - return "" -} - -func (m *GenesisState) GetPreviousAccumulationTimes() GenesisAccumulationTimes { - if m != nil { - return m.PreviousAccumulationTimes - } - return nil -} - -func (m *GenesisState) GetTotalPrincipals() GenesisTotalPrincipals { - if m != nil { - return m.TotalPrincipals - } - return nil -} - -// Params defines the parameters for the cdp module. -type Params struct { - CollateralParams CollateralParams `protobuf:"bytes,1,rep,name=collateral_params,json=collateralParams,proto3,castrepeated=CollateralParams" json:"collateral_params"` - DebtParam DebtParam `protobuf:"bytes,2,opt,name=debt_param,json=debtParam,proto3" json:"debt_param"` - GlobalDebtLimit types.Coin `protobuf:"bytes,3,opt,name=global_debt_limit,json=globalDebtLimit,proto3" json:"global_debt_limit"` - SurplusAuctionThreshold github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,4,opt,name=surplus_auction_threshold,json=surplusAuctionThreshold,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"surplus_auction_threshold"` - SurplusAuctionLot github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,5,opt,name=surplus_auction_lot,json=surplusAuctionLot,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"surplus_auction_lot"` - DebtAuctionThreshold github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,6,opt,name=debt_auction_threshold,json=debtAuctionThreshold,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"debt_auction_threshold"` - DebtAuctionLot github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,7,opt,name=debt_auction_lot,json=debtAuctionLot,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"debt_auction_lot"` - CircuitBreaker bool `protobuf:"varint,8,opt,name=circuit_breaker,json=circuitBreaker,proto3" json:"circuit_breaker,omitempty"` - LiquidationBlockInterval int64 `protobuf:"varint,9,opt,name=liquidation_block_interval,json=liquidationBlockInterval,proto3" json:"liquidation_block_interval,omitempty"` -} - -func (m *Params) Reset() { *m = Params{} } -func (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_e4494a90aaab0034, []int{1} -} -func (m *Params) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Params.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Params) XXX_Merge(src proto.Message) { - xxx_messageInfo_Params.Merge(m, src) -} -func (m *Params) XXX_Size() int { - return m.Size() -} -func (m *Params) XXX_DiscardUnknown() { - xxx_messageInfo_Params.DiscardUnknown(m) -} - -var xxx_messageInfo_Params proto.InternalMessageInfo - -func (m *Params) GetCollateralParams() CollateralParams { - if m != nil { - return m.CollateralParams - } - return nil -} - -func (m *Params) GetDebtParam() DebtParam { - if m != nil { - return m.DebtParam - } - return DebtParam{} -} - -func (m *Params) GetGlobalDebtLimit() types.Coin { - if m != nil { - return m.GlobalDebtLimit - } - return types.Coin{} -} - -func (m *Params) GetCircuitBreaker() bool { - if m != nil { - return m.CircuitBreaker - } - return false -} - -func (m *Params) GetLiquidationBlockInterval() int64 { - if m != nil { - return m.LiquidationBlockInterval - } - return 0 -} - -// DebtParam defines governance params for debt assets -type DebtParam struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - ReferenceAsset string `protobuf:"bytes,2,opt,name=reference_asset,json=referenceAsset,proto3" json:"reference_asset,omitempty"` - ConversionFactor github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=conversion_factor,json=conversionFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"conversion_factor"` - DebtFloor github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,4,opt,name=debt_floor,json=debtFloor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"debt_floor"` -} - -func (m *DebtParam) Reset() { *m = DebtParam{} } -func (m *DebtParam) String() string { return proto.CompactTextString(m) } -func (*DebtParam) ProtoMessage() {} -func (*DebtParam) Descriptor() ([]byte, []int) { - return fileDescriptor_e4494a90aaab0034, []int{2} -} -func (m *DebtParam) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DebtParam) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DebtParam.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *DebtParam) XXX_Merge(src proto.Message) { - xxx_messageInfo_DebtParam.Merge(m, src) -} -func (m *DebtParam) XXX_Size() int { - return m.Size() -} -func (m *DebtParam) XXX_DiscardUnknown() { - xxx_messageInfo_DebtParam.DiscardUnknown(m) -} - -var xxx_messageInfo_DebtParam proto.InternalMessageInfo - -func (m *DebtParam) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *DebtParam) GetReferenceAsset() string { - if m != nil { - return m.ReferenceAsset - } - return "" -} - -// CollateralParam defines governance parameters for each collateral type within the cdp module -type CollateralParam struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Type string `protobuf:"bytes,2,opt,name=type,proto3" json:"type,omitempty"` - LiquidationRatio github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=liquidation_ratio,json=liquidationRatio,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"liquidation_ratio"` - DebtLimit types.Coin `protobuf:"bytes,4,opt,name=debt_limit,json=debtLimit,proto3" json:"debt_limit"` - StabilityFee github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=stability_fee,json=stabilityFee,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"stability_fee"` - AuctionSize github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,6,opt,name=auction_size,json=auctionSize,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"auction_size"` - LiquidationPenalty github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,7,opt,name=liquidation_penalty,json=liquidationPenalty,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"liquidation_penalty"` - SpotMarketID string `protobuf:"bytes,8,opt,name=spot_market_id,json=spotMarketId,proto3" json:"spot_market_id,omitempty"` - LiquidationMarketID string `protobuf:"bytes,9,opt,name=liquidation_market_id,json=liquidationMarketId,proto3" json:"liquidation_market_id,omitempty"` - KeeperRewardPercentage github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,10,opt,name=keeper_reward_percentage,json=keeperRewardPercentage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"keeper_reward_percentage"` - CheckCollateralizationIndexCount github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,11,opt,name=check_collateralization_index_count,json=checkCollateralizationIndexCount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"check_collateralization_index_count"` - ConversionFactor github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,12,opt,name=conversion_factor,json=conversionFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"conversion_factor"` -} - -func (m *CollateralParam) Reset() { *m = CollateralParam{} } -func (m *CollateralParam) String() string { return proto.CompactTextString(m) } -func (*CollateralParam) ProtoMessage() {} -func (*CollateralParam) Descriptor() ([]byte, []int) { - return fileDescriptor_e4494a90aaab0034, []int{3} -} -func (m *CollateralParam) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CollateralParam) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CollateralParam.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CollateralParam) XXX_Merge(src proto.Message) { - xxx_messageInfo_CollateralParam.Merge(m, src) -} -func (m *CollateralParam) XXX_Size() int { - return m.Size() -} -func (m *CollateralParam) XXX_DiscardUnknown() { - xxx_messageInfo_CollateralParam.DiscardUnknown(m) -} - -var xxx_messageInfo_CollateralParam proto.InternalMessageInfo - -func (m *CollateralParam) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *CollateralParam) GetType() string { - if m != nil { - return m.Type - } - return "" -} - -func (m *CollateralParam) GetDebtLimit() types.Coin { - if m != nil { - return m.DebtLimit - } - return types.Coin{} -} - -func (m *CollateralParam) GetSpotMarketID() string { - if m != nil { - return m.SpotMarketID - } - return "" -} - -func (m *CollateralParam) GetLiquidationMarketID() string { - if m != nil { - return m.LiquidationMarketID - } - return "" -} - -// GenesisAccumulationTime defines the previous distribution time and its corresponding denom -type GenesisAccumulationTime struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - PreviousAccumulationTime time.Time `protobuf:"bytes,2,opt,name=previous_accumulation_time,json=previousAccumulationTime,proto3,stdtime" json:"previous_accumulation_time"` - InterestFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=interest_factor,json=interestFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"interest_factor"` -} - -func (m *GenesisAccumulationTime) Reset() { *m = GenesisAccumulationTime{} } -func (m *GenesisAccumulationTime) String() string { return proto.CompactTextString(m) } -func (*GenesisAccumulationTime) ProtoMessage() {} -func (*GenesisAccumulationTime) Descriptor() ([]byte, []int) { - return fileDescriptor_e4494a90aaab0034, []int{4} -} -func (m *GenesisAccumulationTime) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisAccumulationTime) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisAccumulationTime.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisAccumulationTime) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisAccumulationTime.Merge(m, src) -} -func (m *GenesisAccumulationTime) XXX_Size() int { - return m.Size() -} -func (m *GenesisAccumulationTime) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisAccumulationTime.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisAccumulationTime proto.InternalMessageInfo - -func (m *GenesisAccumulationTime) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -func (m *GenesisAccumulationTime) GetPreviousAccumulationTime() time.Time { - if m != nil { - return m.PreviousAccumulationTime - } - return time.Time{} -} - -// GenesisTotalPrincipal defines the total principal and its corresponding collateral type -type GenesisTotalPrincipal struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - TotalPrincipal github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,opt,name=total_principal,json=totalPrincipal,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"total_principal"` -} - -func (m *GenesisTotalPrincipal) Reset() { *m = GenesisTotalPrincipal{} } -func (m *GenesisTotalPrincipal) String() string { return proto.CompactTextString(m) } -func (*GenesisTotalPrincipal) ProtoMessage() {} -func (*GenesisTotalPrincipal) Descriptor() ([]byte, []int) { - return fileDescriptor_e4494a90aaab0034, []int{5} -} -func (m *GenesisTotalPrincipal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisTotalPrincipal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisTotalPrincipal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisTotalPrincipal) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisTotalPrincipal.Merge(m, src) -} -func (m *GenesisTotalPrincipal) XXX_Size() int { - return m.Size() -} -func (m *GenesisTotalPrincipal) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisTotalPrincipal.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisTotalPrincipal proto.InternalMessageInfo - -func (m *GenesisTotalPrincipal) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "kava.cdp.v1beta1.GenesisState") - proto.RegisterType((*Params)(nil), "kava.cdp.v1beta1.Params") - proto.RegisterType((*DebtParam)(nil), "kava.cdp.v1beta1.DebtParam") - proto.RegisterType((*CollateralParam)(nil), "kava.cdp.v1beta1.CollateralParam") - proto.RegisterType((*GenesisAccumulationTime)(nil), "kava.cdp.v1beta1.GenesisAccumulationTime") - proto.RegisterType((*GenesisTotalPrincipal)(nil), "kava.cdp.v1beta1.GenesisTotalPrincipal") -} - -func init() { proto.RegisterFile("kava/cdp/v1beta1/genesis.proto", fileDescriptor_e4494a90aaab0034) } - -var fileDescriptor_e4494a90aaab0034 = []byte{ - // 1210 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x57, 0x4f, 0x6f, 0x13, 0x47, - 0x14, 0xcf, 0x26, 0x26, 0xd8, 0x93, 0x10, 0x3b, 0x43, 0x80, 0x4d, 0x50, 0x6d, 0x37, 0x95, 0x4a, - 0x7a, 0xc0, 0x06, 0x2a, 0x21, 0x55, 0x42, 0x2d, 0x6c, 0x2c, 0x50, 0x04, 0x95, 0xa2, 0x4d, 0x4e, - 0xed, 0x61, 0x35, 0x3b, 0x3b, 0x5e, 0x8f, 0xbc, 0xde, 0xd9, 0xce, 0x8c, 0x5d, 0xe0, 0x2b, 0x54, - 0x55, 0x51, 0xbf, 0x44, 0x25, 0xd4, 0x63, 0x3f, 0x04, 0xbd, 0xa1, 0x9e, 0xaa, 0x1e, 0x4c, 0x65, - 0xbe, 0x48, 0x35, 0x7f, 0x6c, 0x6f, 0xec, 0x58, 0x42, 0xc1, 0xbd, 0x64, 0x3d, 0xef, 0xcf, 0xef, - 0xfd, 0x99, 0xf7, 0xde, 0xbc, 0x80, 0x6a, 0x17, 0x0d, 0x50, 0x13, 0x47, 0x59, 0x73, 0x70, 0x37, - 0x24, 0x12, 0xdd, 0x6d, 0xc6, 0x24, 0x25, 0x82, 0x8a, 0x46, 0xc6, 0x99, 0x64, 0xb0, 0xa2, 0xf8, - 0x0d, 0x1c, 0x65, 0x0d, 0xcb, 0xdf, 0xab, 0x62, 0x26, 0x7a, 0x4c, 0x34, 0x43, 0x24, 0xc8, 0x44, - 0x09, 0x33, 0x9a, 0x1a, 0x8d, 0xbd, 0x5d, 0xc3, 0x0f, 0xf4, 0xa9, 0x69, 0x0e, 0x96, 0xb5, 0x13, - 0xb3, 0x98, 0x19, 0xba, 0xfa, 0x65, 0xa9, 0xb5, 0x98, 0xb1, 0x38, 0x21, 0x4d, 0x7d, 0x0a, 0xfb, - 0xed, 0xa6, 0xa4, 0x3d, 0x22, 0x24, 0xea, 0x65, 0x56, 0x60, 0x6f, 0xce, 0x47, 0xe5, 0x8f, 0xe6, - 0xed, 0xff, 0x59, 0x00, 0x9b, 0x4f, 0x8c, 0xc7, 0x27, 0x12, 0x49, 0x02, 0xef, 0x83, 0xf5, 0x0c, - 0x71, 0xd4, 0x13, 0xae, 0x53, 0x77, 0x0e, 0x36, 0xee, 0xb9, 0x8d, 0xd9, 0x08, 0x1a, 0xc7, 0x9a, - 0xef, 0x15, 0xde, 0x0c, 0x6b, 0x2b, 0xbe, 0x95, 0x86, 0xdf, 0x80, 0x02, 0x8e, 0x32, 0xe1, 0xae, - 0xd6, 0xd7, 0x0e, 0x36, 0xee, 0x5d, 0x9b, 0xd7, 0x3a, 0x6c, 0x1d, 0x7b, 0x3b, 0x4a, 0x65, 0x34, - 0xac, 0x15, 0x0e, 0x5b, 0xc7, 0xe2, 0xf5, 0x3b, 0xf3, 0xf5, 0xb5, 0x22, 0x7c, 0x02, 0x8a, 0x11, - 0xc9, 0x98, 0xa0, 0x52, 0xb8, 0x6b, 0x1a, 0x64, 0x77, 0x1e, 0xa4, 0x65, 0x24, 0xbc, 0x8a, 0x02, - 0x7a, 0xfd, 0xae, 0x56, 0xb4, 0x04, 0xe1, 0x4f, 0x94, 0xe1, 0x57, 0xa0, 0x2c, 0x24, 0xe2, 0x92, - 0xa6, 0x71, 0x80, 0xa3, 0x2c, 0xa0, 0x91, 0x5b, 0xa8, 0x3b, 0x07, 0x05, 0x6f, 0x7b, 0x34, 0xac, - 0x5d, 0x39, 0xb1, 0xac, 0xc3, 0x28, 0x3b, 0x6a, 0xf9, 0x57, 0x44, 0xee, 0x18, 0xc1, 0x4f, 0x00, - 0x88, 0x48, 0x28, 0x83, 0x88, 0xa4, 0xac, 0xe7, 0x5e, 0xaa, 0x3b, 0x07, 0x25, 0xbf, 0xa4, 0x28, - 0x2d, 0x45, 0x80, 0x37, 0x41, 0x29, 0x66, 0x03, 0xcb, 0x5d, 0xd7, 0xdc, 0x62, 0xcc, 0x06, 0x86, - 0xf9, 0x93, 0x03, 0x6e, 0x66, 0x9c, 0x0c, 0x28, 0xeb, 0x8b, 0x00, 0x61, 0xdc, 0xef, 0xf5, 0x13, - 0x24, 0x29, 0x4b, 0x03, 0x7d, 0x1f, 0xee, 0x65, 0x1d, 0xd3, 0x17, 0xf3, 0x31, 0xd9, 0xf4, 0x3f, - 0xca, 0xa9, 0x9c, 0xd2, 0x1e, 0xf1, 0xea, 0x36, 0x46, 0x77, 0x81, 0x80, 0xf0, 0x77, 0xc7, 0xf6, - 0xe6, 0x58, 0x90, 0x83, 0x8a, 0x64, 0x12, 0x25, 0x41, 0xc6, 0x69, 0x8a, 0x69, 0x86, 0x12, 0xe1, - 0x16, 0xb5, 0x07, 0xb7, 0x16, 0x7a, 0x70, 0xaa, 0x14, 0x8e, 0xc7, 0xf2, 0x5e, 0xd5, 0xda, 0xbf, - 0x7e, 0x2e, 0x5b, 0xf8, 0x65, 0x79, 0x96, 0xb0, 0xff, 0xfb, 0x3a, 0x58, 0x37, 0xb5, 0x01, 0x3b, - 0x60, 0x1b, 0xb3, 0x24, 0x41, 0x92, 0x70, 0xe5, 0xc3, 0xb8, 0xa0, 0x94, 0xfd, 0x4f, 0xcf, 0x29, - 0x8d, 0x89, 0xa8, 0x56, 0xf7, 0x5c, 0x6b, 0xb9, 0x32, 0xc3, 0x10, 0x7e, 0x05, 0xcf, 0x50, 0xe0, - 0x43, 0x7b, 0x65, 0xda, 0x86, 0xbb, 0xaa, 0x6b, 0xf6, 0xe6, 0x79, 0x85, 0x13, 0x4a, 0x03, 0x6e, - 0xca, 0x56, 0xdf, 0xaa, 0x26, 0xc0, 0xa7, 0x60, 0x3b, 0x4e, 0x58, 0x88, 0x92, 0x40, 0x03, 0x25, - 0xb4, 0x47, 0xa5, 0xbb, 0xa6, 0x81, 0x76, 0x1b, 0xb6, 0xff, 0x54, 0xb3, 0xe6, 0xdc, 0xa5, 0xa9, - 0x85, 0x29, 0x1b, 0x4d, 0x85, 0xfe, 0x4c, 0xe9, 0xc1, 0xe7, 0x60, 0x57, 0xf4, 0x79, 0x96, 0xa8, - 0x1a, 0xe8, 0x63, 0x73, 0xfd, 0x1d, 0x4e, 0x44, 0x87, 0x25, 0xa6, 0x0c, 0x4b, 0xde, 0x03, 0xa5, - 0xf9, 0xcf, 0xb0, 0xf6, 0x79, 0x4c, 0x65, 0xa7, 0x1f, 0x36, 0x30, 0xeb, 0xd9, 0x36, 0xb7, 0x9f, - 0xdb, 0x22, 0xea, 0x36, 0xe5, 0x8b, 0x8c, 0x88, 0xc6, 0x51, 0x2a, 0xff, 0xfa, 0xe3, 0x36, 0xb0, - 0x5e, 0x1c, 0xa5, 0xd2, 0xbf, 0x61, 0xe1, 0x1f, 0x19, 0xf4, 0xd3, 0x31, 0x38, 0x4c, 0xc0, 0xd5, - 0x59, 0xcb, 0x09, 0x93, 0xa6, 0x88, 0x3f, 0xd2, 0xe6, 0xf6, 0x59, 0x9b, 0xcf, 0x98, 0x84, 0x1c, - 0x5c, 0xd7, 0xd9, 0x9a, 0x0f, 0x72, 0x7d, 0x09, 0x06, 0x77, 0x14, 0xf6, 0x5c, 0x84, 0x6d, 0x50, - 0x39, 0x63, 0x53, 0x85, 0x77, 0x79, 0x09, 0xd6, 0xb6, 0x72, 0xd6, 0x54, 0x6c, 0xb7, 0x40, 0x19, - 0x53, 0x8e, 0xfb, 0x54, 0x06, 0x21, 0x27, 0xa8, 0x4b, 0xb8, 0x5b, 0xac, 0x3b, 0x07, 0x45, 0x7f, - 0xcb, 0x92, 0x3d, 0x43, 0x85, 0x0f, 0xc0, 0x5e, 0x42, 0x7f, 0xe8, 0xd3, 0xc8, 0xf4, 0x79, 0x98, - 0x30, 0xdc, 0x0d, 0x68, 0x2a, 0x09, 0x1f, 0xa0, 0xc4, 0x2d, 0xd5, 0x9d, 0x83, 0x35, 0xdf, 0xcd, - 0x49, 0x78, 0x4a, 0xe0, 0xc8, 0xf2, 0xf7, 0x7f, 0x5d, 0x05, 0xa5, 0x49, 0x59, 0xc2, 0x1d, 0x70, - 0xc9, 0xcc, 0x15, 0x47, 0xcf, 0x15, 0x73, 0x50, 0xae, 0x70, 0xd2, 0x26, 0x9c, 0xa4, 0x98, 0x04, - 0x48, 0x08, 0x22, 0x75, 0x89, 0x97, 0xfc, 0xad, 0x09, 0xf9, 0x91, 0xa2, 0x42, 0xaa, 0x1a, 0x2e, - 0x1d, 0x10, 0x2e, 0x94, 0x27, 0x6d, 0x84, 0x25, 0xe3, 0xba, 0x88, 0x3f, 0x36, 0x39, 0x95, 0x29, - 0xec, 0x63, 0x8d, 0x0a, 0xbf, 0xb7, 0x1d, 0xd7, 0x4e, 0x18, 0xe3, 0x4b, 0xa9, 0x69, 0xdd, 0x8c, - 0x8f, 0x15, 0xdc, 0xfe, 0x2f, 0x45, 0x50, 0x9e, 0xe9, 0xfa, 0x05, 0xa9, 0x81, 0xa0, 0xa0, 0xf0, - 0x6c, 0x3e, 0xf4, 0x6f, 0x95, 0x85, 0xfc, 0x85, 0x70, 0xf5, 0xb9, 0x40, 0x16, 0x5a, 0x04, 0xe7, - 0x3c, 0x6c, 0x11, 0xec, 0x57, 0x72, 0xb0, 0xbe, 0xfa, 0x0b, 0xbf, 0xb6, 0x59, 0x30, 0xe3, 0xa2, - 0xf0, 0x61, 0xe3, 0x42, 0x07, 0x6a, 0x06, 0x05, 0x02, 0xea, 0xed, 0x09, 0x69, 0x42, 0xe5, 0x8b, - 0xa0, 0x4d, 0xc8, 0x05, 0x1a, 0x75, 0xde, 0xcd, 0xcd, 0x09, 0xe4, 0x63, 0x42, 0x60, 0x00, 0x36, - 0xc7, 0xad, 0x22, 0xe8, 0x4b, 0xb2, 0x94, 0xce, 0xdc, 0xb0, 0x88, 0x27, 0xf4, 0x25, 0x81, 0x3d, - 0x70, 0x35, 0x9f, 0xee, 0x8c, 0xa4, 0x28, 0x91, 0x2f, 0x2e, 0xd0, 0x93, 0xf3, 0x91, 0xc0, 0x1c, - 0xf0, 0xb1, 0xc1, 0x85, 0xf7, 0xc1, 0x96, 0xc8, 0x98, 0x0c, 0x7a, 0x88, 0x77, 0x89, 0x54, 0xef, - 0x7a, 0x51, 0x5b, 0xaa, 0x8c, 0x86, 0xb5, 0xcd, 0x93, 0x8c, 0xc9, 0x6f, 0x35, 0xe3, 0xa8, 0xe5, - 0x6f, 0x8a, 0xe9, 0x29, 0x82, 0x4f, 0xc1, 0xb5, 0xbc, 0x9b, 0x53, 0xf5, 0x92, 0x56, 0xbf, 0x31, - 0x1a, 0xd6, 0xae, 0x3e, 0x9b, 0x0a, 0x4c, 0x50, 0xf2, 0xc1, 0x4d, 0xc0, 0x06, 0xc0, 0xed, 0x12, - 0x92, 0x11, 0x1e, 0x70, 0xf2, 0x23, 0xe2, 0x51, 0x90, 0x11, 0x8e, 0x49, 0x2a, 0x51, 0x4c, 0x5c, - 0xb0, 0x84, 0xc0, 0xaf, 0x1b, 0x74, 0x5f, 0x83, 0x1f, 0x4f, 0xb0, 0xd5, 0x7a, 0xf1, 0x19, 0xee, - 0x10, 0xdc, 0x0d, 0xa6, 0x4f, 0x20, 0x7d, 0x69, 0x22, 0xa2, 0x69, 0x44, 0x9e, 0x07, 0x98, 0xf5, - 0x53, 0xe9, 0x6e, 0x2c, 0xe1, 0x92, 0xeb, 0xda, 0xd0, 0xe1, 0xac, 0x9d, 0x23, 0x65, 0xe6, 0x50, - 0x59, 0x39, 0x7f, 0xdc, 0x6c, 0xfe, 0x1f, 0xe3, 0x66, 0xff, 0xe7, 0x55, 0x70, 0x63, 0xc1, 0x06, - 0xa4, 0x27, 0xf5, 0x74, 0xcd, 0xd0, 0xe3, 0xc0, 0xcc, 0x88, 0xad, 0x29, 0xf9, 0x54, 0x0d, 0x86, - 0x10, 0xec, 0x2d, 0xde, 0xcd, 0xec, 0xd6, 0xb0, 0xd7, 0x30, 0x8b, 0x74, 0x63, 0xbc, 0x48, 0x37, - 0x4e, 0xc7, 0x8b, 0xb4, 0x57, 0x54, 0x41, 0xbd, 0x7a, 0x57, 0x73, 0x7c, 0x77, 0xd1, 0xce, 0x05, - 0x09, 0x28, 0xeb, 0xd9, 0x4f, 0x84, 0xbc, 0xf8, 0x00, 0x9e, 0x2f, 0x88, 0xad, 0x31, 0xa8, 0xcd, - 0xc7, 0x6f, 0x0e, 0xb8, 0x76, 0xee, 0x46, 0xf6, 0xe1, 0xd9, 0x20, 0xa0, 0x3c, 0xb3, 0x1c, 0x9a, - 0x29, 0xfa, 0xb1, 0xef, 0xe8, 0xd9, 0x85, 0xd0, 0x7b, 0xf8, 0x66, 0x54, 0x75, 0xde, 0x8e, 0xaa, - 0xce, 0xbf, 0xa3, 0xaa, 0xf3, 0xea, 0x7d, 0x75, 0xe5, 0xed, 0xfb, 0xea, 0xca, 0xdf, 0xef, 0xab, - 0x2b, 0xdf, 0xe5, 0xf1, 0xef, 0xc4, 0x09, 0x0a, 0x45, 0xf3, 0x4e, 0x7c, 0x1b, 0x77, 0x10, 0x4d, - 0x9b, 0xcf, 0xf5, 0x7f, 0x2a, 0xda, 0x46, 0xb8, 0xae, 0xaf, 0xe2, 0xcb, 0xff, 0x02, 0x00, 0x00, - 0xff, 0xff, 0x82, 0x92, 0x8e, 0xd7, 0x66, 0x0d, 0x00, 0x00, -} - -func (m *GenesisState) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.TotalPrincipals) > 0 { - for iNdEx := len(m.TotalPrincipals) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TotalPrincipals[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - } - } - if len(m.PreviousAccumulationTimes) > 0 { - for iNdEx := len(m.PreviousAccumulationTimes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.PreviousAccumulationTimes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - } - if len(m.GovDenom) > 0 { - i -= len(m.GovDenom) - copy(dAtA[i:], m.GovDenom) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.GovDenom))) - i-- - dAtA[i] = 0x32 - } - if len(m.DebtDenom) > 0 { - i -= len(m.DebtDenom) - copy(dAtA[i:], m.DebtDenom) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.DebtDenom))) - i-- - dAtA[i] = 0x2a - } - if m.StartingCdpID != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.StartingCdpID)) - i-- - dAtA[i] = 0x20 - } - if len(m.Deposits) > 0 { - for iNdEx := len(m.Deposits) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposits[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.CDPs) > 0 { - for iNdEx := len(m.CDPs) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.CDPs[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *Params) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Params) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.LiquidationBlockInterval != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.LiquidationBlockInterval)) - i-- - dAtA[i] = 0x48 - } - if m.CircuitBreaker { - i-- - if m.CircuitBreaker { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x40 - } - { - size := m.DebtAuctionLot.Size() - i -= size - if _, err := m.DebtAuctionLot.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - { - size := m.DebtAuctionThreshold.Size() - i -= size - if _, err := m.DebtAuctionThreshold.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size := m.SurplusAuctionLot.Size() - i -= size - if _, err := m.SurplusAuctionLot.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.SurplusAuctionThreshold.Size() - i -= size - if _, err := m.SurplusAuctionThreshold.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.GlobalDebtLimit.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.DebtParam.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.CollateralParams) > 0 { - for iNdEx := len(m.CollateralParams) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.CollateralParams[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *DebtParam) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *DebtParam) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DebtParam) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.DebtFloor.Size() - i -= size - if _, err := m.DebtFloor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.ConversionFactor.Size() - i -= size - if _, err := m.ConversionFactor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.ReferenceAsset) > 0 { - i -= len(m.ReferenceAsset) - copy(dAtA[i:], m.ReferenceAsset) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.ReferenceAsset))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CollateralParam) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CollateralParam) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CollateralParam) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.ConversionFactor.Size() - i -= size - if _, err := m.ConversionFactor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x62 - { - size := m.CheckCollateralizationIndexCount.Size() - i -= size - if _, err := m.CheckCollateralizationIndexCount.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x5a - { - size := m.KeeperRewardPercentage.Size() - i -= size - if _, err := m.KeeperRewardPercentage.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x52 - if len(m.LiquidationMarketID) > 0 { - i -= len(m.LiquidationMarketID) - copy(dAtA[i:], m.LiquidationMarketID) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.LiquidationMarketID))) - i-- - dAtA[i] = 0x4a - } - if len(m.SpotMarketID) > 0 { - i -= len(m.SpotMarketID) - copy(dAtA[i:], m.SpotMarketID) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.SpotMarketID))) - i-- - dAtA[i] = 0x42 - } - { - size := m.LiquidationPenalty.Size() - i -= size - if _, err := m.LiquidationPenalty.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - { - size := m.AuctionSize.Size() - i -= size - if _, err := m.AuctionSize.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size := m.StabilityFee.Size() - i -= size - if _, err := m.StabilityFee.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.DebtLimit.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.LiquidationRatio.Size() - i -= size - if _, err := m.LiquidationRatio.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Type) > 0 { - i -= len(m.Type) - copy(dAtA[i:], m.Type) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.Type))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *GenesisAccumulationTime) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisAccumulationTime) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisAccumulationTime) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.InterestFactor.Size() - i -= size - if _, err := m.InterestFactor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - n5, err5 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.PreviousAccumulationTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.PreviousAccumulationTime):]) - if err5 != nil { - return 0, err5 - } - i -= n5 - i = encodeVarintGenesis(dAtA, i, uint64(n5)) - i-- - dAtA[i] = 0x12 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *GenesisTotalPrincipal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisTotalPrincipal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisTotalPrincipal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.TotalPrincipal.Size() - i -= size - if _, err := m.TotalPrincipal.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *GenesisState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.CDPs) > 0 { - for _, e := range m.CDPs { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.Deposits) > 0 { - for _, e := range m.Deposits { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if m.StartingCdpID != 0 { - n += 1 + sovGenesis(uint64(m.StartingCdpID)) - } - l = len(m.DebtDenom) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = len(m.GovDenom) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - if len(m.PreviousAccumulationTimes) > 0 { - for _, e := range m.PreviousAccumulationTimes { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.TotalPrincipals) > 0 { - for _, e := range m.TotalPrincipals { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.CollateralParams) > 0 { - for _, e := range m.CollateralParams { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - l = m.DebtParam.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.GlobalDebtLimit.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.SurplusAuctionThreshold.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.SurplusAuctionLot.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.DebtAuctionThreshold.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.DebtAuctionLot.Size() - n += 1 + l + sovGenesis(uint64(l)) - if m.CircuitBreaker { - n += 2 - } - if m.LiquidationBlockInterval != 0 { - n += 1 + sovGenesis(uint64(m.LiquidationBlockInterval)) - } - return n -} - -func (m *DebtParam) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = len(m.ReferenceAsset) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = m.ConversionFactor.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.DebtFloor.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *CollateralParam) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = len(m.Type) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = m.LiquidationRatio.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.DebtLimit.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.StabilityFee.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.AuctionSize.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.LiquidationPenalty.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = len(m.SpotMarketID) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = len(m.LiquidationMarketID) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = m.KeeperRewardPercentage.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.CheckCollateralizationIndexCount.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.ConversionFactor.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *GenesisAccumulationTime) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.PreviousAccumulationTime) - n += 1 + l + sovGenesis(uint64(l)) - l = m.InterestFactor.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *GenesisTotalPrincipal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = m.TotalPrincipal.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *GenesisState) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CDPs", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CDPs = append(m.CDPs, CDP{}) - if err := m.CDPs[len(m.CDPs)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposits", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Deposits = append(m.Deposits, Deposit{}) - if err := m.Deposits[len(m.Deposits)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field StartingCdpID", wireType) - } - m.StartingCdpID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.StartingCdpID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DebtDenom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DebtDenom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field GovDenom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.GovDenom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PreviousAccumulationTimes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PreviousAccumulationTimes = append(m.PreviousAccumulationTimes, GenesisAccumulationTime{}) - if err := m.PreviousAccumulationTimes[len(m.PreviousAccumulationTimes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalPrincipals", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TotalPrincipals = append(m.TotalPrincipals, GenesisTotalPrincipal{}) - if err := m.TotalPrincipals[len(m.TotalPrincipals)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Params) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Params: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralParams", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralParams = append(m.CollateralParams, CollateralParam{}) - if err := m.CollateralParams[len(m.CollateralParams)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DebtParam", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.DebtParam.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field GlobalDebtLimit", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.GlobalDebtLimit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SurplusAuctionThreshold", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.SurplusAuctionThreshold.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SurplusAuctionLot", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.SurplusAuctionLot.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DebtAuctionThreshold", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.DebtAuctionThreshold.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DebtAuctionLot", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.DebtAuctionLot.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CircuitBreaker", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CircuitBreaker = bool(v != 0) - case 9: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field LiquidationBlockInterval", wireType) - } - m.LiquidationBlockInterval = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.LiquidationBlockInterval |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DebtParam) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DebtParam: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DebtParam: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ReferenceAsset", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ReferenceAsset = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ConversionFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ConversionFactor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DebtFloor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.DebtFloor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CollateralParam) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CollateralParam: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CollateralParam: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Type = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LiquidationRatio", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.LiquidationRatio.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DebtLimit", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.DebtLimit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field StabilityFee", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.StabilityFee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AuctionSize", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.AuctionSize.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LiquidationPenalty", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.LiquidationPenalty.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SpotMarketID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SpotMarketID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LiquidationMarketID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.LiquidationMarketID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field KeeperRewardPercentage", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.KeeperRewardPercentage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 11: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CheckCollateralizationIndexCount", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.CheckCollateralizationIndexCount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 12: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ConversionFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ConversionFactor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *GenesisAccumulationTime) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisAccumulationTime: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisAccumulationTime: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PreviousAccumulationTime", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.PreviousAccumulationTime, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InterestFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.InterestFactor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *GenesisTotalPrincipal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisTotalPrincipal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisTotalPrincipal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalPrincipal", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TotalPrincipal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/cdp/types/genesis_test.go b/x/cdp/types/genesis_test.go deleted file mode 100644 index a363b995..00000000 --- a/x/cdp/types/genesis_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package types_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - "github.com/0glabs/0g-chain/x/cdp/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestGenesis_Default(t *testing.T) { - defaultGenesis := types.DefaultGenesisState() - - require.NoError(t, defaultGenesis.Validate()) - - defaultParams := types.DefaultParams() - assert.Equal(t, defaultParams, defaultGenesis.Params) -} - -func TestGenesisTotalPrincipal(t *testing.T) { - tests := []struct { - giveName string - giveCollateralType string - givePrincipal sdkmath.Int - wantIsError bool - wantError string - }{ - {"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 { - t.Run(tt.giveName, func(t *testing.T) { - tp := types.NewGenesisTotalPrincipal(tt.giveCollateralType, tt.givePrincipal) - - err := tp.Validate() - if tt.wantIsError { - assert.Error(t, err) - assert.Contains(t, err.Error(), tt.wantError) - } else { - assert.NoError(t, err) - } - }) - } -} diff --git a/x/cdp/types/hooks.go b/x/cdp/types/hooks.go deleted file mode 100644 index 44bc732c..00000000 --- a/x/cdp/types/hooks.go +++ /dev/null @@ -1,25 +0,0 @@ -package types - -import sdk "github.com/cosmos/cosmos-sdk/types" - -// MultiCDPHooks combine multiple cdp hooks, all hook functions are run in array sequence -type MultiCDPHooks []CDPHooks - -// NewMultiCDPHooks returns a new MultiCDPHooks -func NewMultiCDPHooks(hooks ...CDPHooks) MultiCDPHooks { - return hooks -} - -// BeforeCDPModified runs before a cdp is modified -func (h MultiCDPHooks) BeforeCDPModified(ctx sdk.Context, cdp CDP) { - for i := range h { - h[i].BeforeCDPModified(ctx, cdp) - } -} - -// AfterCDPCreated runs before a cdp is created -func (h MultiCDPHooks) AfterCDPCreated(ctx sdk.Context, cdp CDP) { - for i := range h { - h[i].AfterCDPCreated(ctx, cdp) - } -} diff --git a/x/cdp/types/keys.go b/x/cdp/types/keys.go deleted file mode 100644 index 67921b6a..00000000 --- a/x/cdp/types/keys.go +++ /dev/null @@ -1,171 +0,0 @@ -package types - -import ( - "bytes" - "encoding/binary" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // ModuleName The name that will be used throughout the module - ModuleName = "cdp" - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey Top level router key - RouterKey = ModuleName - - // DefaultParamspace default name for parameter store - DefaultParamspace = ModuleName - - // LiquidatorMacc module account for liquidator - LiquidatorMacc = "liquidator" -) - -var sep = []byte(":") - -// Keys for cdp store -// Items are stored with the following key: values -// - 0x00: []cdpID -// - One cdp owner can control one cdp per collateral type -// - 0x01:: CDP -// - cdps are prefix by denom prefix so we can iterate over cdps of one type -// - uses : as separator -// - 0x02::: cdpID -// - Ox03: nextCdpID -// - 0x04: debtDenom -// - 0x05::: Deposit -// - 0x06:totalPrincipal -// - 0x07:feeRate -// - 0x08:previousDistributionTime -// - 0x09:downTime -// - 0x10:totalDistributed - -// KVStore key prefixes -var ( - CdpIDKeyPrefix = []byte{0x01} - CdpKeyPrefix = []byte{0x02} - CollateralRatioIndexPrefix = []byte{0x03} - CdpIDKey = []byte{0x04} - DebtDenomKey = []byte{0x05} - GovDenomKey = []byte{0x06} - DepositKeyPrefix = []byte{0x07} - PrincipalKeyPrefix = []byte{0x08} - PricefeedStatusKeyPrefix = []byte{0x10} - PreviousAccrualTimePrefix = []byte{0x12} - InterestFactorPrefix = []byte{0x13} -) - -// GetCdpIDBytes returns the byte representation of the cdpID -func GetCdpIDBytes(cdpID uint64) (cdpIDBz []byte) { - cdpIDBz = make([]byte, 8) - binary.BigEndian.PutUint64(cdpIDBz, cdpID) - return -} - -// GetCdpIDFromBytes returns cdpID in uint64 format from a byte array -func GetCdpIDFromBytes(bz []byte) (cdpID uint64) { - return binary.BigEndian.Uint64(bz) -} - -// CdpKey key of a specific cdp in the store -func CdpKey(collateralType string, cdpID uint64) []byte { - return createKey([]byte(collateralType), sep, GetCdpIDBytes(cdpID)) -} - -// SplitCdpKey returns the component parts of a cdp key -func SplitCdpKey(key []byte) (string, uint64) { - split := bytes.Split(key, sep) - return string(split[0]), GetCdpIDFromBytes(split[1]) -} - -// DenomIterKey returns the key for iterating over cdps of a certain denom in the store -func DenomIterKey(collateralType string) []byte { - return append([]byte(collateralType), sep...) -} - -// SplitDenomIterKey returns the component part of a key for iterating over cdps by denom -func SplitDenomIterKey(key []byte) string { - split := bytes.Split(key, sep) - return string(split[0]) -} - -// DepositKey key of a specific deposit in the store -func DepositKey(cdpID uint64, depositor sdk.AccAddress) []byte { - return createKey(GetCdpIDBytes(cdpID), sep, depositor) -} - -// SplitDepositKey returns the component parts of a deposit key -func SplitDepositKey(key []byte) (uint64, sdk.AccAddress) { - cdpID := GetCdpIDFromBytes(key[0:8]) - addr := key[9:] - return cdpID, addr -} - -// DepositIterKey returns the prefix key for iterating over deposits to a cdp -func DepositIterKey(cdpID uint64) []byte { - return GetCdpIDBytes(cdpID) -} - -// SplitDepositIterKey returns the component parts of a key for iterating over deposits on a cdp -func SplitDepositIterKey(key []byte) (cdpID uint64) { - return GetCdpIDFromBytes(key) -} - -// CollateralRatioBytes returns the liquidation ratio as sortable bytes -func CollateralRatioBytes(ratio sdk.Dec) []byte { - ok := ValidSortableDec(ratio) - if !ok { - // set to max sortable if input is too large. - ratio = sdk.OneDec().Quo(sdk.SmallestDec()) - } - return SortableDecBytes(ratio) -} - -// CollateralRatioKey returns the key for querying a cdp by its liquidation ratio -func CollateralRatioKey(collateralType string, cdpID uint64, ratio sdk.Dec) []byte { - ratioBytes := CollateralRatioBytes(ratio) - idBytes := GetCdpIDBytes(cdpID) - - return createKey([]byte(collateralType), sep, ratioBytes, sep, idBytes) -} - -// SplitCollateralRatioKey split the collateral ratio key and return the denom, cdp id, and collateral:debt ratio -func SplitCollateralRatioKey(key []byte) (string, uint64, sdk.Dec) { - cdpID := GetCdpIDFromBytes(key[len(key)-8:]) - split := bytes.Split(key[:len(key)-8], sep) - collateralType := string(split[0]) - - ratio, err := ParseDecBytes(split[1]) - if err != nil { - panic(err) - } - return collateralType, cdpID, ratio -} - -// CollateralRatioIterKey returns the key for iterating over cdps by denom and liquidation ratio -func CollateralRatioIterKey(collateralType string, ratio sdk.Dec) []byte { - ratioBytes := CollateralRatioBytes(ratio) - return createKey([]byte(collateralType), sep, ratioBytes) -} - -// SplitCollateralRatioIterKey split the collateral ratio key and return the denom, cdp id, and collateral:debt ratio -func SplitCollateralRatioIterKey(key []byte) (string, sdk.Dec) { - split := bytes.Split(key, sep) - collateralType := string(split[0]) - - ratio, err := ParseDecBytes(split[1]) - if err != nil { - panic(err) - } - return collateralType, ratio -} - -func createKey(bytes ...[]byte) (r []byte) { - for _, b := range bytes { - r = append(r, b...) - } - return -} diff --git a/x/cdp/types/keys_test.go b/x/cdp/types/keys_test.go deleted file mode 100644 index adb3b839..00000000 --- a/x/cdp/types/keys_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/cometbft/cometbft/crypto/ed25519" -) - -var addr = sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) - -func TestCdpKey(t *testing.T) { - key := CdpKey("kava-a", 2) - collateralType, id := SplitCdpKey(key) - require.Equal(t, int(id), 2) - require.Equal(t, "kava-a", collateralType) -} - -func TestDenomIterKey(t *testing.T) { - denomKey := DenomIterKey("kava-a") - collateralType := SplitDenomIterKey(denomKey) - require.Equal(t, "kava-a", collateralType) -} - -func TestDepositKey(t *testing.T) { - depositKey := DepositKey(2, addr) - id, a := SplitDepositKey(depositKey) - require.Equal(t, 2, int(id)) - require.Equal(t, a, addr) -} - -func TestDepositIterKey(t *testing.T) { - depositIterKey := DepositIterKey(2) - id := SplitDepositIterKey(depositIterKey) - require.Equal(t, 2, int(id)) -} - -func TestDepositIterKey_Invalid(t *testing.T) { - require.Panics(t, func() { SplitDepositIterKey([]byte{0x03}) }) -} - -func TestCollateralRatioKey(t *testing.T) { - collateralKey := CollateralRatioKey("kava-a", 2, sdk.MustNewDecFromStr("1.50")) - collateralType, id, ratio := SplitCollateralRatioKey(collateralKey) - require.Equal(t, "kava-a", collateralType) - require.Equal(t, 2, int(id)) - require.Equal(t, ratio, sdk.MustNewDecFromStr("1.50")) -} - -func TestCollateralRatioKey_BigRatio(t *testing.T) { - bigRatio := sdk.OneDec().Quo(sdk.SmallestDec()).Mul(sdk.OneDec().Add(sdk.OneDec())) - collateralKey := CollateralRatioKey("kava-a", 2, bigRatio) - collateralType, id, ratio := SplitCollateralRatioKey(collateralKey) - require.Equal(t, "kava-a", collateralType) - require.Equal(t, 2, int(id)) - require.Equal(t, ratio, MaxSortableDec) -} - -func TestCollateralRatioKey_Invalid(t *testing.T) { - require.Panics(t, func() { SplitCollateralRatioKey(badRatioKey()) }) -} - -func TestCollateralRatioIterKey(t *testing.T) { - collateralIterKey := CollateralRatioIterKey("kava-a", sdk.MustNewDecFromStr("1.50")) - collateralType, ratio := SplitCollateralRatioIterKey(collateralIterKey) - require.Equal(t, "kava-a", collateralType) - require.Equal(t, ratio, sdk.MustNewDecFromStr("1.50")) -} - -func TestCollateralRatioIterKey_Invalid(t *testing.T) { - require.Panics(t, func() { SplitCollateralRatioIterKey(badRatioIterKey()) }) -} - -func badRatioKey() []byte { - r := append(append(append(append([]byte{0x01}, sep...), []byte("nonsense")...), sep...), []byte{0xff}...) - return r -} - -func badRatioIterKey() []byte { - r := append(append([]byte{0x01}, sep...), []byte("nonsense")...) - return r -} diff --git a/x/cdp/types/msg.go b/x/cdp/types/msg.go deleted file mode 100644 index 32f6a308..00000000 --- a/x/cdp/types/msg.go +++ /dev/null @@ -1,312 +0,0 @@ -package types - -import ( - "errors" - "fmt" - "strings" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// ensure Msg interface compliance at compile time -var ( - _ sdk.Msg = &MsgCreateCDP{} - _ sdk.Msg = &MsgDeposit{} - _ sdk.Msg = &MsgWithdraw{} - _ sdk.Msg = &MsgDrawDebt{} - _ sdk.Msg = &MsgRepayDebt{} - _ sdk.Msg = &MsgLiquidate{} -) - -// NewMsgCreateCDP returns a new MsgPlaceBid. -func NewMsgCreateCDP(sender sdk.AccAddress, collateral sdk.Coin, principal sdk.Coin, collateralType string) MsgCreateCDP { - return MsgCreateCDP{ - Sender: sender.String(), - Collateral: collateral, - Principal: principal, - CollateralType: collateralType, - } -} - -// Route return the message type used for routing the message. -func (msg MsgCreateCDP) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgCreateCDP) Type() string { return "create_cdp" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgCreateCDP) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if msg.Collateral.IsZero() || !msg.Collateral.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "collateral amount %s", msg.Collateral) - } - if msg.Principal.IsZero() || !msg.Principal.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "principal amount %s", msg.Principal) - } - if strings.TrimSpace(msg.CollateralType) == "" { - return fmt.Errorf("collateral type cannot be empty") - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgCreateCDP) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgCreateCDP) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgDeposit returns a new MsgDeposit -func NewMsgDeposit(owner sdk.AccAddress, depositor sdk.AccAddress, collateral sdk.Coin, collateralType string) MsgDeposit { - return MsgDeposit{ - Owner: owner.String(), - Depositor: depositor.String(), - Collateral: collateral, - CollateralType: collateralType, - } -} - -// Route return the message type used for routing the message. -func (msg MsgDeposit) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgDeposit) Type() string { return "deposit_cdp" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgDeposit) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Owner) - if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid owner address %s", err) - } - _, err = sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid depositor address %s", err) - } - - if !msg.Collateral.IsValid() || msg.Collateral.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "collateral amount %s", msg.Collateral) - } - if strings.TrimSpace(msg.CollateralType) == "" { - return fmt.Errorf("collateral type cannot be empty") - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgDeposit) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgDeposit) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - panic(err) - } - return []sdk.AccAddress{depositor} -} - -// NewMsgWithdraw returns a new MsgDeposit -func NewMsgWithdraw(owner sdk.AccAddress, depositor sdk.AccAddress, collateral sdk.Coin, collateralType string) MsgWithdraw { - return MsgWithdraw{ - Owner: owner.String(), - Depositor: depositor.String(), - Collateral: collateral, - CollateralType: collateralType, - } -} - -// Route return the message type used for routing the message. -func (msg MsgWithdraw) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgWithdraw) Type() string { return "withdraw_cdp" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgWithdraw) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Owner) - if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid owner address %s", err) - } - _, err = sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid depositor address %s", err) - } - - if !msg.Collateral.IsValid() || msg.Collateral.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "collateral amount %s", msg.Collateral) - } - if strings.TrimSpace(msg.CollateralType) == "" { - return fmt.Errorf("collateral type cannot be empty") - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgWithdraw) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgWithdraw) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - panic(err) - } - return []sdk.AccAddress{depositor} -} - -// NewMsgDrawDebt returns a new MsgDrawDebt -func NewMsgDrawDebt(sender sdk.AccAddress, collateralType string, principal sdk.Coin) MsgDrawDebt { - return MsgDrawDebt{ - Sender: sender.String(), - CollateralType: collateralType, - Principal: principal, - } -} - -// Route return the message type used for routing the message. -func (msg MsgDrawDebt) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgDrawDebt) Type() string { return "draw_cdp" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgDrawDebt) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - 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 errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "principal amount %s", msg.Principal) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgDrawDebt) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgDrawDebt) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgRepayDebt returns a new MsgRepayDebt -func NewMsgRepayDebt(sender sdk.AccAddress, collateralType string, payment sdk.Coin) MsgRepayDebt { - return MsgRepayDebt{ - Sender: sender.String(), - CollateralType: collateralType, - Payment: payment, - } -} - -// Route return the message type used for routing the message. -func (msg MsgRepayDebt) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgRepayDebt) Type() string { return "repay_cdp" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgRepayDebt) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - 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 errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "payment amount %s", msg.Payment) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgRepayDebt) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgRepayDebt) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgLiquidate returns a new MsgLiquidate -func NewMsgLiquidate(keeper, borrower sdk.AccAddress, ctype string) MsgLiquidate { - return MsgLiquidate{ - Keeper: keeper.String(), - Borrower: borrower.String(), - CollateralType: ctype, - } -} - -// Route return the message type used for routing the message. -func (msg MsgLiquidate) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgLiquidate) Type() string { return "liquidate" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgLiquidate) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Keeper) - if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid keeper address %s", err) - } - _, err = sdk.AccAddressFromBech32(msg.Borrower) - if err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid borrower address %s", err) - } - - if strings.TrimSpace(msg.CollateralType) == "" { - return errorsmod.Wrap(ErrInvalidCollateral, "collateral type cannot be empty") - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgLiquidate) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgLiquidate) GetSigners() []sdk.AccAddress { - keeper, err := sdk.AccAddressFromBech32(msg.Keeper) - if err != nil { - panic(err) - } - return []sdk.AccAddress{keeper} -} diff --git a/x/cdp/types/msg_test.go b/x/cdp/types/msg_test.go deleted file mode 100644 index 41ec147a..00000000 --- a/x/cdp/types/msg_test.go +++ /dev/null @@ -1,169 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var ( - coinsSingle = sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000) - coinsZero = sdk.NewCoin(sdk.DefaultBondDenom, sdk.ZeroInt()) - addrs = []sdk.AccAddress{ - sdk.AccAddress("test1"), - sdk.AccAddress("test2"), - } -) - -func TestMsgCreateCDP(t *testing.T) { - tests := []struct { - description string - sender sdk.AccAddress - collateral sdk.Coin - principal sdk.Coin - collateralType string - expectPass bool - }{ - {"create cdp", addrs[0], coinsSingle, coinsSingle, "type-a", true}, - {"create cdp no collateral", addrs[0], coinsZero, coinsSingle, "type-a", false}, - {"create cdp no debt", addrs[0], coinsSingle, coinsZero, "type-a", false}, - {"create cdp empty owner", sdk.AccAddress{}, coinsSingle, coinsSingle, "type-a", false}, - {"create cdp empty type", addrs[0], coinsSingle, coinsSingle, "", false}, - } - - for _, tc := range tests { - msg := NewMsgCreateCDP( - tc.sender, - tc.collateral, - tc.principal, - tc.collateralType, - ) - if tc.expectPass { - require.NoError(t, msg.ValidateBasic(), "test: %v", tc.description) - } else { - require.Error(t, msg.ValidateBasic(), "test: %v", tc.description) - } - } -} - -func TestMsgDeposit(t *testing.T) { - tests := []struct { - description string - sender sdk.AccAddress - depositor sdk.AccAddress - collateral sdk.Coin - collateralType string - expectPass bool - }{ - {"deposit", addrs[0], addrs[1], coinsSingle, "type-a", true}, - {"deposit same owner", addrs[0], addrs[0], coinsSingle, "type-a", true}, - {"deposit no collateral", addrs[0], addrs[1], coinsZero, "type-a", false}, - {"deposit empty owner", sdk.AccAddress{}, addrs[1], coinsSingle, "type-a", false}, - {"deposit empty depositor", addrs[0], sdk.AccAddress{}, coinsSingle, "type-a", false}, - {"deposit empty type", addrs[0], addrs[0], coinsSingle, "", false}, - } - - for _, tc := range tests { - msg := NewMsgDeposit( - tc.sender, - tc.depositor, - tc.collateral, - tc.collateralType, - ) - if tc.expectPass { - require.NoError(t, msg.ValidateBasic(), "test: %v", tc.description) - } else { - require.Error(t, msg.ValidateBasic(), "test: %v", tc.description) - } - } -} - -func TestMsgWithdraw(t *testing.T) { - tests := []struct { - description string - sender sdk.AccAddress - depositor sdk.AccAddress - collateral sdk.Coin - collateralType string - expectPass bool - }{ - {"withdraw", addrs[0], addrs[1], coinsSingle, "type-a", true}, - {"withdraw", addrs[0], addrs[0], coinsSingle, "type-a", true}, - {"withdraw no collateral", addrs[0], addrs[1], coinsZero, "type-a", false}, - {"withdraw empty owner", sdk.AccAddress{}, addrs[1], coinsSingle, "type-a", false}, - {"withdraw empty depositor", addrs[0], sdk.AccAddress{}, coinsSingle, "type-a", false}, - {"withdraw empty type", addrs[0], addrs[0], coinsSingle, "", false}, - } - - for _, tc := range tests { - msg := NewMsgWithdraw( - tc.sender, - tc.depositor, - tc.collateral, - tc.collateralType, - ) - if tc.expectPass { - require.NoError(t, msg.ValidateBasic(), "test: %v", tc.description) - } else { - require.Error(t, msg.ValidateBasic(), "test: %v", tc.description) - } - } -} - -func TestMsgDrawDebt(t *testing.T) { - tests := []struct { - description string - sender sdk.AccAddress - collateralType string - principal sdk.Coin - expectPass bool - }{ - {"draw debt", addrs[0], sdk.DefaultBondDenom, coinsSingle, true}, - {"draw debt no debt", addrs[0], sdk.DefaultBondDenom, coinsZero, false}, - {"draw debt empty owner", sdk.AccAddress{}, sdk.DefaultBondDenom, coinsSingle, false}, - {"draw debt empty denom", sdk.AccAddress{}, "", coinsSingle, false}, - } - - for _, tc := range tests { - msg := NewMsgDrawDebt( - tc.sender, - tc.collateralType, - tc.principal, - ) - if tc.expectPass { - require.NoError(t, msg.ValidateBasic(), "test: %v", tc.description) - } else { - require.Error(t, msg.ValidateBasic(), "test: %v", tc.description) - } - } -} - -func TestMsgRepayDebt(t *testing.T) { - tests := []struct { - description string - sender sdk.AccAddress - denom string - payment sdk.Coin - expectPass bool - }{ - {"repay debt", addrs[0], sdk.DefaultBondDenom, coinsSingle, true}, - {"repay debt no payment", addrs[0], sdk.DefaultBondDenom, coinsZero, false}, - {"repay debt empty owner", sdk.AccAddress{}, sdk.DefaultBondDenom, coinsSingle, false}, - {"repay debt empty denom", sdk.AccAddress{}, "", coinsSingle, false}, - } - - for _, tc := range tests { - msg := NewMsgRepayDebt( - tc.sender, - tc.denom, - tc.payment, - ) - if tc.expectPass { - require.NoError(t, msg.ValidateBasic(), "test: %v", tc.description) - } else { - require.Error(t, msg.ValidateBasic(), "test: %v", tc.description) - } - } -} diff --git a/x/cdp/types/params.go b/x/cdp/types/params.go deleted file mode 100644 index ca3356fb..00000000 --- a/x/cdp/types/params.go +++ /dev/null @@ -1,370 +0,0 @@ -package types - -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" -) - -// Parameter keys -var ( - KeyGlobalDebtLimit = []byte("GlobalDebtLimit") - KeyCollateralParams = []byte("CollateralParams") - KeyDebtParam = []byte("DebtParam") - KeyCircuitBreaker = []byte("CircuitBreaker") - KeyDebtThreshold = []byte("DebtThreshold") - KeyDebtLot = []byte("DebtLot") - KeySurplusThreshold = []byte("SurplusThreshold") - KeySurplusLot = []byte("SurplusLot") - KeyBeginBlockerExecutionBlockInterval = []byte("BeginBlockerExecutionBlockInterval") - DefaultGlobalDebt = sdk.NewCoin(DefaultStableDenom, sdk.ZeroInt()) - DefaultCircuitBreaker = false - DefaultCollateralParams = CollateralParams{} - DefaultDebtParam = DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - } - DefaultCdpStartingID = uint64(1) - DefaultDebtDenom = "debt" - DefaultGovDenom = "ukava" - DefaultStableDenom = "usdx" - DefaultSurplusThreshold = sdkmath.NewInt(500000000000) - DefaultDebtThreshold = sdkmath.NewInt(100000000000) - DefaultSurplusLot = sdkmath.NewInt(10000000000) - DefaultDebtLot = sdkmath.NewInt(10000000000) - stabilityFeeMax = sdk.MustNewDecFromStr("1.000000051034942716") // 500% APR - // Run every block - DefaultBeginBlockerExecutionBlockInterval = int64(1) -) - -// NewParams returns a new params object -func NewParams( - debtLimit sdk.Coin, collateralParams CollateralParams, debtParam DebtParam, surplusThreshold, - surplusLot, debtThreshold, debtLot sdkmath.Int, breaker bool, beginBlockerExecutionBlockInterval int64, -) Params { - return Params{ - GlobalDebtLimit: debtLimit, - CollateralParams: collateralParams, - DebtParam: debtParam, - SurplusAuctionThreshold: surplusThreshold, - SurplusAuctionLot: surplusLot, - DebtAuctionThreshold: debtThreshold, - DebtAuctionLot: debtLot, - CircuitBreaker: breaker, - LiquidationBlockInterval: beginBlockerExecutionBlockInterval, - } -} - -// DefaultParams returns default params for cdp module -func DefaultParams() Params { - return NewParams( - DefaultGlobalDebt, DefaultCollateralParams, DefaultDebtParam, DefaultSurplusThreshold, - DefaultSurplusLot, DefaultDebtThreshold, DefaultDebtLot, - DefaultCircuitBreaker, DefaultBeginBlockerExecutionBlockInterval, - ) -} - -// NewCollateralParam returns a new CollateralParam -func NewCollateralParam( - 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, - Type: ctype, - LiquidationRatio: liqRatio, - DebtLimit: debtLimit, - StabilityFee: stabilityFee, - AuctionSize: auctionSize, - LiquidationPenalty: liqPenalty, - SpotMarketID: spotMarketID, - LiquidationMarketID: liquidationMarketID, - KeeperRewardPercentage: keeperReward, - CheckCollateralizationIndexCount: checkIndexCount, - ConversionFactor: conversionFactor, - } -} - -// CollateralParams array of CollateralParam -type CollateralParams []CollateralParam - -// NewDebtParam returns a new DebtParam -func NewDebtParam(denom, refAsset string, conversionFactor, debtFloor sdkmath.Int) DebtParam { - return DebtParam{ - Denom: denom, - ReferenceAsset: refAsset, - ConversionFactor: conversionFactor, - DebtFloor: debtFloor, - } -} - -// DebtParams array of DebtParam -type DebtParams []DebtParam - -// ParamKeyTable Key declaration for parameters -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements the ParamSet interface and returns all the key/value pairs -// pairs of auth module's parameters. -// nolint -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyGlobalDebtLimit, &p.GlobalDebtLimit, validateGlobalDebtLimitParam), - paramtypes.NewParamSetPair(KeyCollateralParams, &p.CollateralParams, validateCollateralParams), - paramtypes.NewParamSetPair(KeyDebtParam, &p.DebtParam, validateDebtParam), - paramtypes.NewParamSetPair(KeyCircuitBreaker, &p.CircuitBreaker, validateCircuitBreakerParam), - paramtypes.NewParamSetPair(KeySurplusThreshold, &p.SurplusAuctionThreshold, validateSurplusAuctionThresholdParam), - paramtypes.NewParamSetPair(KeySurplusLot, &p.SurplusAuctionLot, validateSurplusAuctionLotParam), - paramtypes.NewParamSetPair(KeyDebtThreshold, &p.DebtAuctionThreshold, validateDebtAuctionThresholdParam), - paramtypes.NewParamSetPair(KeyDebtLot, &p.DebtAuctionLot, validateDebtAuctionLotParam), - paramtypes.NewParamSetPair(KeyBeginBlockerExecutionBlockInterval, &p.LiquidationBlockInterval, validateBeginBlockerExecutionBlockIntervalParam), - } -} - -// Validate checks that the parameters have valid values. -func (p Params) Validate() error { - if err := validateGlobalDebtLimitParam(p.GlobalDebtLimit); err != nil { - return err - } - - if err := validateCollateralParams(p.CollateralParams); err != nil { - return err - } - - if err := validateDebtParam(p.DebtParam); err != nil { - return err - } - - if err := validateCircuitBreakerParam(p.CircuitBreaker); err != nil { - return err - } - - if err := validateBeginBlockerExecutionBlockIntervalParam(p.LiquidationBlockInterval); err != nil { - return err - } - - if err := validateSurplusAuctionThresholdParam(p.SurplusAuctionThreshold); err != nil { - return err - } - - if err := validateSurplusAuctionLotParam(p.SurplusAuctionLot); err != nil { - return err - } - - if err := validateDebtAuctionThresholdParam(p.DebtAuctionThreshold); err != nil { - return err - } - - if err := validateDebtAuctionLotParam(p.DebtAuctionLot); err != nil { - return err - } - - if len(p.CollateralParams) == 0 { // default value OK - return nil - } - - if (DebtParam{}) != p.DebtParam { - if p.DebtParam.Denom != p.GlobalDebtLimit.Denom { - return fmt.Errorf("debt denom %s does not match global debt denom %s", - p.DebtParam.Denom, p.GlobalDebtLimit.Denom) - } - } - - // validate collateral params - collateralTypeDupMap := make(map[string]bool) - collateralParamsDebtLimit := sdk.ZeroInt() - - for _, cp := range p.CollateralParams { - // Collateral type eg busd-a should be unique, but denom can be same eg busd - _, exists := collateralTypeDupMap[cp.Type] - if exists { - return fmt.Errorf("duplicate collateral type %s", cp.Denom) - } - - collateralTypeDupMap[cp.Type] = true - - if cp.DebtLimit.Denom != p.GlobalDebtLimit.Denom { - return fmt.Errorf("collateral debt limit denom %s does not match global debt limit denom %s", - cp.DebtLimit.Denom, p.GlobalDebtLimit.Denom) - } - - collateralParamsDebtLimit = collateralParamsDebtLimit.Add(cp.DebtLimit.Amount) - - if cp.DebtLimit.Amount.GT(p.GlobalDebtLimit.Amount) { - return fmt.Errorf("collateral debt limit %s exceeds global debt limit: %s", cp.DebtLimit, p.GlobalDebtLimit) - } - } - - if collateralParamsDebtLimit.GT(p.GlobalDebtLimit.Amount) { - return fmt.Errorf("sum of collateral debt limits %s exceeds global debt limit %s", - collateralParamsDebtLimit, p.GlobalDebtLimit) - } - - return nil -} - -func validateGlobalDebtLimitParam(i interface{}) error { - globalDebtLimit, ok := i.(sdk.Coin) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if !globalDebtLimit.IsValid() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "global debt limit %s", globalDebtLimit.String()) - } - - return nil -} - -func validateCollateralParams(i interface{}) error { - collateralParams, ok := i.(CollateralParams) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - typeDupMap := make(map[string]bool) - for _, cp := range collateralParams { - if err := sdk.ValidateDenom(cp.Denom); err != nil { - return fmt.Errorf("collateral denom invalid %s", cp.Denom) - } - - if strings.TrimSpace(cp.SpotMarketID) == "" { - return fmt.Errorf("spot market id cannot be blank %v", cp) - } - - if strings.TrimSpace(cp.Type) == "" { - return fmt.Errorf("collateral type cannot be blank %v", cp) - } - - if strings.TrimSpace(cp.LiquidationMarketID) == "" { - return fmt.Errorf("liquidation market id cannot be blank %v", cp) - } - - _, found := typeDupMap[cp.Type] - if found { - return fmt.Errorf("duplicate cdp collateral type: %s", cp.Type) - } - typeDupMap[cp.Type] = true - - if !cp.DebtLimit.IsValid() { - return fmt.Errorf("debt limit for all collaterals should be positive, is %s for %s", cp.DebtLimit, cp.Denom) - } - - if cp.LiquidationRatio.IsNil() || !cp.LiquidationRatio.IsPositive() { - return fmt.Errorf("liquidation ratio must be > 0") - } - - if cp.LiquidationPenalty.LT(sdk.ZeroDec()) || cp.LiquidationPenalty.GT(sdk.OneDec()) { - return fmt.Errorf("liquidation penalty should be between 0 and 1, is %s for %s", cp.LiquidationPenalty, cp.Denom) - } - if !cp.AuctionSize.IsPositive() { - return fmt.Errorf("auction size should be positive, is %s for %s", cp.AuctionSize, cp.Denom) - } - if cp.StabilityFee.LT(sdk.OneDec()) || cp.StabilityFee.GT(stabilityFeeMax) { - return fmt.Errorf("stability fee must be ≥ 1.0, ≤ %s, is %s for %s", stabilityFeeMax, cp.StabilityFee, cp.Denom) - } - if cp.KeeperRewardPercentage.IsNegative() || cp.KeeperRewardPercentage.GT(sdk.OneDec()) { - return fmt.Errorf("keeper reward percentage should be between 0 and 1, is %s for %s", cp.KeeperRewardPercentage, cp.Denom) - } - if cp.CheckCollateralizationIndexCount.IsNegative() { - return fmt.Errorf("keeper reward percentage should be positive, is %s for %s", cp.CheckCollateralizationIndexCount, cp.Denom) - } - } - - return nil -} - -func validateDebtParam(i interface{}) error { - debtParam, ok := i.(DebtParam) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - if err := sdk.ValidateDenom(debtParam.Denom); err != nil { - return fmt.Errorf("debt denom invalid %s", debtParam.Denom) - } - - return nil -} - -func validateCircuitBreakerParam(i interface{}) error { - _, ok := i.(bool) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return nil -} - -func validateSurplusAuctionThresholdParam(i interface{}) error { - sat, ok := i.(sdkmath.Int) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if !sat.IsPositive() { - return fmt.Errorf("surplus auction threshold should be positive: %s", sat) - } - - return nil -} - -func validateSurplusAuctionLotParam(i interface{}) error { - sal, ok := i.(sdkmath.Int) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if !sal.IsPositive() { - return fmt.Errorf("surplus auction lot should be positive: %s", sal) - } - - return nil -} - -func validateDebtAuctionThresholdParam(i interface{}) error { - dat, ok := i.(sdkmath.Int) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if !dat.IsPositive() { - return fmt.Errorf("debt auction threshold should be positive: %s", dat) - } - - return nil -} - -func validateDebtAuctionLotParam(i interface{}) error { - dal, ok := i.(sdkmath.Int) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if !dal.IsPositive() { - return fmt.Errorf("debt auction lot should be positive: %s", dal) - } - - return nil -} - -func validateBeginBlockerExecutionBlockIntervalParam(i interface{}) error { - bbebi, ok := i.(int64) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if bbebi <= 0 { - return fmt.Errorf("begin blocker execution block interval param should be positive: %d", bbebi) - } - - return nil -} diff --git a/x/cdp/types/params_test.go b/x/cdp/types/params_test.go deleted file mode 100644 index d82cfc32..00000000 --- a/x/cdp/types/params_test.go +++ /dev/null @@ -1,876 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/cdp/types" -) - -type ParamsTestSuite struct { - suite.Suite -} - -func (suite *ParamsTestSuite) SetupTest() { -} - -func (suite *ParamsTestSuite) TestParamValidation() { - type args struct { - globalDebtLimit sdk.Coin - collateralParams types.CollateralParams - debtParam types.DebtParam - surplusThreshold sdkmath.Int - surplusLot sdkmath.Int - debtThreshold sdkmath.Int - debtLot sdkmath.Int - breaker bool - beginBlockerExecutionBlockInterval int64 - } - type errArgs struct { - expectPass bool - contains string - } - - testCases := []struct { - name string - args args - errArgs errArgs - }{ - { - name: "default", - args: args{ - globalDebtLimit: types.DefaultGlobalDebt, - collateralParams: types.DefaultCollateralParams, - debtParam: types.DefaultDebtParam, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: true, - contains: "", - }, - }, - { - name: "valid single-collateral", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 4000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: true, - contains: "", - }, - }, - { - name: "invalid single-collateral mismatched debt denoms", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 4000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "susd", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "does not match global debt denom", - }, - }, - { - name: "invalid single-collateral over debt limit", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "exceeds global debt limit", - }, - }, - { - name: "valid multi-collateral", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 4000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - { - Denom: "xrp", - Type: "xrp-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "xrp:usd", - LiquidationMarketID: "xrp:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(6), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: true, - contains: "", - }, - }, - { - name: "invalid multi-collateral over debt limit", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - { - Denom: "xrp", - Type: "xrp-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "xrp:usd", - LiquidationMarketID: "xrp:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(6), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "sum of collateral debt limits", - }, - }, - { - name: "invalid multi-collateral multiple debt denoms", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 4000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - { - Denom: "xrp", - Type: "xrp-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("susd", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "xrp:usd", - LiquidationMarketID: "xrp:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(6), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "does not match global debt limit denom", - }, - }, - { - name: "invalid collateral params empty denom", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "collateral denom invalid", - }, - }, - { - name: "invalid collateral params empty market id", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "", - LiquidationMarketID: "", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "market id cannot be blank", - }, - }, - { - name: "invalid collateral params duplicate denom + type", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "duplicate cdp collateral type", - }, - }, - { - name: "valid collateral params duplicate denom + different type", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - { - Denom: "bnb", - Type: "bnb-b", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: true, - contains: "", - }, - }, - { - name: "invalid collateral params nil debt limit", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.Coin{}, - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "debt limit for all collaterals should be positive", - }, - }, - { - name: "invalid collateral params liquidation ratio out of range", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("1.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "liquidation penalty should be between 0 and 1", - }, - }, - { - name: "invalid collateral params auction size zero", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdk.ZeroInt(), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "auction size should be positive", - }, - }, - { - name: "invalid collateral params stability fee out of range", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.1"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "stability fee must be ≥ 1.0", - }, - }, - { - name: "invalid collateral params zero liquidation ratio", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("0.0"), - DebtLimit: sdk.NewInt64Coin("usdx", 1_000_000_000_000), - StabilityFee: sdk.MustNewDecFromStr("1.1"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50_000_000_000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DefaultDebtParam, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "liquidation ratio must be > 0", - }, - }, - { - name: "invalid debt param empty denom", - args: args{ - globalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - collateralParams: types.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - ConversionFactor: sdkmath.NewInt(8), - CheckCollateralizationIndexCount: sdkmath.NewInt(10), - }, - }, - debtParam: types.DebtParam{ - Denom: "", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(10000000), - }, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "debt denom invalid", - }, - }, - { - name: "nil debt limit", - args: args{ - globalDebtLimit: sdk.Coin{}, - collateralParams: types.DefaultCollateralParams, - debtParam: types.DefaultDebtParam, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "global debt limit : invalid coins", - }, - }, - { - name: "zero surplus auction threshold", - args: args{ - globalDebtLimit: types.DefaultGlobalDebt, - collateralParams: types.DefaultCollateralParams, - debtParam: types.DefaultDebtParam, - surplusThreshold: sdk.ZeroInt(), - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "surplus auction threshold should be positive", - }, - }, - { - name: "zero debt auction threshold", - args: args{ - globalDebtLimit: types.DefaultGlobalDebt, - collateralParams: types.DefaultCollateralParams, - debtParam: types.DefaultDebtParam, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: sdk.ZeroInt(), - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "debt auction threshold should be positive", - }, - }, - { - name: "zero surplus auction lot", - args: args{ - globalDebtLimit: types.DefaultGlobalDebt, - collateralParams: types.DefaultCollateralParams, - debtParam: types.DefaultDebtParam, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: sdk.ZeroInt(), - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "surplus auction lot should be positive", - }, - }, - { - name: "zero debt auction lot", - args: args{ - globalDebtLimit: types.DefaultGlobalDebt, - collateralParams: types.DefaultCollateralParams, - debtParam: types.DefaultDebtParam, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: sdk.ZeroInt(), - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: types.DefaultBeginBlockerExecutionBlockInterval, - }, - errArgs: errArgs{ - expectPass: false, - contains: "debt auction lot should be positive", - }, - }, - { - name: "zero begin blocker execution interval", - args: args{ - globalDebtLimit: types.DefaultGlobalDebt, - collateralParams: types.DefaultCollateralParams, - debtParam: types.DefaultDebtParam, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: 0, - }, - errArgs: errArgs{ - expectPass: false, - contains: "begin blocker execution block interval param should be positive", - }, - }, - { - name: "negative begin blocker execution interval", - args: args{ - globalDebtLimit: types.DefaultGlobalDebt, - collateralParams: types.DefaultCollateralParams, - debtParam: types.DefaultDebtParam, - surplusThreshold: types.DefaultSurplusThreshold, - surplusLot: types.DefaultSurplusLot, - debtThreshold: types.DefaultDebtThreshold, - debtLot: types.DefaultDebtLot, - breaker: types.DefaultCircuitBreaker, - beginBlockerExecutionBlockInterval: -1, - }, - errArgs: errArgs{ - expectPass: false, - contains: "begin blocker execution block interval param should be positive", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - params := types.NewParams(tc.args.globalDebtLimit, tc.args.collateralParams, tc.args.debtParam, tc.args.surplusThreshold, tc.args.surplusLot, tc.args.debtThreshold, tc.args.debtLot, tc.args.breaker, tc.args.beginBlockerExecutionBlockInterval) - err := params.Validate() - if tc.errArgs.expectPass { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - suite.Require().Contains(err.Error(), tc.errArgs.contains) - } - }) - } -} - -func TestParamsTestSuite(t *testing.T) { - suite.Run(t, new(ParamsTestSuite)) -} diff --git a/x/cdp/types/querier.go b/x/cdp/types/querier.go deleted file mode 100644 index f3e6a69b..00000000 --- a/x/cdp/types/querier.go +++ /dev/null @@ -1,27 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// QueryCdpsParams is the params for a filtered CDP query -type QueryCdpsParams struct { - Page int `json:"page" yaml:"page"` - Limit int `json:"limit" yaml:"limit"` - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - Owner sdk.AccAddress `json:"owner" yaml:"owner"` - ID uint64 `json:"id" yaml:"id"` - Ratio sdk.Dec `json:"ratio" yaml:"ratio"` -} - -// NewQueryCdpsParams creates a new QueryCdpsParams -func NewQueryCdpsParams(page, limit int, collateralType string, owner sdk.AccAddress, id uint64, ratio sdk.Dec) QueryCdpsParams { - return QueryCdpsParams{ - Page: page, - Limit: limit, - CollateralType: collateralType, - Owner: owner, - ID: id, - Ratio: ratio, - } -} diff --git a/x/cdp/types/query.pb.go b/x/cdp/types/query.pb.go deleted file mode 100644 index 13f3928e..00000000 --- a/x/cdp/types/query.pb.go +++ /dev/null @@ -1,3857 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/cdp/v1beta1/query.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - types1 "github.com/cosmos/cosmos-sdk/types" - query "github.com/cosmos/cosmos-sdk/types/query" - types "github.com/cosmos/cosmos-sdk/x/auth/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// QueryParamsRequest defines the request type for the Query/Params RPC method. -type QueryParamsRequest struct { -} - -func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } -func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryParamsRequest) ProtoMessage() {} -func (*QueryParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{0} -} -func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsRequest.Merge(m, src) -} -func (m *QueryParamsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo - -// QueryParamsResponse defines the response type for the Query/Params RPC method. -type QueryParamsResponse struct { - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` -} - -func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } -func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryParamsResponse) ProtoMessage() {} -func (*QueryParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{1} -} -func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsResponse.Merge(m, src) -} -func (m *QueryParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo - -// QueryAccountsRequest defines the request type for the Query/Accounts RPC method. -type QueryAccountsRequest struct { -} - -func (m *QueryAccountsRequest) Reset() { *m = QueryAccountsRequest{} } -func (m *QueryAccountsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAccountsRequest) ProtoMessage() {} -func (*QueryAccountsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{2} -} -func (m *QueryAccountsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAccountsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAccountsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryAccountsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAccountsRequest.Merge(m, src) -} -func (m *QueryAccountsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryAccountsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAccountsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAccountsRequest proto.InternalMessageInfo - -// QueryAccountsResponse defines the response type for the Query/Accounts RPC method. -type QueryAccountsResponse struct { - Accounts []types.ModuleAccount `protobuf:"bytes,1,rep,name=accounts,proto3" json:"accounts"` -} - -func (m *QueryAccountsResponse) Reset() { *m = QueryAccountsResponse{} } -func (m *QueryAccountsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAccountsResponse) ProtoMessage() {} -func (*QueryAccountsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{3} -} -func (m *QueryAccountsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAccountsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAccountsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryAccountsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAccountsResponse.Merge(m, src) -} -func (m *QueryAccountsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryAccountsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAccountsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAccountsResponse proto.InternalMessageInfo - -func (m *QueryAccountsResponse) GetAccounts() []types.ModuleAccount { - if m != nil { - return m.Accounts - } - return nil -} - -// QueryCdpRequest defines the request type for the Query/Cdp RPC method. -type QueryCdpRequest struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` -} - -func (m *QueryCdpRequest) Reset() { *m = QueryCdpRequest{} } -func (m *QueryCdpRequest) String() string { return proto.CompactTextString(m) } -func (*QueryCdpRequest) ProtoMessage() {} -func (*QueryCdpRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{4} -} -func (m *QueryCdpRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryCdpRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCdpRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryCdpRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCdpRequest.Merge(m, src) -} -func (m *QueryCdpRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryCdpRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCdpRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCdpRequest proto.InternalMessageInfo - -func (m *QueryCdpRequest) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -func (m *QueryCdpRequest) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -// QueryCdpResponse defines the response type for the Query/Cdp RPC method. -type QueryCdpResponse struct { - Cdp CDPResponse `protobuf:"bytes,1,opt,name=cdp,proto3" json:"cdp"` -} - -func (m *QueryCdpResponse) Reset() { *m = QueryCdpResponse{} } -func (m *QueryCdpResponse) String() string { return proto.CompactTextString(m) } -func (*QueryCdpResponse) ProtoMessage() {} -func (*QueryCdpResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{5} -} -func (m *QueryCdpResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryCdpResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCdpResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryCdpResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCdpResponse.Merge(m, src) -} -func (m *QueryCdpResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryCdpResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCdpResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCdpResponse proto.InternalMessageInfo - -func (m *QueryCdpResponse) GetCdp() CDPResponse { - if m != nil { - return m.Cdp - } - return CDPResponse{} -} - -// QueryCdpsRequest is the params for a filtered CDP query, the request type for the Query/Cdps RPC method. -type QueryCdpsRequest struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - ID uint64 `protobuf:"varint,3,opt,name=id,proto3" json:"id,omitempty"` - // sdk.Dec as a string - Ratio string `protobuf:"bytes,4,opt,name=ratio,proto3" json:"ratio,omitempty"` - Pagination *query.PageRequest `protobuf:"bytes,5,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryCdpsRequest) Reset() { *m = QueryCdpsRequest{} } -func (m *QueryCdpsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryCdpsRequest) ProtoMessage() {} -func (*QueryCdpsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{6} -} -func (m *QueryCdpsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryCdpsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCdpsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryCdpsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCdpsRequest.Merge(m, src) -} -func (m *QueryCdpsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryCdpsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCdpsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCdpsRequest proto.InternalMessageInfo - -func (m *QueryCdpsRequest) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -func (m *QueryCdpsRequest) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *QueryCdpsRequest) GetID() uint64 { - if m != nil { - return m.ID - } - return 0 -} - -func (m *QueryCdpsRequest) GetRatio() string { - if m != nil { - return m.Ratio - } - return "" -} - -func (m *QueryCdpsRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryCdpsResponse defines the response type for the Query/Cdps RPC method. -type QueryCdpsResponse struct { - Cdps CDPResponses `protobuf:"bytes,1,rep,name=cdps,proto3,castrepeated=CDPResponses" json:"cdps"` - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryCdpsResponse) Reset() { *m = QueryCdpsResponse{} } -func (m *QueryCdpsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryCdpsResponse) ProtoMessage() {} -func (*QueryCdpsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{7} -} -func (m *QueryCdpsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryCdpsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCdpsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryCdpsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCdpsResponse.Merge(m, src) -} -func (m *QueryCdpsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryCdpsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCdpsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCdpsResponse proto.InternalMessageInfo - -func (m *QueryCdpsResponse) GetCdps() CDPResponses { - if m != nil { - return m.Cdps - } - return nil -} - -func (m *QueryCdpsResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryDepositsRequest defines the request type for the Query/Deposits RPC method. -type QueryDepositsRequest struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` -} - -func (m *QueryDepositsRequest) Reset() { *m = QueryDepositsRequest{} } -func (m *QueryDepositsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsRequest) ProtoMessage() {} -func (*QueryDepositsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{8} -} -func (m *QueryDepositsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryDepositsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsRequest.Merge(m, src) -} -func (m *QueryDepositsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsRequest proto.InternalMessageInfo - -func (m *QueryDepositsRequest) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -func (m *QueryDepositsRequest) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -// QueryDepositsResponse defines the response type for the Query/Deposits RPC method. -type QueryDepositsResponse struct { - Deposits Deposits `protobuf:"bytes,1,rep,name=deposits,proto3,castrepeated=Deposits" json:"deposits"` -} - -func (m *QueryDepositsResponse) Reset() { *m = QueryDepositsResponse{} } -func (m *QueryDepositsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsResponse) ProtoMessage() {} -func (*QueryDepositsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{9} -} -func (m *QueryDepositsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryDepositsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsResponse.Merge(m, src) -} -func (m *QueryDepositsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsResponse proto.InternalMessageInfo - -func (m *QueryDepositsResponse) GetDeposits() Deposits { - if m != nil { - return m.Deposits - } - return nil -} - -// QueryTotalPrincipalRequest defines the request type for the Query/TotalPrincipal RPC method. -type QueryTotalPrincipalRequest struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` -} - -func (m *QueryTotalPrincipalRequest) Reset() { *m = QueryTotalPrincipalRequest{} } -func (m *QueryTotalPrincipalRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalPrincipalRequest) ProtoMessage() {} -func (*QueryTotalPrincipalRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{10} -} -func (m *QueryTotalPrincipalRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalPrincipalRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalPrincipalRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTotalPrincipalRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalPrincipalRequest.Merge(m, src) -} -func (m *QueryTotalPrincipalRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalPrincipalRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalPrincipalRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalPrincipalRequest proto.InternalMessageInfo - -func (m *QueryTotalPrincipalRequest) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -// QueryTotalPrincipalResponse defines the response type for the Query/TotalPrincipal RPC method. -type QueryTotalPrincipalResponse struct { - TotalPrincipal TotalPrincipals `protobuf:"bytes,1,rep,name=total_principal,json=totalPrincipal,proto3,castrepeated=TotalPrincipals" json:"total_principal"` -} - -func (m *QueryTotalPrincipalResponse) Reset() { *m = QueryTotalPrincipalResponse{} } -func (m *QueryTotalPrincipalResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalPrincipalResponse) ProtoMessage() {} -func (*QueryTotalPrincipalResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{11} -} -func (m *QueryTotalPrincipalResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalPrincipalResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalPrincipalResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTotalPrincipalResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalPrincipalResponse.Merge(m, src) -} -func (m *QueryTotalPrincipalResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalPrincipalResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalPrincipalResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalPrincipalResponse proto.InternalMessageInfo - -func (m *QueryTotalPrincipalResponse) GetTotalPrincipal() TotalPrincipals { - if m != nil { - return m.TotalPrincipal - } - return nil -} - -// QueryTotalCollateralRequest defines the request type for the Query/TotalCollateral RPC method. -type QueryTotalCollateralRequest struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` -} - -func (m *QueryTotalCollateralRequest) Reset() { *m = QueryTotalCollateralRequest{} } -func (m *QueryTotalCollateralRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalCollateralRequest) ProtoMessage() {} -func (*QueryTotalCollateralRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{12} -} -func (m *QueryTotalCollateralRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalCollateralRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalCollateralRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTotalCollateralRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalCollateralRequest.Merge(m, src) -} -func (m *QueryTotalCollateralRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalCollateralRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalCollateralRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalCollateralRequest proto.InternalMessageInfo - -func (m *QueryTotalCollateralRequest) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -// QueryTotalCollateralResponse defines the response type for the Query/TotalCollateral RPC method. -type QueryTotalCollateralResponse struct { - TotalCollateral TotalCollaterals `protobuf:"bytes,1,rep,name=total_collateral,json=totalCollateral,proto3,castrepeated=TotalCollaterals" json:"total_collateral"` -} - -func (m *QueryTotalCollateralResponse) Reset() { *m = QueryTotalCollateralResponse{} } -func (m *QueryTotalCollateralResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalCollateralResponse) ProtoMessage() {} -func (*QueryTotalCollateralResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{13} -} -func (m *QueryTotalCollateralResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalCollateralResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalCollateralResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTotalCollateralResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalCollateralResponse.Merge(m, src) -} -func (m *QueryTotalCollateralResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalCollateralResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalCollateralResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalCollateralResponse proto.InternalMessageInfo - -func (m *QueryTotalCollateralResponse) GetTotalCollateral() TotalCollaterals { - if m != nil { - return m.TotalCollateral - } - return nil -} - -// CDPResponse defines the state of a single collateralized debt position. -type CDPResponse struct { - ID uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Type string `protobuf:"bytes,3,opt,name=type,proto3" json:"type,omitempty"` - Collateral types1.Coin `protobuf:"bytes,4,opt,name=collateral,proto3" json:"collateral"` - Principal types1.Coin `protobuf:"bytes,5,opt,name=principal,proto3" json:"principal"` - AccumulatedFees types1.Coin `protobuf:"bytes,6,opt,name=accumulated_fees,json=accumulatedFees,proto3" json:"accumulated_fees"` - FeesUpdated time.Time `protobuf:"bytes,7,opt,name=fees_updated,json=feesUpdated,proto3,stdtime" json:"fees_updated"` - InterestFactor string `protobuf:"bytes,8,opt,name=interest_factor,json=interestFactor,proto3" json:"interest_factor,omitempty"` - CollateralValue types1.Coin `protobuf:"bytes,9,opt,name=collateral_value,json=collateralValue,proto3" json:"collateral_value"` - CollateralizationRatio string `protobuf:"bytes,10,opt,name=collateralization_ratio,json=collateralizationRatio,proto3" json:"collateralization_ratio,omitempty"` -} - -func (m *CDPResponse) Reset() { *m = CDPResponse{} } -func (m *CDPResponse) String() string { return proto.CompactTextString(m) } -func (*CDPResponse) ProtoMessage() {} -func (*CDPResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fd68799328aaf74a, []int{14} -} -func (m *CDPResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CDPResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CDPResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CDPResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_CDPResponse.Merge(m, src) -} -func (m *CDPResponse) XXX_Size() int { - return m.Size() -} -func (m *CDPResponse) XXX_DiscardUnknown() { - xxx_messageInfo_CDPResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_CDPResponse proto.InternalMessageInfo - -func (m *CDPResponse) GetID() uint64 { - if m != nil { - return m.ID - } - return 0 -} - -func (m *CDPResponse) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *CDPResponse) GetType() string { - if m != nil { - return m.Type - } - return "" -} - -func (m *CDPResponse) GetCollateral() types1.Coin { - if m != nil { - return m.Collateral - } - return types1.Coin{} -} - -func (m *CDPResponse) GetPrincipal() types1.Coin { - if m != nil { - return m.Principal - } - return types1.Coin{} -} - -func (m *CDPResponse) GetAccumulatedFees() types1.Coin { - if m != nil { - return m.AccumulatedFees - } - return types1.Coin{} -} - -func (m *CDPResponse) GetFeesUpdated() time.Time { - if m != nil { - return m.FeesUpdated - } - return time.Time{} -} - -func (m *CDPResponse) GetInterestFactor() string { - if m != nil { - return m.InterestFactor - } - return "" -} - -func (m *CDPResponse) GetCollateralValue() types1.Coin { - if m != nil { - return m.CollateralValue - } - return types1.Coin{} -} - -func (m *CDPResponse) GetCollateralizationRatio() string { - if m != nil { - return m.CollateralizationRatio - } - return "" -} - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.cdp.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.cdp.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryAccountsRequest)(nil), "kava.cdp.v1beta1.QueryAccountsRequest") - proto.RegisterType((*QueryAccountsResponse)(nil), "kava.cdp.v1beta1.QueryAccountsResponse") - proto.RegisterType((*QueryCdpRequest)(nil), "kava.cdp.v1beta1.QueryCdpRequest") - proto.RegisterType((*QueryCdpResponse)(nil), "kava.cdp.v1beta1.QueryCdpResponse") - proto.RegisterType((*QueryCdpsRequest)(nil), "kava.cdp.v1beta1.QueryCdpsRequest") - proto.RegisterType((*QueryCdpsResponse)(nil), "kava.cdp.v1beta1.QueryCdpsResponse") - proto.RegisterType((*QueryDepositsRequest)(nil), "kava.cdp.v1beta1.QueryDepositsRequest") - proto.RegisterType((*QueryDepositsResponse)(nil), "kava.cdp.v1beta1.QueryDepositsResponse") - proto.RegisterType((*QueryTotalPrincipalRequest)(nil), "kava.cdp.v1beta1.QueryTotalPrincipalRequest") - proto.RegisterType((*QueryTotalPrincipalResponse)(nil), "kava.cdp.v1beta1.QueryTotalPrincipalResponse") - proto.RegisterType((*QueryTotalCollateralRequest)(nil), "kava.cdp.v1beta1.QueryTotalCollateralRequest") - proto.RegisterType((*QueryTotalCollateralResponse)(nil), "kava.cdp.v1beta1.QueryTotalCollateralResponse") - proto.RegisterType((*CDPResponse)(nil), "kava.cdp.v1beta1.CDPResponse") -} - -func init() { proto.RegisterFile("kava/cdp/v1beta1/query.proto", fileDescriptor_fd68799328aaf74a) } - -var fileDescriptor_fd68799328aaf74a = []byte{ - // 1150 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x56, 0x4b, 0x6f, 0xe3, 0xd4, - 0x17, 0x8f, 0xd3, 0xb4, 0x93, 0xde, 0x8e, 0x9a, 0xfc, 0xef, 0x3f, 0x74, 0x5c, 0x53, 0x92, 0xd4, - 0x03, 0x6d, 0x41, 0xd4, 0xee, 0x14, 0xf1, 0x16, 0x82, 0xa6, 0xa5, 0xa3, 0x41, 0x42, 0x2a, 0xa6, - 0x80, 0x84, 0x84, 0xc2, 0x8d, 0x7d, 0xeb, 0x1a, 0x12, 0x5f, 0x8f, 0x1f, 0x1d, 0xca, 0x68, 0x84, - 0x60, 0x31, 0x62, 0x39, 0x82, 0x05, 0x0b, 0x24, 0x34, 0x1b, 0x36, 0xac, 0xf9, 0x10, 0xb3, 0x1c, - 0x01, 0x0b, 0x56, 0x33, 0xd0, 0xb2, 0xe0, 0x63, 0xa0, 0x7b, 0x7d, 0x1c, 0x3b, 0x71, 0xd2, 0x66, - 0x16, 0xb3, 0x89, 0xe2, 0xf3, 0xfa, 0xfd, 0xce, 0xf1, 0x79, 0x18, 0x2d, 0x7d, 0x4e, 0x8e, 0x88, - 0x6e, 0x5a, 0x9e, 0x7e, 0x74, 0xa5, 0x43, 0x43, 0x72, 0x45, 0xbf, 0x1e, 0x51, 0xff, 0x58, 0xf3, - 0x7c, 0x16, 0x32, 0x5c, 0xe5, 0x5a, 0xcd, 0xb4, 0x3c, 0x0d, 0xb4, 0x4a, 0xdd, 0x64, 0x41, 0x8f, - 0x05, 0x3a, 0x89, 0xc2, 0xc3, 0xbe, 0x0b, 0x7f, 0x88, 0x3d, 0x94, 0xe7, 0x40, 0xdf, 0x21, 0x01, - 0x8d, 0x43, 0xf5, 0xad, 0x3c, 0x62, 0x3b, 0x2e, 0x09, 0x1d, 0xe6, 0x82, 0x6d, 0x3d, 0x6b, 0x9b, - 0x58, 0x99, 0xcc, 0x49, 0xf4, 0x8b, 0xb1, 0xbe, 0x2d, 0x9e, 0xf4, 0xf8, 0x01, 0x54, 0x35, 0x9b, - 0xd9, 0x2c, 0x96, 0xf3, 0x7f, 0x20, 0x5d, 0xb2, 0x19, 0xb3, 0xbb, 0x54, 0x27, 0x9e, 0xa3, 0x13, - 0xd7, 0x65, 0xa1, 0x40, 0x4b, 0x7c, 0x1a, 0xa0, 0x15, 0x4f, 0x9d, 0xe8, 0x40, 0x0f, 0x9d, 0x1e, - 0x0d, 0x42, 0xd2, 0xf3, 0xc0, 0x40, 0xc9, 0xd5, 0x82, 0x67, 0x0e, 0x5c, 0x73, 0x3a, 0x9b, 0xba, - 0x34, 0x70, 0x20, 0xb8, 0x5a, 0x43, 0xf8, 0x3d, 0x9e, 0xed, 0x1e, 0xf1, 0x49, 0x2f, 0x30, 0xe8, - 0xf5, 0x88, 0x06, 0xa1, 0xfa, 0x11, 0xfa, 0xff, 0x80, 0x34, 0xf0, 0x98, 0x1b, 0x50, 0xfc, 0x12, - 0x9a, 0xf1, 0x84, 0x44, 0x96, 0x9a, 0xd2, 0xda, 0xdc, 0xa6, 0xac, 0x0d, 0xd7, 0x59, 0x8b, 0x3d, - 0x5a, 0xa5, 0x7b, 0x0f, 0x1a, 0x05, 0x03, 0xac, 0x5f, 0x2b, 0x7f, 0x7b, 0xb7, 0x51, 0xf8, 0xf7, - 0x6e, 0xa3, 0xa0, 0x2e, 0xa0, 0x9a, 0x08, 0xbc, 0x65, 0x9a, 0x2c, 0x72, 0xc3, 0x3e, 0xe0, 0x27, - 0xe8, 0x89, 0x21, 0x39, 0x40, 0xee, 0xa0, 0x32, 0x01, 0x99, 0x2c, 0x35, 0xa7, 0xd6, 0xe6, 0x36, - 0x55, 0x0d, 0x2a, 0x2a, 0xde, 0x5e, 0x82, 0xfb, 0x2e, 0xb3, 0xa2, 0x2e, 0x05, 0x77, 0x80, 0xef, - 0x7b, 0xaa, 0x9f, 0xa1, 0x8a, 0x08, 0xbf, 0x6d, 0x79, 0x80, 0x88, 0x57, 0x51, 0xc5, 0x64, 0xdd, - 0x2e, 0x09, 0xa9, 0x4f, 0xba, 0xed, 0xf0, 0xd8, 0xa3, 0x22, 0xa9, 0x59, 0x63, 0x3e, 0x15, 0xef, - 0x1f, 0x7b, 0x14, 0x6b, 0x68, 0x9a, 0xdd, 0x70, 0xa9, 0x2f, 0x17, 0xb9, 0xba, 0x25, 0xff, 0xf6, - 0xeb, 0x7a, 0x0d, 0x18, 0x6c, 0x59, 0x96, 0x4f, 0x83, 0xe0, 0xfd, 0xd0, 0x77, 0x5c, 0xdb, 0x88, - 0xcd, 0xd4, 0x6b, 0xa8, 0x9a, 0x62, 0x41, 0x16, 0x2f, 0xa2, 0x29, 0xd3, 0xf2, 0xa0, 0x6a, 0x4f, - 0xe5, 0xab, 0xb6, 0xbd, 0xb3, 0x97, 0xd8, 0x02, 0x77, 0x6e, 0xaf, 0xfe, 0x2d, 0xa5, 0xb1, 0x82, - 0xc7, 0x4d, 0x1c, 0x2f, 0xa0, 0xa2, 0x63, 0xc9, 0x53, 0x4d, 0x69, 0xad, 0xd4, 0x9a, 0x39, 0x79, - 0xd0, 0x28, 0x5e, 0xdb, 0x31, 0x8a, 0x8e, 0x85, 0x6b, 0x68, 0xda, 0xe7, 0x0d, 0x29, 0x97, 0x04, - 0x4c, 0xfc, 0x80, 0x77, 0x11, 0x4a, 0x07, 0x43, 0x9e, 0x16, 0x99, 0xad, 0x24, 0xaf, 0x86, 0x4f, - 0x86, 0x16, 0x0f, 0x64, 0xda, 0x18, 0x36, 0x85, 0x14, 0x8c, 0x8c, 0xa7, 0xfa, 0xb3, 0x84, 0xfe, - 0x97, 0xc9, 0x11, 0x0a, 0x76, 0x15, 0x95, 0x4c, 0xcb, 0x4b, 0x5e, 0xf9, 0x39, 0x15, 0xab, 0xf1, - 0x8a, 0xfd, 0xf2, 0xb0, 0x71, 0x31, 0x23, 0x0c, 0x0c, 0x11, 0x00, 0x5f, 0x1d, 0xa0, 0x59, 0x14, - 0x34, 0x57, 0xcf, 0xa5, 0x19, 0xc7, 0x18, 0xe0, 0xc9, 0xa0, 0x73, 0x77, 0xa8, 0xc7, 0x02, 0x27, - 0x7c, 0xec, 0xaf, 0x43, 0xfd, 0x14, 0x46, 0x22, 0x05, 0xec, 0xd7, 0xa6, 0x6c, 0x81, 0x0c, 0xea, - 0xb3, 0x98, 0xaf, 0x0f, 0x78, 0xb5, 0xaa, 0x50, 0x9b, 0x72, 0x3f, 0x4c, 0xdf, 0x59, 0x7d, 0x1b, - 0x29, 0x02, 0x61, 0x9f, 0x85, 0xa4, 0xbb, 0xe7, 0x3b, 0xae, 0xe9, 0x78, 0xa4, 0xfb, 0xa8, 0x89, - 0xa9, 0x5f, 0x4b, 0xe8, 0xc9, 0x91, 0x71, 0x80, 0x6f, 0x07, 0x55, 0x42, 0xae, 0x69, 0x7b, 0x89, - 0x0a, 0x68, 0x37, 0xf3, 0xb4, 0x07, 0x43, 0xb4, 0x2e, 0x01, 0xfb, 0xca, 0xa0, 0x3c, 0x30, 0xe6, - 0xc3, 0x01, 0x81, 0xba, 0x9b, 0xa5, 0xb0, 0xdd, 0xe7, 0xf7, 0xc8, 0xb9, 0xdc, 0x96, 0xd0, 0xd2, - 0xe8, 0x40, 0x90, 0xcc, 0x01, 0xaa, 0xc6, 0xc9, 0xa4, 0x8e, 0x90, 0xcd, 0xf2, 0x98, 0x6c, 0xd2, - 0x20, 0x2d, 0x19, 0xd2, 0xa9, 0x0e, 0x29, 0x02, 0x23, 0xae, 0x50, 0x2a, 0x51, 0xbf, 0x2b, 0xa1, - 0xb9, 0x4c, 0x3b, 0xc3, 0x70, 0x4a, 0xa3, 0x86, 0x33, 0xd3, 0x55, 0xc9, 0x28, 0x63, 0x54, 0x12, - 0x49, 0x4e, 0x09, 0xa1, 0xf8, 0x8f, 0xdf, 0x44, 0x28, 0xc3, 0xb9, 0x24, 0x26, 0x61, 0x71, 0x60, - 0x12, 0xfa, 0xb3, 0xc5, 0x1c, 0x17, 0xd6, 0x50, 0xc6, 0x05, 0xbf, 0x81, 0x66, 0xd3, 0x37, 0x38, - 0x3d, 0x99, 0x7f, 0xea, 0x81, 0xdf, 0x41, 0x55, 0x62, 0x9a, 0x51, 0x2f, 0xe2, 0xf1, 0xac, 0xf6, - 0x01, 0xa5, 0x81, 0x3c, 0x33, 0x59, 0x94, 0x4a, 0xc6, 0x71, 0x97, 0x52, 0x3e, 0xd5, 0x17, 0xb9, - 0x7f, 0x3b, 0xf2, 0x2c, 0x2e, 0x93, 0x2f, 0x88, 0x38, 0x8a, 0x16, 0x5f, 0x4a, 0x2d, 0xb9, 0x94, - 0xda, 0x7e, 0x72, 0x29, 0x5b, 0x65, 0x1e, 0xe8, 0xce, 0xc3, 0x86, 0x64, 0xcc, 0x71, 0xcf, 0x0f, - 0x62, 0x47, 0xde, 0x18, 0x8e, 0x1b, 0x52, 0x9f, 0x06, 0x61, 0xfb, 0x80, 0x98, 0x21, 0xf3, 0xe5, - 0x72, 0xdc, 0x18, 0x89, 0x78, 0x57, 0x48, 0x39, 0xfb, 0x4c, 0x07, 0x1d, 0x91, 0x6e, 0x44, 0xe5, - 0xd9, 0x09, 0xd9, 0xa7, 0x8e, 0x1f, 0x72, 0x3f, 0xfc, 0x32, 0xba, 0x94, 0x8a, 0x9c, 0x2f, 0xc5, - 0x7e, 0x69, 0xc7, 0x2b, 0x16, 0x09, 0xf0, 0x85, 0x9c, 0xda, 0xe0, 0xbf, 0x9b, 0x7f, 0x5c, 0x40, - 0xd3, 0xa2, 0x3b, 0xf1, 0x0d, 0x34, 0x13, 0x5f, 0x5a, 0xfc, 0x74, 0xbe, 0xed, 0xf2, 0x07, 0x5d, - 0x79, 0xe6, 0x1c, 0xab, 0xb8, 0xcb, 0xd4, 0xe6, 0x37, 0xbf, 0xff, 0xf3, 0x7d, 0x51, 0xc1, 0xb2, - 0x9e, 0xfb, 0x6c, 0x88, 0x4f, 0x39, 0xfe, 0x0a, 0x95, 0x93, 0x1b, 0x8d, 0x57, 0xc6, 0x04, 0x1d, - 0x3a, 0xee, 0xca, 0xea, 0xb9, 0x76, 0x00, 0xaf, 0x0a, 0xf8, 0x25, 0xac, 0xe4, 0xe1, 0x93, 0x53, - 0x8e, 0x7f, 0x90, 0xd0, 0xfc, 0xe0, 0x36, 0xc0, 0xcf, 0x8f, 0x89, 0x3f, 0x72, 0xaf, 0x29, 0xeb, - 0x13, 0x5a, 0x03, 0xa7, 0x35, 0xc1, 0x49, 0xc5, 0xcd, 0x3c, 0xa7, 0xc1, 0x1d, 0x84, 0x7f, 0x94, - 0x50, 0x65, 0x68, 0xb0, 0xf1, 0x99, 0x60, 0xb9, 0x3d, 0xa5, 0x68, 0x93, 0x9a, 0x03, 0xb9, 0x67, - 0x05, 0xb9, 0xcb, 0x78, 0x79, 0x0c, 0xb9, 0x0c, 0x13, 0x86, 0x4a, 0xfc, 0xc2, 0x62, 0x75, 0x0c, - 0x44, 0xe6, 0x13, 0x43, 0xb9, 0x7c, 0xa6, 0x0d, 0x60, 0xd7, 0x05, 0xb6, 0x8c, 0x17, 0xf4, 0x51, - 0x9f, 0x9f, 0x01, 0xbe, 0x2d, 0xa1, 0xa9, 0x6d, 0xcb, 0xc3, 0xcb, 0xe3, 0x83, 0x25, 0x78, 0xea, - 0x59, 0x26, 0x00, 0xf7, 0x8a, 0x80, 0xdb, 0xc4, 0x1b, 0xa3, 0xe1, 0xf4, 0x9b, 0x62, 0xf3, 0xdd, - 0xd2, 0x6f, 0x0e, 0x2d, 0xfa, 0x5b, 0xf8, 0x27, 0x09, 0xf5, 0xaf, 0xdf, 0xd8, 0x9e, 0x1d, 0x3a, - 0xeb, 0x63, 0x7b, 0x76, 0xf8, 0x1a, 0xab, 0x5b, 0x82, 0xd7, 0xeb, 0xf8, 0xd5, 0x31, 0xbc, 0x92, - 0x6b, 0x3b, 0x9e, 0x60, 0xeb, 0xad, 0x7b, 0x27, 0x75, 0xe9, 0xfe, 0x49, 0x5d, 0xfa, 0xeb, 0xa4, - 0x2e, 0xdd, 0x39, 0xad, 0x17, 0xee, 0x9f, 0xd6, 0x0b, 0x7f, 0x9e, 0xd6, 0x0b, 0x1f, 0xaf, 0xd8, - 0x4e, 0x78, 0x18, 0x75, 0x34, 0x93, 0xf5, 0xf4, 0x0d, 0xbb, 0x4b, 0x3a, 0x81, 0xbe, 0x61, 0xaf, - 0x9b, 0x87, 0xc4, 0x71, 0xf5, 0x2f, 0x04, 0x16, 0x8f, 0x10, 0x74, 0x66, 0xc4, 0xc6, 0x7b, 0xe1, - 0xbf, 0x00, 0x00, 0x00, 0xff, 0xff, 0xa8, 0x6d, 0x9d, 0x1e, 0x16, 0x0d, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - // Params queries all parameters of the cdp module. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Accounts queries the CDP module accounts. - Accounts(ctx context.Context, in *QueryAccountsRequest, opts ...grpc.CallOption) (*QueryAccountsResponse, error) - // TotalPrincipal queries the total principal of a given collateral type. - TotalPrincipal(ctx context.Context, in *QueryTotalPrincipalRequest, opts ...grpc.CallOption) (*QueryTotalPrincipalResponse, error) - // TotalCollateral queries the total collateral of a given collateral type. - TotalCollateral(ctx context.Context, in *QueryTotalCollateralRequest, opts ...grpc.CallOption) (*QueryTotalCollateralResponse, error) - // Cdps queries all active CDPs. - Cdps(ctx context.Context, in *QueryCdpsRequest, opts ...grpc.CallOption) (*QueryCdpsResponse, error) - // Cdp queries a CDP with the input owner address and collateral type. - Cdp(ctx context.Context, in *QueryCdpRequest, opts ...grpc.CallOption) (*QueryCdpResponse, error) - // Deposits queries deposits associated with the CDP owned by an address for a collateral type. - Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { - out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Accounts(ctx context.Context, in *QueryAccountsRequest, opts ...grpc.CallOption) (*QueryAccountsResponse, error) { - out := new(QueryAccountsResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Query/Accounts", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalPrincipal(ctx context.Context, in *QueryTotalPrincipalRequest, opts ...grpc.CallOption) (*QueryTotalPrincipalResponse, error) { - out := new(QueryTotalPrincipalResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Query/TotalPrincipal", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalCollateral(ctx context.Context, in *QueryTotalCollateralRequest, opts ...grpc.CallOption) (*QueryTotalCollateralResponse, error) { - out := new(QueryTotalCollateralResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Query/TotalCollateral", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Cdps(ctx context.Context, in *QueryCdpsRequest, opts ...grpc.CallOption) (*QueryCdpsResponse, error) { - out := new(QueryCdpsResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Query/Cdps", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Cdp(ctx context.Context, in *QueryCdpRequest, opts ...grpc.CallOption) (*QueryCdpResponse, error) { - out := new(QueryCdpResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Query/Cdp", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, error) { - out := new(QueryDepositsResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Query/Deposits", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries all parameters of the cdp module. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Accounts queries the CDP module accounts. - Accounts(context.Context, *QueryAccountsRequest) (*QueryAccountsResponse, error) - // TotalPrincipal queries the total principal of a given collateral type. - TotalPrincipal(context.Context, *QueryTotalPrincipalRequest) (*QueryTotalPrincipalResponse, error) - // TotalCollateral queries the total collateral of a given collateral type. - TotalCollateral(context.Context, *QueryTotalCollateralRequest) (*QueryTotalCollateralResponse, error) - // Cdps queries all active CDPs. - Cdps(context.Context, *QueryCdpsRequest) (*QueryCdpsResponse, error) - // Cdp queries a CDP with the input owner address and collateral type. - Cdp(context.Context, *QueryCdpRequest) (*QueryCdpResponse, error) - // Deposits queries deposits associated with the CDP owned by an address for a collateral type. - Deposits(context.Context, *QueryDepositsRequest) (*QueryDepositsResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") -} -func (*UnimplementedQueryServer) Accounts(ctx context.Context, req *QueryAccountsRequest) (*QueryAccountsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Accounts not implemented") -} -func (*UnimplementedQueryServer) TotalPrincipal(ctx context.Context, req *QueryTotalPrincipalRequest) (*QueryTotalPrincipalResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalPrincipal not implemented") -} -func (*UnimplementedQueryServer) TotalCollateral(ctx context.Context, req *QueryTotalCollateralRequest) (*QueryTotalCollateralResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalCollateral not implemented") -} -func (*UnimplementedQueryServer) Cdps(ctx context.Context, req *QueryCdpsRequest) (*QueryCdpsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Cdps not implemented") -} -func (*UnimplementedQueryServer) Cdp(ctx context.Context, req *QueryCdpRequest) (*QueryCdpResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Cdp not implemented") -} -func (*UnimplementedQueryServer) Deposits(ctx context.Context, req *QueryDepositsRequest) (*QueryDepositsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposits not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryParamsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Params(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Query/Params", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Accounts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAccountsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Accounts(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Query/Accounts", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Accounts(ctx, req.(*QueryAccountsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalPrincipal_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalPrincipalRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalPrincipal(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Query/TotalPrincipal", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalPrincipal(ctx, req.(*QueryTotalPrincipalRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalCollateral_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalCollateralRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalCollateral(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Query/TotalCollateral", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalCollateral(ctx, req.(*QueryTotalCollateralRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Cdps_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryCdpsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Cdps(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Query/Cdps", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Cdps(ctx, req.(*QueryCdpsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Cdp_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryCdpRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Cdp(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Query/Cdp", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Cdp(ctx, req.(*QueryCdpRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Deposits_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryDepositsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Deposits(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Query/Deposits", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Deposits(ctx, req.(*QueryDepositsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.cdp.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Accounts", - Handler: _Query_Accounts_Handler, - }, - { - MethodName: "TotalPrincipal", - Handler: _Query_TotalPrincipal_Handler, - }, - { - MethodName: "TotalCollateral", - Handler: _Query_TotalCollateral_Handler, - }, - { - MethodName: "Cdps", - Handler: _Query_Cdps_Handler, - }, - { - MethodName: "Cdp", - Handler: _Query_Cdp_Handler, - }, - { - MethodName: "Deposits", - Handler: _Query_Deposits_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/cdp/v1beta1/query.proto", -} - -func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryAccountsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryAccountsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAccountsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryAccountsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryAccountsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAccountsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Accounts) > 0 { - for iNdEx := len(m.Accounts) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Accounts[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryCdpRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryCdpRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCdpRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintQuery(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryCdpResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryCdpResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCdpResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Cdp.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryCdpsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryCdpsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCdpsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - if len(m.Ratio) > 0 { - i -= len(m.Ratio) - copy(dAtA[i:], m.Ratio) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Ratio))) - i-- - dAtA[i] = 0x22 - } - if m.ID != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.ID)) - i-- - dAtA[i] = 0x18 - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintQuery(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryCdpsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryCdpsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCdpsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Cdps) > 0 { - for iNdEx := len(m.Cdps) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Cdps[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryDepositsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryDepositsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintQuery(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDepositsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryDepositsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Deposits) > 0 { - for iNdEx := len(m.Deposits) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposits[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalPrincipalRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryTotalPrincipalRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalPrincipalRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintQuery(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalPrincipalResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryTotalPrincipalResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalPrincipalResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.TotalPrincipal) > 0 { - for iNdEx := len(m.TotalPrincipal) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TotalPrincipal[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalCollateralRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryTotalCollateralRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalCollateralRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintQuery(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalCollateralResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryTotalCollateralResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalCollateralResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.TotalCollateral) > 0 { - for iNdEx := len(m.TotalCollateral) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TotalCollateral[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *CDPResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CDPResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CDPResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CollateralizationRatio) > 0 { - i -= len(m.CollateralizationRatio) - copy(dAtA[i:], m.CollateralizationRatio) - i = encodeVarintQuery(dAtA, i, uint64(len(m.CollateralizationRatio))) - i-- - dAtA[i] = 0x52 - } - { - size, err := m.CollateralValue.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x4a - if len(m.InterestFactor) > 0 { - i -= len(m.InterestFactor) - copy(dAtA[i:], m.InterestFactor) - i = encodeVarintQuery(dAtA, i, uint64(len(m.InterestFactor))) - i-- - dAtA[i] = 0x42 - } - n6, err6 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.FeesUpdated, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.FeesUpdated):]) - if err6 != nil { - return 0, err6 - } - i -= n6 - i = encodeVarintQuery(dAtA, i, uint64(n6)) - i-- - dAtA[i] = 0x3a - { - size, err := m.AccumulatedFees.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size, err := m.Principal.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.Collateral.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - if len(m.Type) > 0 { - i -= len(m.Type) - copy(dAtA[i:], m.Type) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Type))) - i-- - dAtA[i] = 0x1a - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if m.ID != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.ID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryParamsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryAccountsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryAccountsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Accounts) > 0 { - for _, e := range m.Accounts { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryCdpRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryCdpResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Cdp.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryCdpsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.ID != 0 { - n += 1 + sovQuery(uint64(m.ID)) - } - l = len(m.Ratio) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryCdpsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Cdps) > 0 { - for _, e := range m.Cdps { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDepositsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDepositsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Deposits) > 0 { - for _, e := range m.Deposits { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryTotalPrincipalRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryTotalPrincipalResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.TotalPrincipal) > 0 { - for _, e := range m.TotalPrincipal { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryTotalCollateralRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryTotalCollateralResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.TotalCollateral) > 0 { - for _, e := range m.TotalCollateral { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *CDPResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.ID != 0 { - n += 1 + sovQuery(uint64(m.ID)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Type) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = m.Collateral.Size() - n += 1 + l + sovQuery(uint64(l)) - l = m.Principal.Size() - n += 1 + l + sovQuery(uint64(l)) - l = m.AccumulatedFees.Size() - n += 1 + l + sovQuery(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.FeesUpdated) - n += 1 + l + sovQuery(uint64(l)) - l = len(m.InterestFactor) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = m.CollateralValue.Size() - n += 1 + l + sovQuery(uint64(l)) - l = len(m.CollateralizationRatio) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryAccountsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryAccountsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAccountsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryAccountsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryAccountsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAccountsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Accounts", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Accounts = append(m.Accounts, types.ModuleAccount{}) - if err := m.Accounts[len(m.Accounts)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryCdpRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryCdpRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCdpRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryCdpResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryCdpResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCdpResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Cdp", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Cdp.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryCdpsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryCdpsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCdpsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - m.ID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Ratio", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Ratio = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryCdpsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryCdpsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCdpsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Cdps", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Cdps = append(m.Cdps, CDPResponse{}) - if err := m.Cdps[len(m.Cdps)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDepositsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryDepositsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDepositsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryDepositsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposits", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Deposits = append(m.Deposits, Deposit{}) - if err := m.Deposits[len(m.Deposits)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTotalPrincipalRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTotalPrincipalRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalPrincipalRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTotalPrincipalResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTotalPrincipalResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalPrincipalResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalPrincipal", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TotalPrincipal = append(m.TotalPrincipal, TotalPrincipal{}) - if err := m.TotalPrincipal[len(m.TotalPrincipal)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTotalCollateralRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTotalCollateralRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalCollateralRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTotalCollateralResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTotalCollateralResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalCollateralResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalCollateral", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TotalCollateral = append(m.TotalCollateral, TotalCollateral{}) - if err := m.TotalCollateral[len(m.TotalCollateral)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CDPResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CDPResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CDPResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - m.ID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Type = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Collateral", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Collateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Principal", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Principal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AccumulatedFees", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.AccumulatedFees.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FeesUpdated", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.FeesUpdated, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InterestFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.InterestFactor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralValue", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.CollateralValue.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralizationRatio", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralizationRatio = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/cdp/types/query.pb.gw.go b/x/cdp/types/query.pb.gw.go deleted file mode 100644 index ca1fd21e..00000000 --- a/x/cdp/types/query.pb.gw.go +++ /dev/null @@ -1,713 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/cdp/v1beta1/query.proto - -/* -Package types is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package types - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join - -func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Params(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Accounts_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAccountsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Accounts(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Accounts_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAccountsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Accounts(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_TotalPrincipal_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_TotalPrincipal_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalPrincipalRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_TotalPrincipal_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.TotalPrincipal(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TotalPrincipal_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalPrincipalRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_TotalPrincipal_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.TotalPrincipal(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_TotalCollateral_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_TotalCollateral_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalCollateralRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_TotalCollateral_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.TotalCollateral(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TotalCollateral_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalCollateralRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_TotalCollateral_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.TotalCollateral(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Cdps_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Cdps_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCdpsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Cdps_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Cdps(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Cdps_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCdpsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Cdps_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Cdps(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Cdp_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCdpRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["owner"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "owner") - } - - protoReq.Owner, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "owner", err) - } - - val, ok = pathParams["collateral_type"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "collateral_type") - } - - protoReq.CollateralType, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "collateral_type", err) - } - - msg, err := client.Cdp(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Cdp_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCdpRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["owner"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "owner") - } - - protoReq.Owner, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "owner", err) - } - - val, ok = pathParams["collateral_type"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "collateral_type") - } - - protoReq.CollateralType, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "collateral_type", err) - } - - msg, err := server.Cdp(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["owner"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "owner") - } - - protoReq.Owner, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "owner", err) - } - - val, ok = pathParams["collateral_type"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "collateral_type") - } - - protoReq.CollateralType, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "collateral_type", err) - } - - msg, err := client.Deposits(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["owner"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "owner") - } - - protoReq.Owner, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "owner", err) - } - - val, ok = pathParams["collateral_type"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "collateral_type") - } - - protoReq.CollateralType, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "collateral_type", err) - } - - msg, err := server.Deposits(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Accounts_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Accounts_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Accounts_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalPrincipal_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_TotalPrincipal_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TotalPrincipal_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalCollateral_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_TotalCollateral_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TotalCollateral_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Cdps_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Cdps_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Cdps_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Cdp_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Cdp_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Cdp_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Deposits_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Deposits_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Deposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Accounts_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Accounts_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Accounts_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalPrincipal_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_TotalPrincipal_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TotalPrincipal_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalCollateral_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_TotalCollateral_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TotalCollateral_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Cdps_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Cdps_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Cdps_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Cdp_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Cdp_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Cdp_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Deposits_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Deposits_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Deposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "cdp", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Accounts_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "cdp", "v1beta1", "accounts"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TotalPrincipal_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "cdp", "v1beta1", "totalPrincipal"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TotalCollateral_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "cdp", "v1beta1", "totalCollateral"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Cdps_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "cdp", "v1beta1", "cdps"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Cdp_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 1, 0, 4, 1, 5, 5}, []string{"kava", "cdp", "v1beta1", "cdps", "owner", "collateral_type"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Deposits_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 1, 0, 4, 1, 5, 5, 1, 0, 4, 1, 5, 6}, []string{"kava", "cdp", "v1beta1", "cdps", "deposits", "owner", "collateral_type"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Accounts_0 = runtime.ForwardResponseMessage - - forward_Query_TotalPrincipal_0 = runtime.ForwardResponseMessage - - forward_Query_TotalCollateral_0 = runtime.ForwardResponseMessage - - forward_Query_Cdps_0 = runtime.ForwardResponseMessage - - forward_Query_Cdp_0 = runtime.ForwardResponseMessage - - forward_Query_Deposits_0 = runtime.ForwardResponseMessage -) diff --git a/x/cdp/types/tx.pb.go b/x/cdp/types/tx.pb.go deleted file mode 100644 index ac7c1464..00000000 --- a/x/cdp/types/tx.pb.go +++ /dev/null @@ -1,3016 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/cdp/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// MsgCreateCDP defines a message to create a new CDP. -type MsgCreateCDP struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Collateral types.Coin `protobuf:"bytes,2,opt,name=collateral,proto3" json:"collateral"` - Principal types.Coin `protobuf:"bytes,3,opt,name=principal,proto3" json:"principal"` - CollateralType string `protobuf:"bytes,4,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` -} - -func (m *MsgCreateCDP) Reset() { *m = MsgCreateCDP{} } -func (m *MsgCreateCDP) String() string { return proto.CompactTextString(m) } -func (*MsgCreateCDP) ProtoMessage() {} -func (*MsgCreateCDP) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{0} -} -func (m *MsgCreateCDP) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgCreateCDP) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgCreateCDP.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgCreateCDP) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgCreateCDP.Merge(m, src) -} -func (m *MsgCreateCDP) XXX_Size() int { - return m.Size() -} -func (m *MsgCreateCDP) XXX_DiscardUnknown() { - xxx_messageInfo_MsgCreateCDP.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgCreateCDP proto.InternalMessageInfo - -func (m *MsgCreateCDP) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgCreateCDP) GetCollateral() types.Coin { - if m != nil { - return m.Collateral - } - return types.Coin{} -} - -func (m *MsgCreateCDP) GetPrincipal() types.Coin { - if m != nil { - return m.Principal - } - return types.Coin{} -} - -func (m *MsgCreateCDP) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -// MsgCreateCDPResponse defines the Msg/CreateCDP response type. -type MsgCreateCDPResponse struct { - CdpID uint64 `protobuf:"varint,1,opt,name=cdp_id,json=cdpId,proto3" json:"cdp_id,omitempty"` -} - -func (m *MsgCreateCDPResponse) Reset() { *m = MsgCreateCDPResponse{} } -func (m *MsgCreateCDPResponse) String() string { return proto.CompactTextString(m) } -func (*MsgCreateCDPResponse) ProtoMessage() {} -func (*MsgCreateCDPResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{1} -} -func (m *MsgCreateCDPResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgCreateCDPResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgCreateCDPResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgCreateCDPResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgCreateCDPResponse.Merge(m, src) -} -func (m *MsgCreateCDPResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgCreateCDPResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgCreateCDPResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgCreateCDPResponse proto.InternalMessageInfo - -func (m *MsgCreateCDPResponse) GetCdpID() uint64 { - if m != nil { - return m.CdpID - } - return 0 -} - -// MsgDeposit defines a message to deposit to a CDP. -type MsgDeposit struct { - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Collateral types.Coin `protobuf:"bytes,3,opt,name=collateral,proto3" json:"collateral"` - CollateralType string `protobuf:"bytes,4,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` -} - -func (m *MsgDeposit) Reset() { *m = MsgDeposit{} } -func (m *MsgDeposit) String() string { return proto.CompactTextString(m) } -func (*MsgDeposit) ProtoMessage() {} -func (*MsgDeposit) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{2} -} -func (m *MsgDeposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDeposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDeposit.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgDeposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDeposit.Merge(m, src) -} -func (m *MsgDeposit) XXX_Size() int { - return m.Size() -} -func (m *MsgDeposit) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDeposit.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDeposit proto.InternalMessageInfo - -func (m *MsgDeposit) GetDepositor() string { - if m != nil { - return m.Depositor - } - return "" -} - -func (m *MsgDeposit) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *MsgDeposit) GetCollateral() types.Coin { - if m != nil { - return m.Collateral - } - return types.Coin{} -} - -func (m *MsgDeposit) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -// MsgDepositResponse defines the Msg/Deposit response type. -type MsgDepositResponse struct { -} - -func (m *MsgDepositResponse) Reset() { *m = MsgDepositResponse{} } -func (m *MsgDepositResponse) String() string { return proto.CompactTextString(m) } -func (*MsgDepositResponse) ProtoMessage() {} -func (*MsgDepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{3} -} -func (m *MsgDepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDepositResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgDepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDepositResponse.Merge(m, src) -} -func (m *MsgDepositResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgDepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDepositResponse proto.InternalMessageInfo - -// MsgWithdraw defines a message to withdraw collateral from a CDP. -type MsgWithdraw struct { - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Collateral types.Coin `protobuf:"bytes,3,opt,name=collateral,proto3" json:"collateral"` - CollateralType string `protobuf:"bytes,4,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` -} - -func (m *MsgWithdraw) Reset() { *m = MsgWithdraw{} } -func (m *MsgWithdraw) String() string { return proto.CompactTextString(m) } -func (*MsgWithdraw) ProtoMessage() {} -func (*MsgWithdraw) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{4} -} -func (m *MsgWithdraw) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdraw) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdraw.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgWithdraw) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdraw.Merge(m, src) -} -func (m *MsgWithdraw) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdraw) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdraw.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdraw proto.InternalMessageInfo - -func (m *MsgWithdraw) GetDepositor() string { - if m != nil { - return m.Depositor - } - return "" -} - -func (m *MsgWithdraw) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *MsgWithdraw) GetCollateral() types.Coin { - if m != nil { - return m.Collateral - } - return types.Coin{} -} - -func (m *MsgWithdraw) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -type MsgWithdrawResponse struct { -} - -func (m *MsgWithdrawResponse) Reset() { *m = MsgWithdrawResponse{} } -func (m *MsgWithdrawResponse) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawResponse) ProtoMessage() {} -func (*MsgWithdrawResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{5} -} -func (m *MsgWithdrawResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgWithdrawResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawResponse.Merge(m, src) -} -func (m *MsgWithdrawResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawResponse proto.InternalMessageInfo - -// MsgDrawDebt defines a message to draw debt from a CDP. -type MsgDrawDebt struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - CollateralType string `protobuf:"bytes,2,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Principal types.Coin `protobuf:"bytes,3,opt,name=principal,proto3" json:"principal"` -} - -func (m *MsgDrawDebt) Reset() { *m = MsgDrawDebt{} } -func (m *MsgDrawDebt) String() string { return proto.CompactTextString(m) } -func (*MsgDrawDebt) ProtoMessage() {} -func (*MsgDrawDebt) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{6} -} -func (m *MsgDrawDebt) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDrawDebt) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDrawDebt.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgDrawDebt) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDrawDebt.Merge(m, src) -} -func (m *MsgDrawDebt) XXX_Size() int { - return m.Size() -} -func (m *MsgDrawDebt) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDrawDebt.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDrawDebt proto.InternalMessageInfo - -func (m *MsgDrawDebt) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgDrawDebt) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -func (m *MsgDrawDebt) GetPrincipal() types.Coin { - if m != nil { - return m.Principal - } - return types.Coin{} -} - -// MsgDrawDebtResponse defines the Msg/DrawDebt response type. -type MsgDrawDebtResponse struct { -} - -func (m *MsgDrawDebtResponse) Reset() { *m = MsgDrawDebtResponse{} } -func (m *MsgDrawDebtResponse) String() string { return proto.CompactTextString(m) } -func (*MsgDrawDebtResponse) ProtoMessage() {} -func (*MsgDrawDebtResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{7} -} -func (m *MsgDrawDebtResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDrawDebtResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDrawDebtResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgDrawDebtResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDrawDebtResponse.Merge(m, src) -} -func (m *MsgDrawDebtResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgDrawDebtResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDrawDebtResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDrawDebtResponse proto.InternalMessageInfo - -// MsgRepayDebt defines a message to repay debt from a CDP. -type MsgRepayDebt struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - CollateralType string `protobuf:"bytes,2,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Payment types.Coin `protobuf:"bytes,3,opt,name=payment,proto3" json:"payment"` -} - -func (m *MsgRepayDebt) Reset() { *m = MsgRepayDebt{} } -func (m *MsgRepayDebt) String() string { return proto.CompactTextString(m) } -func (*MsgRepayDebt) ProtoMessage() {} -func (*MsgRepayDebt) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{8} -} -func (m *MsgRepayDebt) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgRepayDebt) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgRepayDebt.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgRepayDebt) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgRepayDebt.Merge(m, src) -} -func (m *MsgRepayDebt) XXX_Size() int { - return m.Size() -} -func (m *MsgRepayDebt) XXX_DiscardUnknown() { - xxx_messageInfo_MsgRepayDebt.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgRepayDebt proto.InternalMessageInfo - -func (m *MsgRepayDebt) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgRepayDebt) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -func (m *MsgRepayDebt) GetPayment() types.Coin { - if m != nil { - return m.Payment - } - return types.Coin{} -} - -// MsgRepayDebtResponse defines the Msg/RepayDebt response type. -type MsgRepayDebtResponse struct { -} - -func (m *MsgRepayDebtResponse) Reset() { *m = MsgRepayDebtResponse{} } -func (m *MsgRepayDebtResponse) String() string { return proto.CompactTextString(m) } -func (*MsgRepayDebtResponse) ProtoMessage() {} -func (*MsgRepayDebtResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{9} -} -func (m *MsgRepayDebtResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgRepayDebtResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgRepayDebtResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgRepayDebtResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgRepayDebtResponse.Merge(m, src) -} -func (m *MsgRepayDebtResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgRepayDebtResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgRepayDebtResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgRepayDebtResponse proto.InternalMessageInfo - -// MsgLiquidate defines a message to attempt to liquidate a CDP whos -// collateralization ratio is under its liquidation ratio. -type MsgLiquidate struct { - Keeper string `protobuf:"bytes,1,opt,name=keeper,proto3" json:"keeper,omitempty"` - Borrower string `protobuf:"bytes,2,opt,name=borrower,proto3" json:"borrower,omitempty"` - CollateralType string `protobuf:"bytes,3,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` -} - -func (m *MsgLiquidate) Reset() { *m = MsgLiquidate{} } -func (m *MsgLiquidate) String() string { return proto.CompactTextString(m) } -func (*MsgLiquidate) ProtoMessage() {} -func (*MsgLiquidate) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{10} -} -func (m *MsgLiquidate) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgLiquidate) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgLiquidate.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgLiquidate) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgLiquidate.Merge(m, src) -} -func (m *MsgLiquidate) XXX_Size() int { - return m.Size() -} -func (m *MsgLiquidate) XXX_DiscardUnknown() { - xxx_messageInfo_MsgLiquidate.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgLiquidate proto.InternalMessageInfo - -func (m *MsgLiquidate) GetKeeper() string { - if m != nil { - return m.Keeper - } - return "" -} - -func (m *MsgLiquidate) GetBorrower() string { - if m != nil { - return m.Borrower - } - return "" -} - -func (m *MsgLiquidate) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -// MsgLiquidateResponse defines the Msg/Liquidate response type. -type MsgLiquidateResponse struct { -} - -func (m *MsgLiquidateResponse) Reset() { *m = MsgLiquidateResponse{} } -func (m *MsgLiquidateResponse) String() string { return proto.CompactTextString(m) } -func (*MsgLiquidateResponse) ProtoMessage() {} -func (*MsgLiquidateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3b8c9334ad8ab0d3, []int{11} -} -func (m *MsgLiquidateResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgLiquidateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgLiquidateResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgLiquidateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgLiquidateResponse.Merge(m, src) -} -func (m *MsgLiquidateResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgLiquidateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgLiquidateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgLiquidateResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgCreateCDP)(nil), "kava.cdp.v1beta1.MsgCreateCDP") - proto.RegisterType((*MsgCreateCDPResponse)(nil), "kava.cdp.v1beta1.MsgCreateCDPResponse") - proto.RegisterType((*MsgDeposit)(nil), "kava.cdp.v1beta1.MsgDeposit") - proto.RegisterType((*MsgDepositResponse)(nil), "kava.cdp.v1beta1.MsgDepositResponse") - proto.RegisterType((*MsgWithdraw)(nil), "kava.cdp.v1beta1.MsgWithdraw") - proto.RegisterType((*MsgWithdrawResponse)(nil), "kava.cdp.v1beta1.MsgWithdrawResponse") - proto.RegisterType((*MsgDrawDebt)(nil), "kava.cdp.v1beta1.MsgDrawDebt") - proto.RegisterType((*MsgDrawDebtResponse)(nil), "kava.cdp.v1beta1.MsgDrawDebtResponse") - proto.RegisterType((*MsgRepayDebt)(nil), "kava.cdp.v1beta1.MsgRepayDebt") - proto.RegisterType((*MsgRepayDebtResponse)(nil), "kava.cdp.v1beta1.MsgRepayDebtResponse") - proto.RegisterType((*MsgLiquidate)(nil), "kava.cdp.v1beta1.MsgLiquidate") - proto.RegisterType((*MsgLiquidateResponse)(nil), "kava.cdp.v1beta1.MsgLiquidateResponse") -} - -func init() { proto.RegisterFile("kava/cdp/v1beta1/tx.proto", fileDescriptor_3b8c9334ad8ab0d3) } - -var fileDescriptor_3b8c9334ad8ab0d3 = []byte{ - // 642 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xdc, 0x55, 0x4d, 0x6e, 0xd3, 0x40, - 0x18, 0x8d, 0x9b, 0xfe, 0x65, 0x8a, 0x00, 0x99, 0x80, 0xd2, 0x08, 0xdc, 0x2a, 0x82, 0xd2, 0x4d, - 0xed, 0xb6, 0x20, 0x04, 0x0b, 0x04, 0x24, 0xd9, 0x54, 0x22, 0x52, 0xe5, 0x22, 0x21, 0xb1, 0xa9, - 0xc6, 0x9e, 0x91, 0x3b, 0x6a, 0xe2, 0x19, 0x66, 0xa6, 0x4d, 0x73, 0x0b, 0x6e, 0xc0, 0x06, 0x89, - 0x0b, 0x70, 0x88, 0x2e, 0x2b, 0x56, 0xac, 0x02, 0x4a, 0x56, 0x9c, 0x80, 0x2d, 0xb2, 0xc7, 0x1e, - 0x47, 0xa9, 0x13, 0x02, 0x88, 0x0d, 0x3b, 0x7b, 0xde, 0xf7, 0x3d, 0xbd, 0xf7, 0xfc, 0xcd, 0x67, - 0xb0, 0x7a, 0x0c, 0x4f, 0xa1, 0xe3, 0x23, 0xe6, 0x9c, 0xee, 0x78, 0x58, 0xc2, 0x1d, 0x47, 0x9e, - 0xd9, 0x8c, 0x53, 0x49, 0xcd, 0xeb, 0x11, 0x64, 0xfb, 0x88, 0xd9, 0x09, 0x54, 0xb5, 0x7c, 0x2a, - 0x3a, 0x54, 0x38, 0x1e, 0x14, 0x58, 0xd7, 0xfb, 0x94, 0x84, 0xaa, 0xa3, 0xba, 0xaa, 0xf0, 0xc3, - 0xf8, 0xcd, 0x51, 0x2f, 0x09, 0x54, 0x0e, 0x68, 0x40, 0xd5, 0x79, 0xf4, 0xa4, 0x4e, 0x6b, 0xdf, - 0x0d, 0x70, 0xa5, 0x25, 0x82, 0x06, 0xc7, 0x50, 0xe2, 0x46, 0x73, 0xdf, 0xdc, 0x06, 0x8b, 0x02, - 0x87, 0x08, 0xf3, 0x8a, 0xb1, 0x6e, 0x6c, 0x96, 0xea, 0x95, 0xcf, 0x9f, 0xb6, 0xca, 0x09, 0xd1, - 0x0b, 0x84, 0x38, 0x16, 0xe2, 0x40, 0x72, 0x12, 0x06, 0x6e, 0x52, 0x67, 0x3e, 0x03, 0xc0, 0xa7, - 0xed, 0x36, 0x94, 0x98, 0xc3, 0x76, 0x65, 0x6e, 0xdd, 0xd8, 0x5c, 0xd9, 0x5d, 0xb5, 0x93, 0x96, - 0x48, 0x68, 0xaa, 0xde, 0x6e, 0x50, 0x12, 0xd6, 0xe7, 0xcf, 0xfb, 0x6b, 0x05, 0x77, 0xa4, 0xc5, - 0x7c, 0x0a, 0x4a, 0x8c, 0x93, 0xd0, 0x27, 0x0c, 0xb6, 0x2b, 0xc5, 0xd9, 0xfa, 0xb3, 0x0e, 0xf3, - 0x3e, 0xb8, 0x96, 0x91, 0x1d, 0xca, 0x1e, 0xc3, 0x95, 0xf9, 0x48, 0xba, 0x7b, 0x35, 0x3b, 0x7e, - 0xd5, 0x63, 0xb8, 0xf6, 0x18, 0x94, 0x47, 0xad, 0xba, 0x58, 0x30, 0x1a, 0x0a, 0x6c, 0xae, 0x83, - 0x45, 0x1f, 0xb1, 0x43, 0x82, 0x62, 0xcb, 0xf3, 0xf5, 0xd2, 0xa0, 0xbf, 0xb6, 0xd0, 0x40, 0x6c, - 0xaf, 0xe9, 0x2e, 0xf8, 0x88, 0xed, 0xa1, 0x5a, 0xdf, 0x00, 0xa0, 0x25, 0x82, 0x26, 0x66, 0x54, - 0x10, 0x69, 0x3e, 0x02, 0x25, 0xa4, 0x1e, 0xe9, 0xaf, 0x63, 0xca, 0x4a, 0x4d, 0x1b, 0x2c, 0xd0, - 0x6e, 0x88, 0x79, 0x1c, 0xd2, 0xb4, 0x1e, 0x55, 0x36, 0x96, 0x6c, 0xf1, 0xf7, 0x93, 0x9d, 0x39, - 0x9a, 0x32, 0x30, 0x33, 0x7f, 0x69, 0x30, 0xb5, 0xaf, 0x06, 0x58, 0x69, 0x89, 0xe0, 0x35, 0x91, - 0x47, 0x88, 0xc3, 0xee, 0x7f, 0xe8, 0xfb, 0x26, 0xb8, 0x31, 0x62, 0x50, 0x1b, 0xff, 0xa8, 0x8c, - 0x37, 0x39, 0xec, 0x36, 0xb1, 0x27, 0xff, 0xe0, 0x52, 0xe4, 0x28, 0x98, 0xcb, 0x53, 0xf0, 0x97, - 0xc3, 0x9f, 0x18, 0x48, 0x85, 0x6a, 0x03, 0x1f, 0xd4, 0xb5, 0x76, 0x31, 0x83, 0xbd, 0x7f, 0xed, - 0xe0, 0x09, 0x58, 0x62, 0xb0, 0xd7, 0xc1, 0xa1, 0x9c, 0x55, 0x7f, 0x5a, 0x5f, 0xbb, 0x15, 0xdf, - 0x48, 0xad, 0x52, 0xcb, 0x7f, 0xaf, 0xe4, 0xbf, 0x24, 0x6f, 0x4f, 0x08, 0x82, 0x12, 0x47, 0xf2, - 0x8f, 0x31, 0x66, 0xb3, 0xc8, 0x57, 0x75, 0xe6, 0x43, 0xb0, 0xec, 0x51, 0xce, 0x69, 0x77, 0x86, - 0xb1, 0xd3, 0x95, 0x79, 0xa6, 0x8b, 0xb9, 0x83, 0xa3, 0x94, 0x6b, 0x81, 0xa9, 0xf2, 0xdd, 0x1f, - 0x45, 0x50, 0x6c, 0x89, 0xc0, 0x3c, 0x00, 0xa5, 0x6c, 0xa7, 0x5a, 0xf6, 0xf8, 0x22, 0xb7, 0x47, - 0x17, 0x51, 0x75, 0x63, 0x3a, 0xae, 0x17, 0x55, 0x0b, 0x2c, 0xa5, 0x2b, 0xe8, 0x76, 0x6e, 0x4b, - 0x82, 0x56, 0xef, 0x4e, 0x43, 0x35, 0xdd, 0x3e, 0x58, 0xd6, 0x57, 0xfb, 0x4e, 0x6e, 0x47, 0x0a, - 0x57, 0xef, 0x4d, 0x85, 0x47, 0x19, 0xf5, 0x9d, 0xc9, 0x67, 0x4c, 0xe1, 0x09, 0x8c, 0xe3, 0x83, - 0x1c, 0xe5, 0x98, 0x0d, 0x71, 0x7e, 0x8e, 0x1a, 0x9f, 0x90, 0xe3, 0xa5, 0xf1, 0x8a, 0x48, 0xb3, - 0xd1, 0xca, 0x27, 0xd5, 0xf8, 0x04, 0xd2, 0x4b, 0x5f, 0xbe, 0xfe, 0xfc, 0x7c, 0x60, 0x19, 0x17, - 0x03, 0xcb, 0xf8, 0x36, 0xb0, 0x8c, 0x77, 0x43, 0xab, 0x70, 0x31, 0xb4, 0x0a, 0x5f, 0x86, 0x56, - 0xe1, 0xcd, 0x46, 0x40, 0xe4, 0xd1, 0x89, 0x67, 0xfb, 0xb4, 0xe3, 0x6c, 0x07, 0x6d, 0xe8, 0x09, - 0x67, 0x3b, 0xd8, 0xf2, 0x8f, 0x20, 0x09, 0x9d, 0xb3, 0xf8, 0xcf, 0x1f, 0x0d, 0x9a, 0xf0, 0x16, - 0xe3, 0x5f, 0xf2, 0x83, 0x9f, 0x01, 0x00, 0x00, 0xff, 0xff, 0xae, 0x1f, 0xa2, 0x1e, 0x12, 0x08, - 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - // CreateCDP defines a method to create a new CDP. - CreateCDP(ctx context.Context, in *MsgCreateCDP, opts ...grpc.CallOption) (*MsgCreateCDPResponse, error) - // Deposit defines a method to deposit to a CDP. - Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) - // Withdraw defines a method to withdraw collateral from a CDP. - Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) - // DrawDebt defines a method to draw debt from a CDP. - DrawDebt(ctx context.Context, in *MsgDrawDebt, opts ...grpc.CallOption) (*MsgDrawDebtResponse, error) - // RepayDebt defines a method to repay debt from a CDP. - RepayDebt(ctx context.Context, in *MsgRepayDebt, opts ...grpc.CallOption) (*MsgRepayDebtResponse, error) - // Liquidate defines a method to attempt to liquidate a CDP whos - // collateralization ratio is under its liquidation ratio. - Liquidate(ctx context.Context, in *MsgLiquidate, opts ...grpc.CallOption) (*MsgLiquidateResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) CreateCDP(ctx context.Context, in *MsgCreateCDP, opts ...grpc.CallOption) (*MsgCreateCDPResponse, error) { - out := new(MsgCreateCDPResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Msg/CreateCDP", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) { - out := new(MsgDepositResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Msg/Deposit", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) { - out := new(MsgWithdrawResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Msg/Withdraw", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) DrawDebt(ctx context.Context, in *MsgDrawDebt, opts ...grpc.CallOption) (*MsgDrawDebtResponse, error) { - out := new(MsgDrawDebtResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Msg/DrawDebt", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) RepayDebt(ctx context.Context, in *MsgRepayDebt, opts ...grpc.CallOption) (*MsgRepayDebtResponse, error) { - out := new(MsgRepayDebtResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Msg/RepayDebt", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Liquidate(ctx context.Context, in *MsgLiquidate, opts ...grpc.CallOption) (*MsgLiquidateResponse, error) { - out := new(MsgLiquidateResponse) - err := c.cc.Invoke(ctx, "/kava.cdp.v1beta1.Msg/Liquidate", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // CreateCDP defines a method to create a new CDP. - CreateCDP(context.Context, *MsgCreateCDP) (*MsgCreateCDPResponse, error) - // Deposit defines a method to deposit to a CDP. - Deposit(context.Context, *MsgDeposit) (*MsgDepositResponse, error) - // Withdraw defines a method to withdraw collateral from a CDP. - Withdraw(context.Context, *MsgWithdraw) (*MsgWithdrawResponse, error) - // DrawDebt defines a method to draw debt from a CDP. - DrawDebt(context.Context, *MsgDrawDebt) (*MsgDrawDebtResponse, error) - // RepayDebt defines a method to repay debt from a CDP. - RepayDebt(context.Context, *MsgRepayDebt) (*MsgRepayDebtResponse, error) - // Liquidate defines a method to attempt to liquidate a CDP whos - // collateralization ratio is under its liquidation ratio. - Liquidate(context.Context, *MsgLiquidate) (*MsgLiquidateResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) CreateCDP(ctx context.Context, req *MsgCreateCDP) (*MsgCreateCDPResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method CreateCDP not implemented") -} -func (*UnimplementedMsgServer) Deposit(ctx context.Context, req *MsgDeposit) (*MsgDepositResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposit not implemented") -} -func (*UnimplementedMsgServer) Withdraw(ctx context.Context, req *MsgWithdraw) (*MsgWithdrawResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Withdraw not implemented") -} -func (*UnimplementedMsgServer) DrawDebt(ctx context.Context, req *MsgDrawDebt) (*MsgDrawDebtResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method DrawDebt not implemented") -} -func (*UnimplementedMsgServer) RepayDebt(ctx context.Context, req *MsgRepayDebt) (*MsgRepayDebtResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method RepayDebt not implemented") -} -func (*UnimplementedMsgServer) Liquidate(ctx context.Context, req *MsgLiquidate) (*MsgLiquidateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Liquidate not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_CreateCDP_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgCreateCDP) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).CreateCDP(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Msg/CreateCDP", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).CreateCDP(ctx, req.(*MsgCreateCDP)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Deposit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgDeposit) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Deposit(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Msg/Deposit", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Deposit(ctx, req.(*MsgDeposit)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Withdraw_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgWithdraw) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Withdraw(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Msg/Withdraw", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Withdraw(ctx, req.(*MsgWithdraw)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_DrawDebt_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgDrawDebt) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).DrawDebt(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Msg/DrawDebt", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).DrawDebt(ctx, req.(*MsgDrawDebt)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_RepayDebt_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgRepayDebt) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).RepayDebt(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Msg/RepayDebt", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).RepayDebt(ctx, req.(*MsgRepayDebt)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Liquidate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgLiquidate) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Liquidate(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.cdp.v1beta1.Msg/Liquidate", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Liquidate(ctx, req.(*MsgLiquidate)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.cdp.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "CreateCDP", - Handler: _Msg_CreateCDP_Handler, - }, - { - MethodName: "Deposit", - Handler: _Msg_Deposit_Handler, - }, - { - MethodName: "Withdraw", - Handler: _Msg_Withdraw_Handler, - }, - { - MethodName: "DrawDebt", - Handler: _Msg_DrawDebt_Handler, - }, - { - MethodName: "RepayDebt", - Handler: _Msg_RepayDebt_Handler, - }, - { - MethodName: "Liquidate", - Handler: _Msg_Liquidate_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/cdp/v1beta1/tx.proto", -} - -func (m *MsgCreateCDP) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgCreateCDP) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgCreateCDP) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintTx(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x22 - } - { - size, err := m.Principal.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.Collateral.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgCreateCDPResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgCreateCDPResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgCreateCDPResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.CdpID != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.CdpID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *MsgDeposit) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgDeposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDeposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintTx(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x22 - } - { - size, err := m.Collateral.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintTx(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgDepositResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgDepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgWithdraw) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgWithdraw) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdraw) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintTx(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x22 - } - { - size, err := m.Collateral.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintTx(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgWithdrawResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgDrawDebt) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgDrawDebt) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDrawDebt) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Principal.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintTx(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgDrawDebtResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgDrawDebtResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDrawDebtResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgRepayDebt) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgRepayDebt) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgRepayDebt) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Payment.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintTx(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgRepayDebtResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgRepayDebtResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgRepayDebtResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgLiquidate) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgLiquidate) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgLiquidate) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintTx(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x1a - } - if len(m.Borrower) > 0 { - i -= len(m.Borrower) - copy(dAtA[i:], m.Borrower) - i = encodeVarintTx(dAtA, i, uint64(len(m.Borrower))) - i-- - dAtA[i] = 0x12 - } - if len(m.Keeper) > 0 { - i -= len(m.Keeper) - copy(dAtA[i:], m.Keeper) - i = encodeVarintTx(dAtA, i, uint64(len(m.Keeper))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgLiquidateResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgLiquidateResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgLiquidateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgCreateCDP) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Collateral.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.Principal.Size() - n += 1 + l + sovTx(uint64(l)) - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgCreateCDPResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CdpID != 0 { - n += 1 + sovTx(uint64(m.CdpID)) - } - return n -} - -func (m *MsgDeposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Collateral.Size() - n += 1 + l + sovTx(uint64(l)) - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgDepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgWithdraw) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Collateral.Size() - n += 1 + l + sovTx(uint64(l)) - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgWithdrawResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgDrawDebt) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Principal.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgDrawDebtResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgRepayDebt) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Payment.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgRepayDebtResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgLiquidate) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Keeper) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Borrower) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgLiquidateResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgCreateCDP) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgCreateCDP: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgCreateCDP: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Collateral", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Collateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Principal", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Principal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgCreateCDPResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgCreateCDPResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgCreateCDPResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CdpID", wireType) - } - m.CdpID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CdpID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDeposit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDeposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDeposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Collateral", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Collateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDepositResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdraw) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdraw: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdraw: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Collateral", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Collateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDrawDebt) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDrawDebt: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDrawDebt: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Principal", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Principal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDrawDebtResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDrawDebtResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDrawDebtResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgRepayDebt) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgRepayDebt: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgRepayDebt: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Payment", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Payment.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgRepayDebtResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgRepayDebtResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgRepayDebtResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgLiquidate) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgLiquidate: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgLiquidate: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Keeper", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Keeper = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Borrower", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Borrower = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgLiquidateResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgLiquidateResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgLiquidateResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/cdp/types/utils.go b/x/cdp/types/utils.go deleted file mode 100644 index 518fc0fd..00000000 --- a/x/cdp/types/utils.go +++ /dev/null @@ -1,100 +0,0 @@ -package types - -import ( - "bytes" - "fmt" - "strings" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// MaxSortableDec largest sortable sdk.Dec -var MaxSortableDec = sdk.OneDec().Quo(sdk.SmallestDec()) - -// ValidSortableDec sdk.Dec can't have precision of less than 10^-18 -func ValidSortableDec(dec sdk.Dec) bool { - return dec.Abs().LTE(MaxSortableDec) -} - -// SortableDecBytes returns a byte slice representation of a Dec that can be sorted. -// Left and right pads with 0s so there are 18 digits to left and right of the decimal point. -// For this reason, there is a maximum and minimum value for this, enforced by ValidSortableDec. -func SortableDecBytes(dec sdk.Dec) []byte { - if !ValidSortableDec(dec) { - panic("dec must be within bounds") - } - // Instead of adding an extra byte to all sortable decs in order to handle max sortable, we just - // makes its bytes be "max" which comes after all numbers in ASCIIbetical order - if dec.Equal(MaxSortableDec) { - return []byte("max") - } - // For the same reason, we make the bytes of minimum sortable dec be --, which comes before all numbers. - if dec.Equal(MaxSortableDec.Neg()) { - return []byte("--") - } - // We move the negative sign to the front of all the left padded 0s, to make negative numbers come before positive numbers - if dec.IsNegative() { - return append([]byte("-"), []byte(fmt.Sprintf(fmt.Sprintf("%%0%ds", sdk.Precision*2+1), dec.Abs().String()))...) - } - return []byte(fmt.Sprintf(fmt.Sprintf("%%0%ds", sdk.Precision*2+1), dec.String())) -} - -// ParseDecBytes parses a []byte encoded using SortableDecBytes back to sdk.Dec -func ParseDecBytes(db []byte) (sdk.Dec, error) { - strFromDecBytes := strings.Trim(string(db[:]), "0") - if string(strFromDecBytes[0]) == "." { - strFromDecBytes = "0" + strFromDecBytes - } - if string(strFromDecBytes[len(strFromDecBytes)-1]) == "." { - strFromDecBytes = strFromDecBytes + "0" - } - if bytes.Equal(db, []byte("max")) { - return MaxSortableDec, nil - } - if bytes.Equal(db, []byte("--")) { - return MaxSortableDec.Neg(), nil - } - dec, err := sdk.NewDecFromStr(strFromDecBytes) - if err != nil { - return sdk.Dec{}, err - } - return dec, nil -} - -// 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 sdkmath.Int, n sdkmath.Int, b sdkmath.Int) (z sdkmath.Int) { - if x.IsZero() { - if n.IsZero() { - z = b // 0^0 = 1 - return - } - z = sdk.ZeroInt() // otherwise 0^a = 0 - return - } - - z = x - if n.Mod(sdkmath.NewInt(2)).Equal(sdk.ZeroInt()) { - z = b - } - - halfOfB := b.Quo(sdkmath.NewInt(2)) - n = n.Quo(sdkmath.NewInt(2)) - - for n.GT(sdk.ZeroInt()) { - xSquared := x.Mul(x) - xSquaredRounded := xSquared.Add(halfOfB) - - x = xSquaredRounded.Quo(b) - - if n.Mod(sdkmath.NewInt(2)).Equal(sdk.OneInt()) { - zx := z.Mul(x) - zxRounded := zx.Add(halfOfB) - z = zxRounded.Quo(b) - } - n = n.Quo(sdkmath.NewInt(2)) - } - return -} diff --git a/x/cdp/types/utils_test.go b/x/cdp/types/utils_test.go deleted file mode 100644 index 88856df1..00000000 --- a/x/cdp/types/utils_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package types - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestSortableDecBytes(t *testing.T) { - tests := []struct { - d sdk.Dec - want []byte - }{ - {sdk.NewDec(0), []byte("000000000000000000.000000000000000000")}, - {sdk.NewDec(1), []byte("000000000000000001.000000000000000000")}, - {sdk.MustNewDecFromStr("2.0"), []byte("000000000000000002.000000000000000000")}, - {sdk.MustNewDecFromStr("-2.0"), []byte("-000000000000000002.000000000000000000")}, - {sdk.NewDec(10), []byte("000000000000000010.000000000000000000")}, - {sdk.NewDec(12340), []byte("000000000000012340.000000000000000000")}, - {sdk.NewDecWithPrec(12340, 4), []byte("000000000000000001.234000000000000000")}, - {sdk.NewDecWithPrec(12340, 5), []byte("000000000000000000.123400000000000000")}, - {sdk.NewDecWithPrec(12340, 8), []byte("000000000000000000.000123400000000000")}, - {sdk.NewDecWithPrec(1009009009009009009, 17), []byte("000000000000000010.090090090090090090")}, - {sdk.NewDecWithPrec(-1009009009009009009, 17), []byte("-000000000000000010.090090090090090090")}, - {sdk.NewDec(1000000000000000000), []byte("max")}, - {sdk.NewDec(-1000000000000000000), []byte("--")}, - } - for tcIndex, tc := range tests { - assert.Equal(t, tc.want, SortableDecBytes(tc.d), "bad String(), index: %v", tcIndex) - } - - assert.Panics(t, func() { SortableDecBytes(sdk.NewDec(1000000000000000001)) }) - assert.Panics(t, func() { SortableDecBytes(sdk.NewDec(-1000000000000000001)) }) -} - -func TestParseSortableDecBytes(t *testing.T) { - tests := []struct { - d sdk.Dec - want []byte - }{ - {sdk.NewDec(0), []byte("000000000000000000.000000000000000000")}, - {sdk.NewDec(1), []byte("000000000000000001.000000000000000000")}, - {sdk.MustNewDecFromStr("2.0"), []byte("000000000000000002.000000000000000000")}, - {sdk.MustNewDecFromStr("-2.0"), []byte("-000000000000000002.000000000000000000")}, - {sdk.NewDec(10), []byte("000000000000000010.000000000000000000")}, - {sdk.NewDec(12340), []byte("000000000000012340.000000000000000000")}, - {sdk.NewDecWithPrec(12340, 4), []byte("000000000000000001.234000000000000000")}, - {sdk.NewDecWithPrec(12340, 5), []byte("000000000000000000.123400000000000000")}, - {sdk.NewDecWithPrec(12340, 8), []byte("000000000000000000.000123400000000000")}, - {sdk.NewDecWithPrec(1009009009009009009, 17), []byte("000000000000000010.090090090090090090")}, - {sdk.NewDecWithPrec(-1009009009009009009, 17), []byte("-000000000000000010.090090090090090090")}, - {sdk.NewDec(1000000000000000000), []byte("max")}, - {sdk.NewDec(-1000000000000000000), []byte("--")}, - } - for tcIndex, tc := range tests { - b := SortableDecBytes(tc.d) - r, err := ParseDecBytes(b) - assert.NoError(t, err) - assert.Equal(t, tc.d, r, "bad Dec(), index: %v", tcIndex) - } -} - -func TestRelativePow(t *testing.T) { - tests := []struct { - args []sdkmath.Int - want sdkmath.Int - }{ - {[]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]) - require.Equal(t, tc.want, res, "unexpected result for test case %d, input: %v, got: %v", i, tc.args, res) - } -} diff --git a/x/committee/keeper/msg_server_test.go b/x/committee/keeper/msg_server_test.go index f2128131..779c46a8 100644 --- a/x/committee/keeper/msg_server_test.go +++ b/x/committee/keeper/msg_server_test.go @@ -9,13 +9,11 @@ import ( sdkmath "cosmossdk.io/math" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" 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" "github.com/0glabs/0g-chain/app" "github.com/0glabs/0g-chain/x/committee/keeper" "github.com/0glabs/0g-chain/x/committee/types" - swaptypes "github.com/0glabs/0g-chain/x/swap/types" ) //NewDistributionGenesisWithPool creates a default distribution genesis state with some coins in the community pool. @@ -72,54 +70,54 @@ func (suite *MsgServerTestSuite) SetupTest() { suite.ctx = suite.app.NewContext(true, tmproto.Header{Height: 1, Time: firstBlockTime}) } -func (suite *MsgServerTestSuite) TestSubmitProposalMsg_Valid() { - msg, err := types.NewMsgSubmitProposal( - proposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []proposal.ParamChange{{ - Subspace: swaptypes.ModuleName, - Key: string(swaptypes.KeySwapFee), - Value: "\"0.001500000000000000\"", - }}, - ), - suite.addresses[0], - 1, - ) - suite.Require().NoError(err) +// func (suite *MsgServerTestSuite) TestSubmitProposalMsg_Valid() { +// msg, err := types.NewMsgSubmitProposal( +// proposal.NewParameterChangeProposal( +// "A Title", +// "A description of this proposal.", +// []proposal.ParamChange{{ +// Subspace: swaptypes.ModuleName, +// Key: string(swaptypes.KeySwapFee), +// Value: "\"0.001500000000000000\"", +// }}, +// ), +// suite.addresses[0], +// 1, +// ) +// suite.Require().NoError(err) - res, err := suite.msgServer.SubmitProposal(sdk.WrapSDKContext(suite.ctx), msg) +// res, err := suite.msgServer.SubmitProposal(sdk.WrapSDKContext(suite.ctx), msg) - suite.NoError(err) - _, found := suite.keeper.GetProposal(suite.ctx, res.ProposalID) - suite.True(found) -} +// suite.NoError(err) +// _, found := suite.keeper.GetProposal(suite.ctx, res.ProposalID) +// suite.True(found) +// } -func (suite *MsgServerTestSuite) TestSubmitProposalMsg_Invalid() { - var committeeID uint64 = 1 - msg, err := types.NewMsgSubmitProposal( - proposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []proposal.ParamChange{{ - Subspace: swaptypes.ModuleName, - Key: "nonsense-key", - Value: "nonsense-value", - }}, - ), - suite.addresses[0], - committeeID, - ) - suite.Require().NoError(err) +// func (suite *MsgServerTestSuite) TestSubmitProposalMsg_Invalid() { +// var committeeID uint64 = 1 +// msg, err := types.NewMsgSubmitProposal( +// proposal.NewParameterChangeProposal( +// "A Title", +// "A description of this proposal.", +// []proposal.ParamChange{{ +// Subspace: swaptypes.ModuleName, +// Key: "nonsense-key", +// Value: "nonsense-value", +// }}, +// ), +// suite.addresses[0], +// committeeID, +// ) +// suite.Require().NoError(err) - _, err = suite.msgServer.SubmitProposal(sdk.WrapSDKContext(suite.ctx), msg) +// _, err = suite.msgServer.SubmitProposal(sdk.WrapSDKContext(suite.ctx), msg) - suite.Error(err) - suite.Empty( - suite.keeper.GetProposalsByCommittee(suite.ctx, committeeID), - "proposal found when none should exist", - ) -} +// suite.Error(err) +// suite.Empty( +// suite.keeper.GetProposalsByCommittee(suite.ctx, committeeID), +// "proposal found when none should exist", +// ) +// } func (suite *MsgServerTestSuite) TestSubmitProposalMsg_ValidUpgrade() { msg, err := types.NewMsgSubmitProposal( @@ -163,32 +161,32 @@ func (suite *MsgServerTestSuite) TestSubmitProposalMsg_Unregistered() { ) } -func (suite *MsgServerTestSuite) TestSubmitProposalMsgAndVote() { - msg, err := types.NewMsgSubmitProposal( - proposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []proposal.ParamChange{{ - Subspace: swaptypes.ModuleName, - Key: string(swaptypes.KeySwapFee), - Value: "\"0.001500000000000000\"", - }}, - ), - suite.addresses[0], - 1, - ) - suite.Require().NoError(err) +// func (suite *MsgServerTestSuite) TestSubmitProposalMsgAndVote() { +// msg, err := types.NewMsgSubmitProposal( +// proposal.NewParameterChangeProposal( +// "A Title", +// "A description of this proposal.", +// []proposal.ParamChange{{ +// Subspace: swaptypes.ModuleName, +// Key: string(swaptypes.KeySwapFee), +// Value: "\"0.001500000000000000\"", +// }}, +// ), +// suite.addresses[0], +// 1, +// ) +// suite.Require().NoError(err) - res, err := suite.msgServer.SubmitProposal(sdk.WrapSDKContext(suite.ctx), msg) - suite.Require().NoError(err) +// res, err := suite.msgServer.SubmitProposal(sdk.WrapSDKContext(suite.ctx), msg) +// suite.Require().NoError(err) - proposal, found := suite.keeper.GetProposal(suite.ctx, res.ProposalID) - suite.Require().True(found) +// proposal, found := suite.keeper.GetProposal(suite.ctx, res.ProposalID) +// suite.Require().True(found) - msgVote := types.NewMsgVote(suite.addresses[0], proposal.ID, types.VOTE_TYPE_YES) - _, err = suite.msgServer.Vote(sdk.WrapSDKContext(suite.ctx), msgVote) - suite.Require().NoError(err) -} +// msgVote := types.NewMsgVote(suite.addresses[0], proposal.ID, types.VOTE_TYPE_YES) +// _, err = suite.msgServer.Vote(sdk.WrapSDKContext(suite.ctx), msgVote) +// suite.Require().NoError(err) +// } func TestMsgServerTestSuite(t *testing.T) { suite.Run(t, new(MsgServerTestSuite)) diff --git a/x/committee/types/codec.go b/x/committee/types/codec.go index aa5c76b4..17cd4bfe 100644 --- a/x/committee/types/codec.go +++ b/x/committee/types/codec.go @@ -1,8 +1,6 @@ package types import ( - communitytypes "github.com/0glabs/0g-chain/x/community/types" - kavadisttypes "github.com/0glabs/0g-chain/x/kavadist/types" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" "github.com/cosmos/cosmos-sdk/codec/types" @@ -49,10 +47,10 @@ func init() { RegisterProposalTypeCodec(govv1beta1.TextProposal{}, "cosmos-sdk/TextProposal") RegisterProposalTypeCodec(upgradetypes.SoftwareUpgradeProposal{}, "cosmos-sdk/SoftwareUpgradeProposal") RegisterProposalTypeCodec(upgradetypes.CancelSoftwareUpgradeProposal{}, "cosmos-sdk/CancelSoftwareUpgradeProposal") - RegisterProposalTypeCodec(communitytypes.CommunityCDPRepayDebtProposal{}, "kava/CommunityCDPRepayDebtProposal") - RegisterProposalTypeCodec(communitytypes.CommunityCDPWithdrawCollateralProposal{}, "kava/CommunityCDPWithdrawCollateralProposal") - RegisterProposalTypeCodec(communitytypes.CommunityPoolLendWithdrawProposal{}, "kava/CommunityPoolLendWithdrawProposal") - RegisterProposalTypeCodec(kavadisttypes.CommunityPoolMultiSpendProposal{}, "kava/CommunityPoolMultiSpendProposal") + // RegisterProposalTypeCodec(communitytypes.CommunityCDPRepayDebtProposal{}, "kava/CommunityCDPRepayDebtProposal") + // RegisterProposalTypeCodec(communitytypes.CommunityCDPWithdrawCollateralProposal{}, "kava/CommunityCDPWithdrawCollateralProposal") + // RegisterProposalTypeCodec(communitytypes.CommunityPoolLendWithdrawProposal{}, "kava/CommunityPoolLendWithdrawProposal") + // RegisterProposalTypeCodec(kavadisttypes.CommunityPoolMultiSpendProposal{}, "kava/CommunityPoolMultiSpendProposal") } // RegisterLegacyAminoCodec registers all the necessary types and interfaces for the module. @@ -125,13 +123,13 @@ func RegisterInterfaces(registry types.InterfaceRegistry) { &Proposal{}, &distrtypes.CommunityPoolSpendProposal{}, &govv1beta1.TextProposal{}, - &kavadisttypes.CommunityPoolMultiSpendProposal{}, + // &kavadisttypes.CommunityPoolMultiSpendProposal{}, &proposaltypes.ParameterChangeProposal{}, &upgradetypes.SoftwareUpgradeProposal{}, &upgradetypes.CancelSoftwareUpgradeProposal{}, - &communitytypes.CommunityCDPRepayDebtProposal{}, - &communitytypes.CommunityCDPWithdrawCollateralProposal{}, - &communitytypes.CommunityPoolLendWithdrawProposal{}, + // &communitytypes.CommunityCDPRepayDebtProposal{}, + // &communitytypes.CommunityCDPWithdrawCollateralProposal{}, + // &communitytypes.CommunityPoolLendWithdrawProposal{}, ) registry.RegisterImplementations( diff --git a/x/committee/types/param_permissions_test.go b/x/committee/types/param_permissions_test.go index 7913f5b0..552c40a7 100644 --- a/x/committee/types/param_permissions_test.go +++ b/x/committee/types/param_permissions_test.go @@ -4,7 +4,6 @@ import ( fmt "fmt" "testing" - sdkmath "cosmossdk.io/math" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" tmtime "github.com/cometbft/cometbft/types/time" sdk "github.com/cosmos/cosmos-sdk/types" @@ -13,7 +12,6 @@ import ( "github.com/stretchr/testify/suite" "github.com/0glabs/0g-chain/app" - cdptypes "github.com/0glabs/0g-chain/x/cdp/types" types "github.com/0glabs/0g-chain/x/committee/types" pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" ) @@ -24,8 +22,8 @@ type ParamsChangeTestSuite struct { ctx sdk.Context pk types.ParamKeeper - cdpCollateralParams cdptypes.CollateralParams - cdpDebtParam cdptypes.DebtParam + // cdpCollateralParams cdptypes.CollateralParams + // cdpDebtParam cdptypes.DebtParam cdpCollateralRequirements []types.SubparamRequirement } @@ -36,42 +34,42 @@ func (suite *ParamsChangeTestSuite) SetupTest() { suite.ctx = ctx suite.pk = tApp.GetParamsKeeper() - suite.cdpDebtParam = cdptypes.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdkmath.NewInt(6), - DebtFloor: sdkmath.NewInt(1000), - } + // suite.cdpDebtParam = cdptypes.DebtParam{ + // Denom: "usdx", + // ReferenceAsset: "usd", + // ConversionFactor: sdkmath.NewInt(6), + // DebtFloor: sdkmath.NewInt(1000), + // } - suite.cdpCollateralParams = cdptypes.CollateralParams{ - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("2.0"), - DebtLimit: sdk.NewCoin("usdx", sdkmath.NewInt(100)), - StabilityFee: sdk.MustNewDecFromStr("1.02"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdkmath.NewInt(100), - ConversionFactor: sdkmath.NewInt(6), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - CheckCollateralizationIndexCount: sdkmath.NewInt(0), - }, - { - Denom: "btc", - Type: "btc-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewCoin("usdx", sdkmath.NewInt(100)), - StabilityFee: sdk.MustNewDecFromStr("1.01"), - LiquidationPenalty: sdk.MustNewDecFromStr("0.10"), - AuctionSize: sdkmath.NewInt(1000), - ConversionFactor: sdkmath.NewInt(8), - SpotMarketID: "btc:usd", - LiquidationMarketID: "btc:usd", - CheckCollateralizationIndexCount: sdkmath.NewInt(1), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.12"), - }, - } + // suite.cdpCollateralParams = cdptypes.CollateralParams{ + // { + // Denom: "bnb", + // Type: "bnb-a", + // LiquidationRatio: sdk.MustNewDecFromStr("2.0"), + // DebtLimit: sdk.NewCoin("usdx", sdkmath.NewInt(100)), + // StabilityFee: sdk.MustNewDecFromStr("1.02"), + // LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), + // AuctionSize: sdkmath.NewInt(100), + // ConversionFactor: sdkmath.NewInt(6), + // SpotMarketID: "bnb:usd", + // LiquidationMarketID: "bnb:usd", + // CheckCollateralizationIndexCount: sdkmath.NewInt(0), + // }, + // { + // Denom: "btc", + // Type: "btc-a", + // LiquidationRatio: sdk.MustNewDecFromStr("1.5"), + // DebtLimit: sdk.NewCoin("usdx", sdkmath.NewInt(100)), + // StabilityFee: sdk.MustNewDecFromStr("1.01"), + // LiquidationPenalty: sdk.MustNewDecFromStr("0.10"), + // AuctionSize: sdkmath.NewInt(1000), + // ConversionFactor: sdkmath.NewInt(8), + // SpotMarketID: "btc:usd", + // LiquidationMarketID: "btc:usd", + // CheckCollateralizationIndexCount: sdkmath.NewInt(1), + // KeeperRewardPercentage: sdk.MustNewDecFromStr("0.12"), + // }, + // } suite.cdpCollateralRequirements = []types.SubparamRequirement{ { Key: "type", @@ -86,587 +84,587 @@ func (suite *ParamsChangeTestSuite) SetupTest() { } } -func (s *ParamsChangeTestSuite) TestSingleSubparams_CdpDeptParams() { - testcases := []struct { - name string - expected bool - permission types.AllowedParamsChange - paramChange paramsproposal.ParamChange - }{ - { - name: "allow changes to all allowed fields", - expected: true, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"denom", "reference_asset", "conversion_factor", "debt_floor"}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "DebtParam", - Value: `{ - "denom": "bnb", - "reference_asset": "bnbx", - "conversion_factor": "11", - "debt_floor": "1200" - }`, - }, - }, - { - name: "allows changes only to certain fields", - expected: true, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"denom", "debt_floor"}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "DebtParam", - Value: `{ - "denom": "bnb", - "reference_asset": "usd", - "conversion_factor": "6", - "debt_floor": "1100" - }`, - }, - }, - { - name: "fails if changing attr that is not allowed", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"denom", "debt_floor"}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "DebtParam", - Value: `{ - "denom": "usdx", - "reference_asset": "usd", - "conversion_factor": "7", - "debt_floor": "1000" - }`, - }, - }, - { - name: "fails if there are unexpected param change attrs", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"denom"}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "DebtParam", - Value: `{ - "denom": "usdx", - "reference_asset": "usd", - "conversion_factor": "6", - "debt_floor": "1000", - "extra_attr": "123" - }`, - }, - }, - { - name: "fails if there are missing param change attrs", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"denom", "reference_asset"}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "DebtParam", - // debt_floor is missing - Value: `{ - "denom": "usdx", - "reference_asset": "usd", - "conversion_factor": "11.000000000000000000", - }`, - }, - }, - { - name: "fails if subspace does not match", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"denom"}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "auction", - Key: "DebtParam", - Value: `{ - "denom": "usdx", - "reference_asset": "usd", - "conversion_factor": "6", - "debt_floor": "1000" - }`, - }, - }, - } +// func (s *ParamsChangeTestSuite) TestSingleSubparams_CdpDeptParams() { +// testcases := []struct { +// name string +// expected bool +// permission types.AllowedParamsChange +// paramChange paramsproposal.ParamChange +// }{ +// { +// name: "allow changes to all allowed fields", +// expected: true, +// permission: types.AllowedParamsChange{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyDebtParam), +// SingleSubparamAllowedAttrs: []string{"denom", "reference_asset", "conversion_factor", "debt_floor"}, +// }, +// paramChange: paramsproposal.ParamChange{ +// Subspace: "cdp", +// Key: "DebtParam", +// Value: `{ +// "denom": "bnb", +// "reference_asset": "bnbx", +// "conversion_factor": "11", +// "debt_floor": "1200" +// }`, +// }, +// }, +// { +// name: "allows changes only to certain fields", +// expected: true, +// permission: types.AllowedParamsChange{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyDebtParam), +// SingleSubparamAllowedAttrs: []string{"denom", "debt_floor"}, +// }, +// paramChange: paramsproposal.ParamChange{ +// Subspace: "cdp", +// Key: "DebtParam", +// Value: `{ +// "denom": "bnb", +// "reference_asset": "usd", +// "conversion_factor": "6", +// "debt_floor": "1100" +// }`, +// }, +// }, +// { +// name: "fails if changing attr that is not allowed", +// expected: false, +// permission: types.AllowedParamsChange{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyDebtParam), +// SingleSubparamAllowedAttrs: []string{"denom", "debt_floor"}, +// }, +// paramChange: paramsproposal.ParamChange{ +// Subspace: "cdp", +// Key: "DebtParam", +// Value: `{ +// "denom": "usdx", +// "reference_asset": "usd", +// "conversion_factor": "7", +// "debt_floor": "1000" +// }`, +// }, +// }, +// { +// name: "fails if there are unexpected param change attrs", +// expected: false, +// permission: types.AllowedParamsChange{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyDebtParam), +// SingleSubparamAllowedAttrs: []string{"denom"}, +// }, +// paramChange: paramsproposal.ParamChange{ +// Subspace: "cdp", +// Key: "DebtParam", +// Value: `{ +// "denom": "usdx", +// "reference_asset": "usd", +// "conversion_factor": "6", +// "debt_floor": "1000", +// "extra_attr": "123" +// }`, +// }, +// }, +// { +// name: "fails if there are missing param change attrs", +// expected: false, +// permission: types.AllowedParamsChange{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyDebtParam), +// SingleSubparamAllowedAttrs: []string{"denom", "reference_asset"}, +// }, +// paramChange: paramsproposal.ParamChange{ +// Subspace: "cdp", +// Key: "DebtParam", +// // debt_floor is missing +// Value: `{ +// "denom": "usdx", +// "reference_asset": "usd", +// "conversion_factor": "11.000000000000000000", +// }`, +// }, +// }, +// { +// name: "fails if subspace does not match", +// expected: false, +// permission: types.AllowedParamsChange{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyDebtParam), +// SingleSubparamAllowedAttrs: []string{"denom"}, +// }, +// paramChange: paramsproposal.ParamChange{ +// Subspace: "auction", +// Key: "DebtParam", +// Value: `{ +// "denom": "usdx", +// "reference_asset": "usd", +// "conversion_factor": "6", +// "debt_floor": "1000" +// }`, +// }, +// }, +// } - for _, tc := range testcases { - s.Run(tc.name, func() { - s.SetupTest() +// for _, tc := range testcases { +// s.Run(tc.name, func() { +// s.SetupTest() - subspace, found := s.pk.GetSubspace(cdptypes.ModuleName) - s.Require().True(found) - subspace.Set(s.ctx, cdptypes.KeyDebtParam, s.cdpDebtParam) +// subspace, found := s.pk.GetSubspace(cdptypes.ModuleName) +// s.Require().True(found) +// subspace.Set(s.ctx, cdptypes.KeyDebtParam, s.cdpDebtParam) - permission := types.ParamsChangePermission{ - AllowedParamsChanges: types.AllowedParamsChanges{tc.permission}, - } - proposal := paramsproposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []paramsproposal.ParamChange{tc.paramChange}, - ) - s.Require().Equal( - tc.expected, - permission.Allows(s.ctx, s.pk, proposal), - ) - }) - } -} +// permission := types.ParamsChangePermission{ +// AllowedParamsChanges: types.AllowedParamsChanges{tc.permission}, +// } +// proposal := paramsproposal.NewParameterChangeProposal( +// "A Title", +// "A description of this proposal.", +// []paramsproposal.ParamChange{tc.paramChange}, +// ) +// s.Require().Equal( +// tc.expected, +// permission.Allows(s.ctx, s.pk, proposal), +// ) +// }) +// } +// } -func (s *ParamsChangeTestSuite) TestMultiSubparams_CdpCollateralParams() { - unchangedBnbValue := `{ - "denom": "bnb", - "type": "bnb-a", - "liquidation_ratio": "2.000000000000000000", - "debt_limit": { "denom": "usdx", "amount": "100" }, - "stability_fee": "1.020000000000000000", - "auction_size": "100", - "liquidation_penalty": "0.050000000000000000", - "spot_market_id": "bnb:usd", - "liquidation_market_id": "bnb:usd", - "keeper_reward_percentage": "0", - "check_collateralization_index_count": "0", - "conversion_factor": "6" - }` - unchangedBtcValue := `{ - "denom": "btc", - "type": "btc-a", - "liquidation_ratio": "1.500000000000000000", - "debt_limit": { "denom": "usdx", "amount": "100" }, - "stability_fee": "1.010000000000000000", - "auction_size": "1000", - "liquidation_penalty": "0.100000000000000000", - "spot_market_id": "btc:usd", - "liquidation_market_id": "btc:usd", - "keeper_reward_percentage": "0.12", - "check_collateralization_index_count": "1", - "conversion_factor": "8" - }` +// func (s *ParamsChangeTestSuite) TestMultiSubparams_CdpCollateralParams() { +// unchangedBnbValue := `{ +// "denom": "bnb", +// "type": "bnb-a", +// "liquidation_ratio": "2.000000000000000000", +// "debt_limit": { "denom": "usdx", "amount": "100" }, +// "stability_fee": "1.020000000000000000", +// "auction_size": "100", +// "liquidation_penalty": "0.050000000000000000", +// "spot_market_id": "bnb:usd", +// "liquidation_market_id": "bnb:usd", +// "keeper_reward_percentage": "0", +// "check_collateralization_index_count": "0", +// "conversion_factor": "6" +// }` +// unchangedBtcValue := `{ +// "denom": "btc", +// "type": "btc-a", +// "liquidation_ratio": "1.500000000000000000", +// "debt_limit": { "denom": "usdx", "amount": "100" }, +// "stability_fee": "1.010000000000000000", +// "auction_size": "1000", +// "liquidation_penalty": "0.100000000000000000", +// "spot_market_id": "btc:usd", +// "liquidation_market_id": "btc:usd", +// "keeper_reward_percentage": "0.12", +// "check_collateralization_index_count": "1", +// "conversion_factor": "8" +// }` - testcases := []struct { - name string - expected bool - permission types.AllowedParamsChange - paramChange paramsproposal.ParamChange - }{ - { - name: "succeeds when changing allowed values and keeping not allowed the same", - expected: true, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: s.cdpCollateralRequirements, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - Value: `[{ - "denom": "bnb", - "type": "bnb-a", - "liquidation_ratio": "2.010000000000000000", - "debt_limit": { "denom": "usdx", "amount": "100" }, - "stability_fee": "1.020000000000000000", - "auction_size": "100", - "liquidation_penalty": "0.050000000000000000", - "spot_market_id": "bnbc:usd", - "liquidation_market_id": "bnb:usd", - "keeper_reward_percentage": "0", - "check_collateralization_index_count": "0", - "conversion_factor": "9" - }, - { - "denom": "btc", - "type": "btc-a", - "liquidation_ratio": "1.500000000000000000", - "debt_limit": { "denom": "usdx", "amount": "200" }, - "stability_fee": "2.010000000000000000", - "auction_size": "1200", - "liquidation_penalty": "0.100000000000000000", - "spot_market_id": "btc:usd", - "liquidation_market_id": "btc:usd", - "keeper_reward_percentage": "0.000000000000000000", - "check_collateralization_index_count": "1", - "conversion_factor": "8" - }]`, - }, - }, - { - name: "succeeds if nothing is changed", - expected: true, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: s.cdpCollateralRequirements, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, unchangedBtcValue), - }, - }, - { - name: "fails if changed records are not the same length as existing records", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: s.cdpCollateralRequirements, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - Value: fmt.Sprintf("[%s]", unchangedBnbValue), - }, - }, - { - name: "fails if incoming records are missing a existing record", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: s.cdpCollateralRequirements, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - // same length as existing records but missing one with the correct key/value pair - Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, unchangedBnbValue), - }, - }, - { - name: "fails when changing an attribute that is not allowed", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: s.cdpCollateralRequirements, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - // changed liquidation_ratio, which is not whitelisted - Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, `{ - "denom": "btc", - "type": "btc-a", - "liquidation_ratio": "1.2", - "debt_limit": { "denom": "usdx", "amount": "100" }, - "stability_fee": "1.01", - "auction_size": "1000", - "liquidation_penalty": "0.1", - "spot_market_id": "btc:usd", - "liquidation_market_id": "btc:usd", - "keeper_reward_percentage": "0.12", - "check_collateralization_index_count": "1", - "conversion_factor": "8" - }`), - }, - }, - { - name: "fails when requirements does not include an existing record", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: []types.SubparamRequirement{s.cdpCollateralRequirements[0]}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, unchangedBtcValue), - }, - }, - { - name: "fails when changes has missing key", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: []types.SubparamRequirement{s.cdpCollateralRequirements[0]}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - // missing check_collateralization_index_count - Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, `{ - "denom": "btc", - "type": "btc-a", - "liquidation_ratio": "1.500000000000000000", - "debt_limit": { "denom": "usdx", "amount": "100" }, - "stability_fee": "1.010000000000000000", - "auction_size": "1000", - "liquidation_penalty": "0.100000000000000000", - "spot_market_id": "btc:usd", - "liquidation_market_id": "btc:usd", - "keeper_reward_percentage": "0.12", - "conversion_factor": "8" - }`), - }, - }, - { - name: "fails when changes has same keys length but an unknown key", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: []types.SubparamRequirement{s.cdpCollateralRequirements[0]}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - // missspelled denom key - Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, `{ - "denoms": "btc", - "type": "btc-a", - "liquidation_ratio": "1.500000000000000000", - "debt_limit": { "denom": "usdx", "amount": "100" }, - "stability_fee": "1.010000000000000000", - "auction_size": "1000", - "liquidation_penalty": "0.100000000000000000", - "spot_market_id": "btc:usd", - "liquidation_market_id": "btc:usd", - "keeper_reward_percentage": "0.12", - "check_collateralization_index_count": "1", - "conversion_factor": "8" - }`), - }, - }, - { - name: "fails when attr is not allowed and has different value", - expected: false, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: []types.SubparamRequirement{s.cdpCollateralRequirements[0]}, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - // liquidation_ratio changed value but is not allowed - Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, `{ - "denom": "btc", - "type": "btc-a", - "liquidation_ratio": "1.510000000000000000", - "debt_limit": { "denom": "usdx", "amount": "100" }, - "stability_fee": "1.010000000000000000", - "auction_size": "1000", - "liquidation_penalty": "0.100000000000000000", - "spot_market_id": "btc:usd", - "liquidation_market_id": "btc:usd", - "keeper_reward_percentage": "0.12", - "check_collateralization_index_count": "1", - "conversion_factor": "8" - }`), - }, - }, - { - name: "succeeds when param attr is not allowed but is same", - expected: true, - permission: types.AllowedParamsChange{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: s.cdpCollateralRequirements, - }, - paramChange: paramsproposal.ParamChange{ - Subspace: "cdp", - Key: "CollateralParams", - // liquidation_ratio is not allowed but the same - // stability_fee is allowed but changed - Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, `{ - "denom": "btc", - "type": "btc-a", - "liquidation_ratio": "1.500000000000000000", - "debt_limit": { "denom": "usdx", "amount": "100" }, - "stability_fee": "1.020000000000000000", - "auction_size": "1000", - "liquidation_penalty": "0.100000000000000000", - "spot_market_id": "btc:usd", - "liquidation_market_id": "btc:usd", - "keeper_reward_percentage": "0.12", - "check_collateralization_index_count": "1", - "conversion_factor": "8" - }`), - }, - }, - } +// testcases := []struct { +// name string +// expected bool +// permission types.AllowedParamsChange +// paramChange paramsproposal.ParamChange +// }{ +// { +// name: "succeeds when changing allowed values and keeping not allowed the same", +// expected: true, +// permission: types.AllowedParamsChange{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyCollateralParams), +// MultiSubparamsRequirements: s.cdpCollateralRequirements, +// }, +// paramChange: paramsproposal.ParamChange{ +// Subspace: "cdp", +// Key: "CollateralParams", +// Value: `[{ +// "denom": "bnb", +// "type": "bnb-a", +// "liquidation_ratio": "2.010000000000000000", +// "debt_limit": { "denom": "usdx", "amount": "100" }, +// "stability_fee": "1.020000000000000000", +// "auction_size": "100", +// "liquidation_penalty": "0.050000000000000000", +// "spot_market_id": "bnbc:usd", +// "liquidation_market_id": "bnb:usd", +// "keeper_reward_percentage": "0", +// "check_collateralization_index_count": "0", +// "conversion_factor": "9" +// }, +// { +// "denom": "btc", +// "type": "btc-a", +// "liquidation_ratio": "1.500000000000000000", +// "debt_limit": { "denom": "usdx", "amount": "200" }, +// "stability_fee": "2.010000000000000000", +// "auction_size": "1200", +// "liquidation_penalty": "0.100000000000000000", +// "spot_market_id": "btc:usd", +// "liquidation_market_id": "btc:usd", +// "keeper_reward_percentage": "0.000000000000000000", +// "check_collateralization_index_count": "1", +// "conversion_factor": "8" +// }]`, +// }, +// }, +// { +// name: "succeeds if nothing is changed", +// expected: true, +// permission: types.AllowedParamsChange{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyCollateralParams), +// MultiSubparamsRequirements: s.cdpCollateralRequirements, +// }, +// paramChange: paramsproposal.ParamChange{ +// Subspace: "cdp", +// Key: "CollateralParams", +// Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, unchangedBtcValue), +// }, +// }, +// { +// name: "fails if changed records are not the same length as existing records", +// expected: false, +// permission: types.AllowedParamsChange{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyCollateralParams), +// MultiSubparamsRequirements: s.cdpCollateralRequirements, +// }, +// paramChange: paramsproposal.ParamChange{ +// Subspace: "cdp", +// Key: "CollateralParams", +// Value: fmt.Sprintf("[%s]", unchangedBnbValue), +// }, +// }, +// { +// name: "fails if incoming records are missing a existing record", +// expected: false, +// permission: types.AllowedParamsChange{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyCollateralParams), +// MultiSubparamsRequirements: s.cdpCollateralRequirements, +// }, +// paramChange: paramsproposal.ParamChange{ +// Subspace: "cdp", +// Key: "CollateralParams", +// // same length as existing records but missing one with the correct key/value pair +// Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, unchangedBnbValue), +// }, +// }, +// { +// name: "fails when changing an attribute that is not allowed", +// expected: false, +// permission: types.AllowedParamsChange{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyCollateralParams), +// MultiSubparamsRequirements: s.cdpCollateralRequirements, +// }, +// paramChange: paramsproposal.ParamChange{ +// Subspace: "cdp", +// Key: "CollateralParams", +// // changed liquidation_ratio, which is not whitelisted +// Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, `{ +// "denom": "btc", +// "type": "btc-a", +// "liquidation_ratio": "1.2", +// "debt_limit": { "denom": "usdx", "amount": "100" }, +// "stability_fee": "1.01", +// "auction_size": "1000", +// "liquidation_penalty": "0.1", +// "spot_market_id": "btc:usd", +// "liquidation_market_id": "btc:usd", +// "keeper_reward_percentage": "0.12", +// "check_collateralization_index_count": "1", +// "conversion_factor": "8" +// }`), +// }, +// }, +// { +// name: "fails when requirements does not include an existing record", +// expected: false, +// permission: types.AllowedParamsChange{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyCollateralParams), +// MultiSubparamsRequirements: []types.SubparamRequirement{s.cdpCollateralRequirements[0]}, +// }, +// paramChange: paramsproposal.ParamChange{ +// Subspace: "cdp", +// Key: "CollateralParams", +// Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, unchangedBtcValue), +// }, +// }, +// { +// name: "fails when changes has missing key", +// expected: false, +// permission: types.AllowedParamsChange{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyCollateralParams), +// MultiSubparamsRequirements: []types.SubparamRequirement{s.cdpCollateralRequirements[0]}, +// }, +// paramChange: paramsproposal.ParamChange{ +// Subspace: "cdp", +// Key: "CollateralParams", +// // missing check_collateralization_index_count +// Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, `{ +// "denom": "btc", +// "type": "btc-a", +// "liquidation_ratio": "1.500000000000000000", +// "debt_limit": { "denom": "usdx", "amount": "100" }, +// "stability_fee": "1.010000000000000000", +// "auction_size": "1000", +// "liquidation_penalty": "0.100000000000000000", +// "spot_market_id": "btc:usd", +// "liquidation_market_id": "btc:usd", +// "keeper_reward_percentage": "0.12", +// "conversion_factor": "8" +// }`), +// }, +// }, +// { +// name: "fails when changes has same keys length but an unknown key", +// expected: false, +// permission: types.AllowedParamsChange{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyCollateralParams), +// MultiSubparamsRequirements: []types.SubparamRequirement{s.cdpCollateralRequirements[0]}, +// }, +// paramChange: paramsproposal.ParamChange{ +// Subspace: "cdp", +// Key: "CollateralParams", +// // missspelled denom key +// Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, `{ +// "denoms": "btc", +// "type": "btc-a", +// "liquidation_ratio": "1.500000000000000000", +// "debt_limit": { "denom": "usdx", "amount": "100" }, +// "stability_fee": "1.010000000000000000", +// "auction_size": "1000", +// "liquidation_penalty": "0.100000000000000000", +// "spot_market_id": "btc:usd", +// "liquidation_market_id": "btc:usd", +// "keeper_reward_percentage": "0.12", +// "check_collateralization_index_count": "1", +// "conversion_factor": "8" +// }`), +// }, +// }, +// { +// name: "fails when attr is not allowed and has different value", +// expected: false, +// permission: types.AllowedParamsChange{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyCollateralParams), +// MultiSubparamsRequirements: []types.SubparamRequirement{s.cdpCollateralRequirements[0]}, +// }, +// paramChange: paramsproposal.ParamChange{ +// Subspace: "cdp", +// Key: "CollateralParams", +// // liquidation_ratio changed value but is not allowed +// Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, `{ +// "denom": "btc", +// "type": "btc-a", +// "liquidation_ratio": "1.510000000000000000", +// "debt_limit": { "denom": "usdx", "amount": "100" }, +// "stability_fee": "1.010000000000000000", +// "auction_size": "1000", +// "liquidation_penalty": "0.100000000000000000", +// "spot_market_id": "btc:usd", +// "liquidation_market_id": "btc:usd", +// "keeper_reward_percentage": "0.12", +// "check_collateralization_index_count": "1", +// "conversion_factor": "8" +// }`), +// }, +// }, +// { +// name: "succeeds when param attr is not allowed but is same", +// expected: true, +// permission: types.AllowedParamsChange{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyCollateralParams), +// MultiSubparamsRequirements: s.cdpCollateralRequirements, +// }, +// paramChange: paramsproposal.ParamChange{ +// Subspace: "cdp", +// Key: "CollateralParams", +// // liquidation_ratio is not allowed but the same +// // stability_fee is allowed but changed +// Value: fmt.Sprintf("[%s, %s]", unchangedBnbValue, `{ +// "denom": "btc", +// "type": "btc-a", +// "liquidation_ratio": "1.500000000000000000", +// "debt_limit": { "denom": "usdx", "amount": "100" }, +// "stability_fee": "1.020000000000000000", +// "auction_size": "1000", +// "liquidation_penalty": "0.100000000000000000", +// "spot_market_id": "btc:usd", +// "liquidation_market_id": "btc:usd", +// "keeper_reward_percentage": "0.12", +// "check_collateralization_index_count": "1", +// "conversion_factor": "8" +// }`), +// }, +// }, +// } - for _, tc := range testcases { - s.Run(tc.name, func() { - s.SetupTest() +// for _, tc := range testcases { +// s.Run(tc.name, func() { +// s.SetupTest() - subspace, found := s.pk.GetSubspace(cdptypes.ModuleName) - s.Require().True(found) - subspace.Set(s.ctx, cdptypes.KeyCollateralParams, s.cdpCollateralParams) +// subspace, found := s.pk.GetSubspace(cdptypes.ModuleName) +// s.Require().True(found) +// subspace.Set(s.ctx, cdptypes.KeyCollateralParams, s.cdpCollateralParams) - permission := types.ParamsChangePermission{ - AllowedParamsChanges: types.AllowedParamsChanges{tc.permission}, - } - proposal := paramsproposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []paramsproposal.ParamChange{tc.paramChange}, - ) - s.Require().Equal( - tc.expected, - permission.Allows(s.ctx, s.pk, proposal), - ) - }) - } -} +// permission := types.ParamsChangePermission{ +// AllowedParamsChanges: types.AllowedParamsChanges{tc.permission}, +// } +// proposal := paramsproposal.NewParameterChangeProposal( +// "A Title", +// "A description of this proposal.", +// []paramsproposal.ParamChange{tc.paramChange}, +// ) +// s.Require().Equal( +// tc.expected, +// permission.Allows(s.ctx, s.pk, proposal), +// ) +// }) +// } +// } -func (s *ParamsChangeTestSuite) TestAllowedParamsChange_InvalidJSON() { - subspace, found := s.pk.GetSubspace(cdptypes.ModuleName) - s.Require().True(found) - subspace.Set(s.ctx, cdptypes.KeyDebtParam, s.cdpDebtParam) +// func (s *ParamsChangeTestSuite) TestAllowedParamsChange_InvalidJSON() { +// subspace, found := s.pk.GetSubspace(cdptypes.ModuleName) +// s.Require().True(found) +// subspace.Set(s.ctx, cdptypes.KeyDebtParam, s.cdpDebtParam) - permission := types.ParamsChangePermission{ - AllowedParamsChanges: types.AllowedParamsChanges{{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"denom", "reference_asset", "conversion_factor", "debt_floor"}, - }}, - } - proposal := paramsproposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []paramsproposal.ParamChange{ - { - Subspace: "cdp", - Key: "DebtParam", - Value: `{badjson}`, - }, - }, - ) - s.Require().Equal( - false, - permission.Allows(s.ctx, s.pk, proposal), - ) -} +// permission := types.ParamsChangePermission{ +// AllowedParamsChanges: types.AllowedParamsChanges{{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyDebtParam), +// SingleSubparamAllowedAttrs: []string{"denom", "reference_asset", "conversion_factor", "debt_floor"}, +// }}, +// } +// proposal := paramsproposal.NewParameterChangeProposal( +// "A Title", +// "A description of this proposal.", +// []paramsproposal.ParamChange{ +// { +// Subspace: "cdp", +// Key: "DebtParam", +// Value: `{badjson}`, +// }, +// }, +// ) +// s.Require().Equal( +// false, +// permission.Allows(s.ctx, s.pk, proposal), +// ) +// } -func (s *ParamsChangeTestSuite) TestAllowedParamsChange_InvalidJSONArray() { - subspace, found := s.pk.GetSubspace(cdptypes.ModuleName) - s.Require().True(found) - subspace.Set(s.ctx, cdptypes.KeyCollateralParams, s.cdpCollateralParams) - permission := types.ParamsChangePermission{ - AllowedParamsChanges: types.AllowedParamsChanges{{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyCollateralParams), - MultiSubparamsRequirements: s.cdpCollateralRequirements, - }}, - } - proposal := paramsproposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []paramsproposal.ParamChange{ - { - Subspace: "cdp", - Key: string(cdptypes.KeyCollateralParams), - Value: `[badjson]`, - }, - }, - ) - s.Require().Equal( - false, - permission.Allows(s.ctx, s.pk, proposal), - ) -} +// func (s *ParamsChangeTestSuite) TestAllowedParamsChange_InvalidJSONArray() { +// subspace, found := s.pk.GetSubspace(cdptypes.ModuleName) +// s.Require().True(found) +// subspace.Set(s.ctx, cdptypes.KeyCollateralParams, s.cdpCollateralParams) +// permission := types.ParamsChangePermission{ +// AllowedParamsChanges: types.AllowedParamsChanges{{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyCollateralParams), +// MultiSubparamsRequirements: s.cdpCollateralRequirements, +// }}, +// } +// proposal := paramsproposal.NewParameterChangeProposal( +// "A Title", +// "A description of this proposal.", +// []paramsproposal.ParamChange{ +// { +// Subspace: "cdp", +// Key: string(cdptypes.KeyCollateralParams), +// Value: `[badjson]`, +// }, +// }, +// ) +// s.Require().Equal( +// false, +// permission.Allows(s.ctx, s.pk, proposal), +// ) +// } -func (s *ParamsChangeTestSuite) TestAllowedParamsChange_NoSubspaceData() { - permission := types.ParamsChangePermission{ - AllowedParamsChanges: types.AllowedParamsChanges{{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"denom"}, - }}, - } - proposal := paramsproposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []paramsproposal.ParamChange{{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - Value: `{}`, - }}, - ) - s.Require().Panics(func() { - permission.Allows(s.ctx, s.pk, proposal) - }) -} +// func (s *ParamsChangeTestSuite) TestAllowedParamsChange_NoSubspaceData() { +// permission := types.ParamsChangePermission{ +// AllowedParamsChanges: types.AllowedParamsChanges{{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyDebtParam), +// SingleSubparamAllowedAttrs: []string{"denom"}, +// }}, +// } +// proposal := paramsproposal.NewParameterChangeProposal( +// "A Title", +// "A description of this proposal.", +// []paramsproposal.ParamChange{{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyDebtParam), +// Value: `{}`, +// }}, +// ) +// s.Require().Panics(func() { +// permission.Allows(s.ctx, s.pk, proposal) +// }) +// } -func (s *ParamsChangeTestSuite) TestParamsChangePermission_NoAllowedChanged() { - permission := types.ParamsChangePermission{} - proposal := paramsproposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - []paramsproposal.ParamChange{ - { - Key: string(cdptypes.KeyDebtParam), - Subspace: cdptypes.ModuleName, - Value: `{}`, - }, - }, - ) - s.Require().False(permission.Allows(s.ctx, s.pk, proposal)) -} +// func (s *ParamsChangeTestSuite) TestParamsChangePermission_NoAllowedChanged() { +// permission := types.ParamsChangePermission{} +// proposal := paramsproposal.NewParameterChangeProposal( +// "A Title", +// "A description of this proposal.", +// []paramsproposal.ParamChange{ +// { +// Key: string(cdptypes.KeyDebtParam), +// Subspace: cdptypes.ModuleName, +// Value: `{}`, +// }, +// }, +// ) +// s.Require().False(permission.Allows(s.ctx, s.pk, proposal)) +// } -func (s *ParamsChangeTestSuite) TestParamsChangePermission_PassWhenOneAllowed() { - subspace, found := s.pk.GetSubspace(cdptypes.ModuleName) - s.Require().True(found) - subspace.Set(s.ctx, cdptypes.KeyDebtParam, s.cdpDebtParam) +// func (s *ParamsChangeTestSuite) TestParamsChangePermission_PassWhenOneAllowed() { +// subspace, found := s.pk.GetSubspace(cdptypes.ModuleName) +// s.Require().True(found) +// subspace.Set(s.ctx, cdptypes.KeyDebtParam, s.cdpDebtParam) - permission := types.ParamsChangePermission{ - AllowedParamsChanges: types.AllowedParamsChanges{ - { - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"denom"}, - }, - { - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeyDebtParam), - SingleSubparamAllowedAttrs: []string{"reference_asset"}, - }, - }, - } - proposal := paramsproposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - // test success if one AllowedParamsChange is allowed and the other is not - []paramsproposal.ParamChange{ - { - Key: string(cdptypes.KeyDebtParam), - Subspace: cdptypes.ModuleName, - Value: `{ - "denom": "usdx", - "reference_asset": "usd2", - "conversion_factor": "6", - "debt_floor": "1000" - }`, - }, - }, - ) - s.Require().True(permission.Allows(s.ctx, s.pk, proposal)) -} +// permission := types.ParamsChangePermission{ +// AllowedParamsChanges: types.AllowedParamsChanges{ +// { +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyDebtParam), +// SingleSubparamAllowedAttrs: []string{"denom"}, +// }, +// { +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeyDebtParam), +// SingleSubparamAllowedAttrs: []string{"reference_asset"}, +// }, +// }, +// } +// proposal := paramsproposal.NewParameterChangeProposal( +// "A Title", +// "A description of this proposal.", +// // test success if one AllowedParamsChange is allowed and the other is not +// []paramsproposal.ParamChange{ +// { +// Key: string(cdptypes.KeyDebtParam), +// Subspace: cdptypes.ModuleName, +// Value: `{ +// "denom": "usdx", +// "reference_asset": "usd2", +// "conversion_factor": "6", +// "debt_floor": "1000" +// }`, +// }, +// }, +// ) +// s.Require().True(permission.Allows(s.ctx, s.pk, proposal)) +// } // Test subparam value with slice data unchanged comparision func (s *ParamsChangeTestSuite) TestParamsChangePermission_SliceSubparamComparision() { @@ -761,76 +759,76 @@ func (s *ParamsChangeTestSuite) TestParamsChangePermission_SliceSubparamComparis } } -func (s *ParamsChangeTestSuite) TestParamsChangePermission_NoSubparamRequirements() { - permission := types.ParamsChangePermission{ - AllowedParamsChanges: types.AllowedParamsChanges{{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeySurplusThreshold), - }}, - } +// func (s *ParamsChangeTestSuite) TestParamsChangePermission_NoSubparamRequirements() { +// permission := types.ParamsChangePermission{ +// AllowedParamsChanges: types.AllowedParamsChanges{{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeySurplusThreshold), +// }}, +// } - testcases := []struct { - name string - expected bool - changes []paramsproposal.ParamChange - }{ - { - name: "success when changing allowed params", - expected: true, - changes: []paramsproposal.ParamChange{{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeySurplusThreshold), - Value: sdkmath.NewInt(120).String(), - }}, - }, - { - name: "fail when changing not allowed params", - expected: false, - changes: []paramsproposal.ParamChange{{ - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeySurplusLot), - Value: sdkmath.NewInt(120).String(), - }}, - }, - { - name: "fail if one change is not allowed", - expected: false, - changes: []paramsproposal.ParamChange{ - { - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeySurplusThreshold), - Value: sdkmath.NewInt(120).String(), - }, - { - Subspace: cdptypes.ModuleName, - Key: string(cdptypes.KeySurplusLot), - Value: sdkmath.NewInt(120).String(), - }, - }, - }, - } +// testcases := []struct { +// name string +// expected bool +// changes []paramsproposal.ParamChange +// }{ +// { +// name: "success when changing allowed params", +// expected: true, +// changes: []paramsproposal.ParamChange{{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeySurplusThreshold), +// Value: sdkmath.NewInt(120).String(), +// }}, +// }, +// { +// name: "fail when changing not allowed params", +// expected: false, +// changes: []paramsproposal.ParamChange{{ +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeySurplusLot), +// Value: sdkmath.NewInt(120).String(), +// }}, +// }, +// { +// name: "fail if one change is not allowed", +// expected: false, +// changes: []paramsproposal.ParamChange{ +// { +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeySurplusThreshold), +// Value: sdkmath.NewInt(120).String(), +// }, +// { +// Subspace: cdptypes.ModuleName, +// Key: string(cdptypes.KeySurplusLot), +// Value: sdkmath.NewInt(120).String(), +// }, +// }, +// }, +// } - for _, tc := range testcases { - s.Run(tc.name, func() { - s.SetupTest() +// for _, tc := range testcases { +// s.Run(tc.name, func() { +// s.SetupTest() - subspace, found := s.pk.GetSubspace(cdptypes.ModuleName) - s.Require().True(found) - subspace.Set(s.ctx, cdptypes.KeySurplusThreshold, sdkmath.NewInt(100)) - subspace.Set(s.ctx, cdptypes.KeySurplusLot, sdkmath.NewInt(110)) +// subspace, found := s.pk.GetSubspace(cdptypes.ModuleName) +// s.Require().True(found) +// subspace.Set(s.ctx, cdptypes.KeySurplusThreshold, sdkmath.NewInt(100)) +// subspace.Set(s.ctx, cdptypes.KeySurplusLot, sdkmath.NewInt(110)) - proposal := paramsproposal.NewParameterChangeProposal( - "A Title", - "A description of this proposal.", - tc.changes, - ) - s.Require().Equal( - tc.expected, - permission.Allows(s.ctx, s.pk, proposal), - ) - }) - } -} +// proposal := paramsproposal.NewParameterChangeProposal( +// "A Title", +// "A description of this proposal.", +// tc.changes, +// ) +// s.Require().Equal( +// tc.expected, +// permission.Allows(s.ctx, s.pk, proposal), +// ) +// }) +// } +// } func TestParamsChangeTestSuite(t *testing.T) { suite.Run(t, new(ParamsChangeTestSuite)) diff --git a/x/committee/types/permissions.go b/x/committee/types/permissions.go index c46fbcae..00e101c2 100644 --- a/x/committee/types/permissions.go +++ b/x/committee/types/permissions.go @@ -6,7 +6,6 @@ import ( "reflect" "strings" - communitytypes "github.com/0glabs/0g-chain/x/community/types" "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" @@ -54,9 +53,9 @@ var ( _ Permission = TextPermission{} _ Permission = SoftwareUpgradePermission{} _ Permission = ParamsChangePermission{} - _ Permission = CommunityCDPRepayDebtPermission{} - _ Permission = CommunityPoolLendWithdrawPermission{} - _ Permission = CommunityCDPWithdrawCollateralPermission{} + // _ Permission = CommunityCDPRepayDebtPermission{} + // _ Permission = CommunityPoolLendWithdrawPermission{} + // _ Permission = CommunityCDPWithdrawCollateralPermission{} ) // Allows implement permission interface for GodPermission. @@ -74,23 +73,23 @@ func (SoftwareUpgradePermission) Allows(_ sdk.Context, _ ParamKeeper, p PubPropo return ok } -// Allows implement permission interface for CommunityCDPRepayDebtPermission. -func (CommunityCDPRepayDebtPermission) Allows(_ sdk.Context, _ ParamKeeper, p PubProposal) bool { - _, ok := p.(*communitytypes.CommunityCDPRepayDebtProposal) - return ok -} +// // Allows implement permission interface for CommunityCDPRepayDebtPermission. +// func (CommunityCDPRepayDebtPermission) Allows(_ sdk.Context, _ ParamKeeper, p PubProposal) bool { +// _, ok := p.(*communitytypes.CommunityCDPRepayDebtProposal) +// return ok +// } -// Allows implement permission interface for CommunityCDPWithdrawCollateralPermission. -func (CommunityCDPWithdrawCollateralPermission) Allows(_ sdk.Context, _ ParamKeeper, p PubProposal) bool { - _, ok := p.(*communitytypes.CommunityCDPWithdrawCollateralProposal) - return ok -} +// // Allows implement permission interface for CommunityCDPWithdrawCollateralPermission. +// func (CommunityCDPWithdrawCollateralPermission) Allows(_ sdk.Context, _ ParamKeeper, p PubProposal) bool { +// _, ok := p.(*communitytypes.CommunityCDPWithdrawCollateralProposal) +// return ok +// } -// Allows implement permission interface for CommunityPoolLendWithdrawPermission. -func (CommunityPoolLendWithdrawPermission) Allows(_ sdk.Context, _ ParamKeeper, p PubProposal) bool { - _, ok := p.(*communitytypes.CommunityPoolLendWithdrawProposal) - return ok -} +// // Allows implement permission interface for CommunityPoolLendWithdrawPermission. +// func (CommunityPoolLendWithdrawPermission) Allows(_ sdk.Context, _ ParamKeeper, p PubProposal) bool { +// _, ok := p.(*communitytypes.CommunityPoolLendWithdrawProposal) +// return ok +// } // Allows implement permission interface for ParamsChangePermission. func (perm ParamsChangePermission) Allows(ctx sdk.Context, pk ParamKeeper, p PubProposal) bool { diff --git a/x/committee/types/permissions_test.go b/x/committee/types/permissions_test.go index 084e6f90..07ccc157 100644 --- a/x/committee/types/permissions_test.go +++ b/x/committee/types/permissions_test.go @@ -11,7 +11,6 @@ import ( paramsproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" "github.com/0glabs/0g-chain/x/committee/types" - communitytypes "github.com/0glabs/0g-chain/x/community/types" ) func TestPackPermissions_Success(t *testing.T) { @@ -41,118 +40,118 @@ func TestUnpackPermissions_Failure(t *testing.T) { require.Error(t, err) } -func TestCommunityCDPRepayDebtPermission_Allows(t *testing.T) { - permission := types.CommunityCDPRepayDebtPermission{} - testcases := []struct { - name string - proposal types.PubProposal - allowed bool - }{ - { - name: "allowed for correct proposal", - proposal: communitytypes.NewCommunityCDPRepayDebtProposal( - "repay x/community cdp debt", - "repays debt on a cdp position", - "collateral-type", - sdk.NewInt64Coin("ukava", 1e10), - ), - allowed: true, - }, - { - name: "fails for nil proposal", - proposal: nil, - allowed: false, - }, - { - name: "fails for wrong proposal", - proposal: newTestParamsChangeProposalWithChanges([]paramsproposal.ParamChange{ - {Subspace: "cdp", Key: "DebtThreshold", Value: `test`}, - }), - allowed: false, - }, - } +// func TestCommunityCDPRepayDebtPermission_Allows(t *testing.T) { +// permission := types.CommunityCDPRepayDebtPermission{} +// testcases := []struct { +// name string +// proposal types.PubProposal +// allowed bool +// }{ +// { +// name: "allowed for correct proposal", +// proposal: communitytypes.NewCommunityCDPRepayDebtProposal( +// "repay x/community cdp debt", +// "repays debt on a cdp position", +// "collateral-type", +// sdk.NewInt64Coin("ukava", 1e10), +// ), +// allowed: true, +// }, +// { +// name: "fails for nil proposal", +// proposal: nil, +// allowed: false, +// }, +// { +// name: "fails for wrong proposal", +// proposal: newTestParamsChangeProposalWithChanges([]paramsproposal.ParamChange{ +// {Subspace: "cdp", Key: "DebtThreshold", Value: `test`}, +// }), +// allowed: false, +// }, +// } - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - require.Equal(t, tc.allowed, permission.Allows(sdk.Context{}, nil, tc.proposal)) - }) - } -} +// for _, tc := range testcases { +// t.Run(tc.name, func(t *testing.T) { +// require.Equal(t, tc.allowed, permission.Allows(sdk.Context{}, nil, tc.proposal)) +// }) +// } +// } -func TestCommunityPoolLendWithdrawPermission_Allows(t *testing.T) { - permission := types.CommunityPoolLendWithdrawPermission{} - testcases := []struct { - name string - proposal types.PubProposal - allowed bool - }{ - { - name: "allowed for correct proposal", - proposal: communitytypes.NewCommunityPoolLendWithdrawProposal( - "withdraw lend position", - "this fake proposal withdraws a lend position for the community pool", - sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e10))), - ), - allowed: true, - }, - { - name: "fails for nil proposal", - proposal: nil, - allowed: false, - }, - { - name: "fails for wrong proposal", - proposal: newTestParamsChangeProposalWithChanges([]paramsproposal.ParamChange{ - {Subspace: "cdp", Key: "DebtThreshold", Value: `test`}, - }), - allowed: false, - }, - } +// func TestCommunityPoolLendWithdrawPermission_Allows(t *testing.T) { +// permission := types.CommunityPoolLendWithdrawPermission{} +// testcases := []struct { +// name string +// proposal types.PubProposal +// allowed bool +// }{ +// { +// name: "allowed for correct proposal", +// proposal: communitytypes.NewCommunityPoolLendWithdrawProposal( +// "withdraw lend position", +// "this fake proposal withdraws a lend position for the community pool", +// sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e10))), +// ), +// allowed: true, +// }, +// { +// name: "fails for nil proposal", +// proposal: nil, +// allowed: false, +// }, +// { +// name: "fails for wrong proposal", +// proposal: newTestParamsChangeProposalWithChanges([]paramsproposal.ParamChange{ +// {Subspace: "cdp", Key: "DebtThreshold", Value: `test`}, +// }), +// allowed: false, +// }, +// } - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - require.Equal(t, tc.allowed, permission.Allows(sdk.Context{}, nil, tc.proposal)) - }) - } -} +// for _, tc := range testcases { +// t.Run(tc.name, func(t *testing.T) { +// require.Equal(t, tc.allowed, permission.Allows(sdk.Context{}, nil, tc.proposal)) +// }) +// } +// } -func TestCommunityCDPWithdrawCollateralPermission_Allows(t *testing.T) { - permission := types.CommunityCDPWithdrawCollateralPermission{} - testcases := []struct { - name string - proposal types.PubProposal - allowed bool - }{ - { - name: "allowed for correct proposal", - proposal: communitytypes.NewCommunityCDPWithdrawCollateralProposal( - "withdraw x/community cdp collateral", - "yes", - "collateral-type", - sdk.NewInt64Coin("ukava", 1e10), - ), - allowed: true, - }, - { - name: "fails for nil proposal", - proposal: nil, - allowed: false, - }, - { - name: "fails for wrong proposal", - proposal: newTestParamsChangeProposalWithChanges([]paramsproposal.ParamChange{ - {Subspace: "cdp", Key: "DebtThreshold", Value: `test`}, - }), - allowed: false, - }, - } +// func TestCommunityCDPWithdrawCollateralPermission_Allows(t *testing.T) { +// permission := types.CommunityCDPWithdrawCollateralPermission{} +// testcases := []struct { +// name string +// proposal types.PubProposal +// allowed bool +// }{ +// { +// name: "allowed for correct proposal", +// proposal: communitytypes.NewCommunityCDPWithdrawCollateralProposal( +// "withdraw x/community cdp collateral", +// "yes", +// "collateral-type", +// sdk.NewInt64Coin("ukava", 1e10), +// ), +// allowed: true, +// }, +// { +// name: "fails for nil proposal", +// proposal: nil, +// allowed: false, +// }, +// { +// name: "fails for wrong proposal", +// proposal: newTestParamsChangeProposalWithChanges([]paramsproposal.ParamChange{ +// {Subspace: "cdp", Key: "DebtThreshold", Value: `test`}, +// }), +// allowed: false, +// }, +// } - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - require.Equal(t, tc.allowed, permission.Allows(sdk.Context{}, nil, tc.proposal)) - }) - } -} +// for _, tc := range testcases { +// t.Run(tc.name, func(t *testing.T) { +// require.Equal(t, tc.allowed, permission.Allows(sdk.Context{}, nil, tc.proposal)) +// }) +// } +// } func TestParamsChangePermission_SimpleParamsChange_Allows(t *testing.T) { testPermission := types.ParamsChangePermission{ diff --git a/x/community/abci.go b/x/community/abci.go deleted file mode 100644 index 9ae0dad4..00000000 --- a/x/community/abci.go +++ /dev/null @@ -1,20 +0,0 @@ -package community - -import ( - "time" - - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/community/keeper" - "github.com/0glabs/0g-chain/x/community/types" -) - -// BeginBlocker runs the community module begin blocker logic. -func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { - defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) - - // This exact call order is required to allow payout on the upgrade block - k.CheckAndDisableMintAndKavaDistInflation(ctx) - k.PayoutAccumulatedStakingRewards(ctx) -} diff --git a/x/community/abci_test.go b/x/community/abci_test.go deleted file mode 100644 index 5404c868..00000000 --- a/x/community/abci_test.go +++ /dev/null @@ -1,74 +0,0 @@ -package community_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/community" - "github.com/0glabs/0g-chain/x/community/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/stretchr/testify/require" -) - -func TestABCIStakingRewardsArePaidOutOnDisableInflationBlock(t *testing.T) { - app.SetSDKConfig() - tApp := app.NewTestApp() - tApp.InitializeFromGenesisStates() - keeper := tApp.GetCommunityKeeper() - accountKeeper := tApp.GetAccountKeeper() - bankKeeper := tApp.GetBankKeeper() - - // a block that runs after addition of the disable inflation code on chain - // but before the disable inflation time - initialBlockTime := time.Now() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: initialBlockTime}) - - poolAcc := accountKeeper.GetModuleAccount(ctx, types.ModuleName) - feeCollectorAcc := accountKeeper.GetModuleAccount(ctx, authtypes.FeeCollectorName) - - disableTime := initialBlockTime.Add(9 * time.Second) - - // set state - params, _ := keeper.GetParams(ctx) - params.UpgradeTimeDisableInflation = disableTime - params.UpgradeTimeSetStakingRewardsPerSecond = sdkmath.LegacyNewDec(1000000) // 1 KAVA - params.StakingRewardsPerSecond = sdkmath.LegacyZeroDec() - keeper.SetParams(ctx, params) - - // fund community pool account - tApp.FundAccount(ctx, poolAcc.GetAddress(), sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10000000)))) // 10 KAVA - initialFeeCollectorBalance := bankKeeper.GetBalance(ctx, feeCollectorAcc.GetAddress(), "ukava").Amount - - // run one block - community.BeginBlocker(ctx, keeper) - - // assert that staking rewards in parameters are still set to zero - params, found := keeper.GetParams(ctx) - require.True(t, found) - require.Equal(t, sdkmath.LegacyZeroDec(), params.StakingRewardsPerSecond) - - // assert no rewards are given yet - rewards := bankKeeper.GetBalance(ctx, feeCollectorAcc.GetAddress(), "ukava").Amount.Sub(initialFeeCollectorBalance) - require.Equal(t, sdkmath.ZeroInt(), rewards) - - // new block when disable inflation runs, 10 seconds from initial block for easy math - blockTime := disableTime.Add(1 * time.Second) - ctx = tApp.NewContext(true, tmproto.Header{Height: ctx.BlockHeight() + 1, Time: blockTime}) - - // run the next block - community.BeginBlocker(ctx, keeper) - - // assert that staking rewards have been set and disable inflation time is zero - params, found = keeper.GetParams(ctx) - require.True(t, found) - require.True(t, params.UpgradeTimeDisableInflation.IsZero()) - require.Equal(t, sdkmath.LegacyNewDec(1000000), params.StakingRewardsPerSecond) - - // assert that 10 KAVA has been distributed in rewards - rewards = bankKeeper.GetBalance(ctx, feeCollectorAcc.GetAddress(), "ukava").Amount.Sub(initialFeeCollectorBalance) - require.Equal(t, sdkmath.NewInt(10000000).String(), rewards.String()) -} diff --git a/x/community/client/cli/query.go b/x/community/client/cli/query.go deleted file mode 100644 index 6e5424a3..00000000 --- a/x/community/client/cli/query.go +++ /dev/null @@ -1,107 +0,0 @@ -package cli - -import ( - "context" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - - "github.com/0glabs/0g-chain/x/community/types" -) - -// GetQueryCmd returns the cli query commands for the community module. -func GetQueryCmd() *cobra.Command { - communityQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the community module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - commands := []*cobra.Command{ - getCmdQueryParams(), - getCmdQueryBalance(), - getCmdQueryAnnualizedRewards(), - } - - for _, cmd := range commands { - flags.AddQueryFlagsToCmd(cmd) - } - - communityQueryCmd.AddCommand(commands...) - - return communityQueryCmd -} - -func getCmdQueryParams() *cobra.Command { - return &cobra.Command{ - Use: "params", - Short: "get the community module parameters", - Long: "Get the current community module parameters.", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.Params(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - } -} - -// getCmdQueryBalance implements a command to return the current community pool balance. -func getCmdQueryBalance() *cobra.Command { - return &cobra.Command{ - Use: "balance", - Short: "Query the current balance of the community module account", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.Balance(cmd.Context(), &types.QueryBalanceRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -// getCmdQueryAnnualizedRewards implements a command to return the current annualized rewards. -func getCmdQueryAnnualizedRewards() *cobra.Command { - return &cobra.Command{ - Use: "annualized-rewards", - Short: "Query a current calculation of annualized rewards for the chain.", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.AnnualizedRewards(cmd.Context(), &types.QueryAnnualizedRewardsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} diff --git a/x/community/client/cli/tx.go b/x/community/client/cli/tx.go deleted file mode 100644 index 2567074e..00000000 --- a/x/community/client/cli/tx.go +++ /dev/null @@ -1,210 +0,0 @@ -package cli - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - "github.com/0glabs/0g-chain/x/community/client/utils" - "github.com/0glabs/0g-chain/x/community/types" -) - -const ( - flagDeposit = "deposit" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - communityTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "community module transactions subcommands", - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - getCmdFundCommunityPool(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - communityTxCmd.AddCommand(cmds...) - - return communityTxCmd -} - -func getCmdFundCommunityPool() *cobra.Command { - return &cobra.Command{ - Use: "fund-community-pool [coins]", - Short: "funds the community pool", - Long: "Fund community pool removes the listed coins from the sender's account and send them to the community module account.", - Args: cobra.ExactArgs(1), - Example: fmt.Sprintf( - `%s tx %s fund-community-module 10000000ukava --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - coins, err := sdk.ParseCoinsNormalized(args[0]) - if err != nil { - return err - } - - msg := types.NewMsgFundCommunityPool(clientCtx.GetFromAddress(), coins) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -// NewCmdSubmitCommunityPoolLendDepositProposal implements the command to submit a community-pool lend deposit proposal -func NewCmdSubmitCommunityPoolLendDepositProposal() *cobra.Command { - cmd := &cobra.Command{ - Use: "community-pool-lend-deposit [proposal-file]", - Args: cobra.ExactArgs(1), - Short: "Submit a community pool lend deposit proposal", - Long: strings.TrimSpace( - fmt.Sprintf(`Submit a community pool lend deposit proposal along with an initial deposit. -The proposal details must be supplied via a JSON file. -Note that --deposit below is the initial proposal deposit submitted along with the proposal. -Example: -$ %s tx gov submit-proposal community-pool-lend-deposit --deposit 1000000000ukava --from= -Where proposal.json contains: -{ - "title": "Community Pool Deposit", - "description": "Deposit some KAVA from community pool!", - "amount": [ - { - "denom": "ukava", - "amount": "100000000000" - } - ] -} -`, - version.AppName, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - // parse proposal - proposal, err := utils.ParseCommunityPoolLendDepositProposal(clientCtx.Codec, args[0]) - if err != nil { - return err - } - - deposit, err := parseInitialDeposit(cmd) - if err != nil { - return err - } - - from := clientCtx.GetFromAddress() - msg, err := govv1beta1.NewMsgSubmitProposal(&proposal, deposit, from) - if err != nil { - return err - } - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - cmd.Flags().String(flagDeposit, "", "Initial deposit for the proposal") - - return cmd -} - -// NewCmdSubmitCommunityPoolLendWithdrawProposal implements the command to submit a community-pool lend withdraw proposal -func NewCmdSubmitCommunityPoolLendWithdrawProposal() *cobra.Command { - cmd := &cobra.Command{ - Use: "community-pool-lend-withdraw [proposal-file]", - Args: cobra.ExactArgs(1), - Short: "Submit a community pool lend withdraw proposal", - Long: strings.TrimSpace( - fmt.Sprintf(`Submit a community pool lend withdraw proposal along with an initial deposit. -The proposal details must be supplied via a JSON file. -Note that --deposit below is the initial proposal deposit submitted along with the proposal. -Example: -$ %s tx gov submit-proposal community-pool-lend-withdraw --deposit 1000000000ukava --from= -Where proposal.json contains: -{ - "title": "Community Pool Withdrawal", - "description": "Withdraw some KAVA from community pool!", - "amount": [ - { - "denom": "ukava", - "amount": "100000000000" - } - ] -} -`, - version.AppName, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - // parse proposal - proposal, err := utils.ParseCommunityPoolLendWithdrawProposal(clientCtx.Codec, args[0]) - if err != nil { - return err - } - - deposit, err := parseInitialDeposit(cmd) - if err != nil { - return err - } - from := clientCtx.GetFromAddress() - msg, err := govv1beta1.NewMsgSubmitProposal(&proposal, deposit, from) - if err != nil { - return err - } - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - cmd.Flags().String(flagDeposit, "", "Initial deposit for the proposal") - - return cmd -} - -func parseInitialDeposit(cmd *cobra.Command) (sdk.Coins, error) { - // parse initial deposit - depositStr, err := cmd.Flags().GetString(flagDeposit) - if err != nil { - return nil, fmt.Errorf("no initial deposit found. did you set --deposit? %s", err) - } - deposit, err := sdk.ParseCoinsNormalized(depositStr) - if err != nil { - return nil, fmt.Errorf("unable to parse deposit: %s", err) - } - if !deposit.IsValid() || deposit.IsZero() { - return nil, fmt.Errorf("no initial deposit set, use --deposit flag") - } - return deposit, nil -} diff --git a/x/community/client/proposal_handler.go b/x/community/client/proposal_handler.go deleted file mode 100644 index 10c415eb..00000000 --- a/x/community/client/proposal_handler.go +++ /dev/null @@ -1,17 +0,0 @@ -package client - -import ( - govclient "github.com/cosmos/cosmos-sdk/x/gov/client" - - "github.com/0glabs/0g-chain/x/community/client/cli" -) - -// community-pool deposit/withdraw lend proposal handlers -var ( - LendDepositProposalHandler = govclient.NewProposalHandler( - cli.NewCmdSubmitCommunityPoolLendDepositProposal, - ) - LendWithdrawProposalHandler = govclient.NewProposalHandler( - cli.NewCmdSubmitCommunityPoolLendWithdrawProposal, - ) -) diff --git a/x/community/client/utils/utils.go b/x/community/client/utils/utils.go deleted file mode 100644 index c62a32af..00000000 --- a/x/community/client/utils/utils.go +++ /dev/null @@ -1,39 +0,0 @@ -package utils - -import ( - "os" - - "github.com/cosmos/cosmos-sdk/codec" - - "github.com/0glabs/0g-chain/x/community/types" -) - -// ParseCommunityPoolLendDepositProposal reads a JSON file and parses it to a CommunityPoolLendDepositProposal -func ParseCommunityPoolLendDepositProposal( - cdc codec.JSONCodec, - proposalFile string, -) (types.CommunityPoolLendDepositProposal, error) { - proposal := types.CommunityPoolLendDepositProposal{} - contents, err := os.ReadFile(proposalFile) - if err != nil { - return proposal, err - } - - err = cdc.UnmarshalJSON(contents, &proposal) - return proposal, err -} - -// ParseCommunityPoolLendWithdrawProposal reads a JSON file and parses it to a CommunityPoolLendWithdrawProposal -func ParseCommunityPoolLendWithdrawProposal( - cdc codec.JSONCodec, - proposalFile string, -) (types.CommunityPoolLendWithdrawProposal, error) { - proposal := types.CommunityPoolLendWithdrawProposal{} - contents, err := os.ReadFile(proposalFile) - if err != nil { - return proposal, err - } - - err = cdc.UnmarshalJSON(contents, &proposal) - return proposal, err -} diff --git a/x/community/client/utils/utils_test.go b/x/community/client/utils/utils_test.go deleted file mode 100644 index 87baea69..00000000 --- a/x/community/client/utils/utils_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package utils_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/community/client/utils" -) - -func TestParseDepositProposal(t *testing.T) { - cdc := codec.NewAminoCodec(codec.NewLegacyAmino()) - okJSON := testutil.WriteToNewTempFile(t, ` -{ - "title": "Community Pool Lend Deposit", - "description": "Deposit some KAVA from community pool to Lend!", - "amount": [ - { - "denom": "ukava", - "amount": "100000000000" - } - ] -} -`) - proposal, err := utils.ParseCommunityPoolLendDepositProposal(cdc, okJSON.Name()) - require.NoError(t, err) - - expectedAmount, err := sdk.ParseCoinsNormalized("100000000000ukava") - require.NoError(t, err) - - require.Equal(t, "Community Pool Lend Deposit", proposal.Title) - require.Equal(t, "Deposit some KAVA from community pool to Lend!", proposal.Description) - require.Equal(t, expectedAmount, proposal.Amount) -} - -func TestParseWithdrawProposal(t *testing.T) { - cdc := codec.NewAminoCodec(codec.NewLegacyAmino()) - okJSON := testutil.WriteToNewTempFile(t, ` -{ - "title": "Community Pool Lend Withdraw", - "description": "Withdraw some KAVA from community pool to Lend!", - "amount": [ - { - "denom": "ukava", - "amount": "100000000000" - } - ] -} -`) - proposal, err := utils.ParseCommunityPoolLendWithdrawProposal(cdc, okJSON.Name()) - require.NoError(t, err) - - expectedAmount, err := sdk.ParseCoinsNormalized("100000000000ukava") - require.NoError(t, err) - - require.Equal(t, "Community Pool Lend Withdraw", proposal.Title) - require.Equal(t, "Withdraw some KAVA from community pool to Lend!", proposal.Description) - require.Equal(t, expectedAmount, proposal.Amount) -} - -func TestParseFileNoExists(t *testing.T) { - cdc := codec.NewAminoCodec(codec.NewLegacyAmino()) - _, err := utils.ParseCommunityPoolLendDepositProposal(cdc, "not-a-file.json") - require.ErrorContains(t, err, "no such file or directory") - _, err = utils.ParseCommunityPoolLendWithdrawProposal(cdc, "not-a-file.json") - require.ErrorContains(t, err, "no such file or directory") -} - -func TestParseFileMalformed(t *testing.T) { - cdc := codec.NewAminoCodec(codec.NewLegacyAmino()) - malformed := testutil.WriteToNewTempFile(t, ` -{ - "title": "I'm malformed b/c there's no closing quote, - "description": "A description", - "amount": [{"denom": "ukava", "amount": "100000000000"}] -} -`) - _, err := utils.ParseCommunityPoolLendDepositProposal(cdc, malformed.Name()) - require.ErrorContains(t, err, "invalid character") - _, err = utils.ParseCommunityPoolLendWithdrawProposal(cdc, malformed.Name()) - require.ErrorContains(t, err, "invalid character") -} diff --git a/x/community/disable_inflation_abci_test.go b/x/community/disable_inflation_abci_test.go deleted file mode 100644 index 4a4fba87..00000000 --- a/x/community/disable_inflation_abci_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package community_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/community" - "github.com/0glabs/0g-chain/x/community/keeper" - "github.com/0glabs/0g-chain/x/community/testutil" -) - -func TestABCIDisableInflation(t *testing.T) { - testFunc := func(ctx sdk.Context, k keeper.Keeper) { - community.BeginBlocker(ctx, k) - } - suite.Run(t, testutil.NewDisableInflationTestSuite(testFunc)) -} diff --git a/x/community/genesis.go b/x/community/genesis.go deleted file mode 100644 index 40b532ec..00000000 --- a/x/community/genesis.go +++ /dev/null @@ -1,34 +0,0 @@ -// the community module has no genesis state but must init its module account on init -package community - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/community/keeper" - "github.com/0glabs/0g-chain/x/community/types" -) - -// InitGenesis initializes the community module account and stores the genesis state -func InitGenesis(ctx sdk.Context, k keeper.Keeper, ak types.AccountKeeper, gs types.GenesisState) { - // check if the module account exists - if moduleAcc := ak.GetModuleAccount(ctx, types.ModuleAccountName); moduleAcc == nil { - panic(fmt.Sprintf("%s module account has not been set", types.ModuleAccountName)) - } - - k.SetParams(ctx, gs.Params) - k.SetStakingRewardsState(ctx, gs.StakingRewardsState) -} - -// ExportGenesis exports the store to a genesis state -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { - params, found := k.GetParams(ctx) - if !found { - params = types.Params{} - } - - stakingRewardsState := k.GetStakingRewardsState(ctx) - - return types.NewGenesisState(params, stakingRewardsState) -} diff --git a/x/community/genesis_test.go b/x/community/genesis_test.go deleted file mode 100644 index 11cab4db..00000000 --- a/x/community/genesis_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package community_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - "github.com/0glabs/0g-chain/x/community" - "github.com/0glabs/0g-chain/x/community/testutil" - "github.com/0glabs/0g-chain/x/community/types" -) - -type genesisTestSuite struct { - testutil.Suite -} - -func (suite *genesisTestSuite) SetupTest() { - suite.Suite.SetupTest() -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(genesisTestSuite)) -} - -func (suite *genesisTestSuite) TestInitGenesis() { - - accountKeeper := suite.App.GetAccountKeeper() - - genesisState := types.NewGenesisState( - types.NewParams( - time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - sdkmath.LegacyNewDec(1000), - sdkmath.LegacyNewDec(1000), - ), - types.NewStakingRewardsState( - time.Date(1997, 1, 1, 0, 0, 0, 0, time.UTC), - sdkmath.LegacyMustNewDecFromStr("0.100000000000000000"), - ), - ) - - suite.NotPanics(func() { - community.InitGenesis(suite.Ctx, suite.Keeper, accountKeeper, genesisState) - }) - - // check for module account this way b/c GetModuleAccount creates if not existing. - acc := accountKeeper.GetAccount(suite.Ctx, suite.MaccAddress) - suite.NotNil(acc) - _, ok := acc.(authtypes.ModuleAccountI) - suite.True(ok) - - keeper := suite.App.GetCommunityKeeper() - storedParams, found := keeper.GetParams(suite.Ctx) - suite.True(found) - suite.Equal(genesisState.Params, storedParams) - - stakingRewardsState := keeper.GetStakingRewardsState(suite.Ctx) - suite.Equal(genesisState.StakingRewardsState, stakingRewardsState) -} - -func (suite *genesisTestSuite) TestExportGenesis() { - params := types.NewParams( - time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - sdkmath.LegacyNewDec(1000), - sdkmath.LegacyNewDec(1000), - ) - suite.Keeper.SetParams(suite.Ctx, params) - - stakingRewardsState := types.NewStakingRewardsState( - time.Date(1997, 1, 1, 0, 0, 0, 0, time.UTC), - sdkmath.LegacyMustNewDecFromStr("0.100000000000000000"), - ) - suite.Keeper.SetStakingRewardsState(suite.Ctx, stakingRewardsState) - - genesisState := community.ExportGenesis(suite.Ctx, suite.Keeper) - - suite.Equal(params, genesisState.Params) - suite.Equal(stakingRewardsState, genesisState.StakingRewardsState) -} - -func (suite *genesisTestSuite) TestInitExportIsLossless() { - genesisState := types.NewGenesisState( - types.NewParams( - time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - sdkmath.LegacyNewDec(1000), - sdkmath.LegacyNewDec(1000), - ), - types.NewStakingRewardsState( - time.Date(1997, 1, 1, 0, 0, 0, 0, time.UTC), - sdkmath.LegacyMustNewDecFromStr("0.100000000000000000"), - ), - ) - - community.InitGenesis(suite.Ctx, suite.Keeper, suite.App.GetAccountKeeper(), genesisState) - exportedState := community.ExportGenesis(suite.Ctx, suite.Keeper) - - suite.Equal(genesisState, exportedState) -} diff --git a/x/community/handler.go b/x/community/handler.go deleted file mode 100644 index 6f661ae1..00000000 --- a/x/community/handler.go +++ /dev/null @@ -1,29 +0,0 @@ -package community - -import ( - errorsmod "cosmossdk.io/errors" - 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/0glabs/0g-chain/x/community/keeper" - "github.com/0glabs/0g-chain/x/community/types" -) - -// NewCommunityPoolProposalHandler handles x/community proposals. -func NewCommunityPoolProposalHandler(k keeper.Keeper) govv1beta1.Handler { - return func(ctx sdk.Context, content govv1beta1.Content) error { - switch c := content.(type) { - case *types.CommunityCDPRepayDebtProposal: - return keeper.HandleCommunityCDPRepayDebtProposal(ctx, k, c) - case *types.CommunityCDPWithdrawCollateralProposal: - return keeper.HandleCommunityCDPWithdrawCollateralProposal(ctx, k, c) - case *types.CommunityPoolLendDepositProposal: - return keeper.HandleCommunityPoolLendDepositProposal(ctx, k, c) - case *types.CommunityPoolLendWithdrawProposal: - return keeper.HandleCommunityPoolLendWithdrawProposal(ctx, k, c) - default: - return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized community proposal content type: %T", c) - } - } -} diff --git a/x/community/keeper/consolidate.go b/x/community/keeper/consolidate.go deleted file mode 100644 index 748002da..00000000 --- a/x/community/keeper/consolidate.go +++ /dev/null @@ -1,104 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/0glabs/0g-chain/x/community/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - kavadisttypes "github.com/0glabs/0g-chain/x/kavadist/types" - - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" -) - -// StartCommunityFundConsolidation consolidates the community funds from -// x/distribution and x/kavadist into the x/community module account -func (k Keeper) StartCommunityFundConsolidation(ctx sdk.Context) error { - logger := k.Logger(ctx) - logger.Info("community fund consolidation upgrade started") - - // Consolidate x/distribution community pool - if err := k.consolidateCommunityDistribution(ctx); err != nil { - return err - } - - // Consolidate x/kavadist account - if err := k.consolidateCommunityKavadist(ctx); err != nil { - return err - } - - // Log new x/community balance - communityCoins := k.GetModuleAccountBalance(ctx) - logger.Info(fmt.Sprintf("community funds consolidated, x/community balance is now %s", communityCoins)) - - return nil -} - -// consolidateCommunityDistribution transfers all coins from the x/distribution -// community pool to the x/community module account -func (k Keeper) consolidateCommunityDistribution(ctx sdk.Context) error { - logger := k.Logger(ctx) - - // Get community coins with leftover leftoverDust - truncatedCoins, leftoverDust := k.distrKeeper. - GetFeePoolCommunityCoins(ctx). - TruncateDecimal() - - // Transfer to x/community - err := k.bankKeeper.SendCoinsFromModuleToModule( - ctx, - distrtypes.ModuleName, // sender - types.ModuleName, // recipient - truncatedCoins, - ) - if err != nil { - return fmt.Errorf("failed to transfer x/distribution coins to x/community: %w", err) - } - - logger.Info(fmt.Sprintf("transferred %s from x/distribution to x/community", truncatedCoins)) - - // Set x/distribution community pool to remaining dust amounts - feePool := k.distrKeeper.GetFeePool(ctx) - feePool.CommunityPool = leftoverDust - k.distrKeeper.SetFeePool(ctx, feePool) - - logger.Info(fmt.Sprintf("remaining x/distribution community pool dust: %s", leftoverDust)) - - return nil -} - -// consolidateCommunityKavadist transfers all coins from the x/kavadist module -// account to the x/community module account -func (k Keeper) consolidateCommunityKavadist(ctx sdk.Context) error { - logger := k.Logger(ctx) - - kavadistAcc := k.accountKeeper.GetModuleAccount(ctx, kavadisttypes.KavaDistMacc) - transferCoins := k.bankKeeper.GetAllBalances(ctx, kavadistAcc.GetAddress()) - - // Remove ukava from transfer coins - ony transfer non-ukava coins - found, kavaCoins := transferCoins.Find("ukava") - if found { - transferCoins = transferCoins.Sub(kavaCoins) - } - - // Transfer remaining coins to x/community - err := k.bankKeeper.SendCoinsFromModuleToModule( - ctx, - kavadisttypes.ModuleName, // sender - types.ModuleName, // recipient - transferCoins, - ) - if err != nil { - return fmt.Errorf("failed to transfer x/kavadist coins to x/community: %w", err) - } - - kavadistRemainingCoins := k.bankKeeper.GetAllBalances(ctx, kavadistAcc.GetAddress()) - - logger.Info(fmt.Sprintf( - "transferred %s from x/kavadist to x/community, remaining x/kavadist balance: %s", - transferCoins, - kavadistRemainingCoins, - )) - - return nil -} diff --git a/x/community/keeper/disable_inflation.go b/x/community/keeper/disable_inflation.go deleted file mode 100644 index 2ec1e0d9..00000000 --- a/x/community/keeper/disable_inflation.go +++ /dev/null @@ -1,83 +0,0 @@ -package keeper - -import ( - "time" - - "github.com/0glabs/0g-chain/x/community/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// CheckAndDisableMintAndKavaDistInflation compares the disable inflation time and block time, -// and disables inflation if time is set and before block time. Inflation time is reset, -// so this method is safe to call more than once. -func (k Keeper) CheckAndDisableMintAndKavaDistInflation(ctx sdk.Context) { - // panic if params are not found since this can only be reached if chain state is corrupted or method is ran at an invalid height - params := k.mustGetParams(ctx) - - // if disable inflation time is in the future or zero there is nothing to do, so return - if params.UpgradeTimeDisableInflation.IsZero() || params.UpgradeTimeDisableInflation.After(ctx.BlockTime()) { - return - } - - logger := k.Logger(ctx) - logger.Info("disable inflation upgrade started") - - // run disable inflation logic - k.disableInflation(ctx) - k.disableCommunityTax(ctx) - - logger.Info("disable inflation upgrade finished successfully!") - - // reset disable inflation time to ensure next call is a no-op - params.UpgradeTimeDisableInflation = time.Time{} - // set staking rewards to provided intial value - params.StakingRewardsPerSecond = params.UpgradeTimeSetStakingRewardsPerSecond - k.SetParams(ctx, params) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeInflationStop, - sdk.NewAttribute( - types.AttributeKeyInflationDisableTime, - ctx.BlockTime().Format(time.RFC3339), - ), - ), - ) - - if err := k.StartCommunityFundConsolidation(ctx); err != nil { - panic(err) - } -} - -// TODO: double check this is correct method for disabling inflation in kavadist without -// affecting rewards. In addition, inflation periods in kavadist should be removed. -func (k Keeper) disableInflation(ctx sdk.Context) { - logger := k.Logger(ctx) - - // set x/min inflation to 0 - mintParams := k.mintKeeper.GetParams(ctx) - mintParams.InflationMin = sdk.ZeroDec() - mintParams.InflationMax = sdk.ZeroDec() - if err := k.mintKeeper.SetParams(ctx, mintParams); err != nil { - panic(err) - } - logger.Info("x/mint inflation set to 0") - - // disable kavadist inflation - kavadistParams := k.kavadistKeeper.GetParams(ctx) - kavadistParams.Active = false - k.kavadistKeeper.SetParams(ctx, kavadistParams) - logger.Info("x/kavadist inflation disabled") -} - -// disableCommunityTax sets x/distribution Params.CommunityTax to 0 -func (k Keeper) disableCommunityTax(ctx sdk.Context) { - logger := k.Logger(ctx) - - distrParams := k.distrKeeper.GetParams(ctx) - distrParams.CommunityTax = sdk.ZeroDec() - if err := k.distrKeeper.SetParams(ctx, distrParams); err != nil { - panic(err) - } - logger.Info("x/distribution community tax set to 0") -} diff --git a/x/community/keeper/disable_inflation_test.go b/x/community/keeper/disable_inflation_test.go deleted file mode 100644 index 69f07569..00000000 --- a/x/community/keeper/disable_inflation_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/community/keeper" - "github.com/0glabs/0g-chain/x/community/testutil" -) - -func TestKeeperDisableInflation(t *testing.T) { - testFunc := func(ctx sdk.Context, k keeper.Keeper) { - k.CheckAndDisableMintAndKavaDistInflation(ctx) - } - suite.Run(t, testutil.NewDisableInflationTestSuite(testFunc)) -} diff --git a/x/community/keeper/grpc_query.go b/x/community/keeper/grpc_query.go deleted file mode 100644 index ac70351e..00000000 --- a/x/community/keeper/grpc_query.go +++ /dev/null @@ -1,99 +0,0 @@ -package keeper - -import ( - "context" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/0glabs/0g-chain/x/community/types" -) - -type queryServer struct { - keeper Keeper -} - -var _ types.QueryServer = queryServer{} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(k Keeper) types.QueryServer { - return &queryServer{keeper: k} -} - -// Params implements the gRPC service handler for querying x/community params. -func (s queryServer) Params(c context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - params, found := s.keeper.GetParams(ctx) - if !found { - return nil, status.Error(codes.NotFound, "params not found") - } - - return &types.QueryParamsResponse{ - Params: params, - }, nil -} - -// Balance implements the gRPC service handler for querying x/community balance. -func (s queryServer) Balance(c context.Context, _ *types.QueryBalanceRequest) (*types.QueryBalanceResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - return &types.QueryBalanceResponse{ - Coins: s.keeper.GetModuleAccountBalance(ctx), - }, nil -} - -// CommunityPool queries the community pool coins -func (s queryServer) TotalBalance( - c context.Context, - req *types.QueryTotalBalanceRequest, -) (*types.QueryTotalBalanceResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - // x/distribution community pool balance - nativePoolBalance := s.keeper.distrKeeper.GetFeePoolCommunityCoins(ctx) - - // x/community pool balance - communityPoolBalance := s.keeper.GetModuleAccountBalance(ctx) - - totalBalance := nativePoolBalance.Add(sdk.NewDecCoinsFromCoins(communityPoolBalance...)...) - - return &types.QueryTotalBalanceResponse{ - Pool: totalBalance, - }, nil -} - -// AnnualizedRewards calculates the annualized rewards for the chain. -func (s queryServer) AnnualizedRewards( - c context.Context, - req *types.QueryAnnualizedRewardsRequest, -) (*types.QueryAnnualizedRewardsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - - // staking rewards come from one of two sources depending on if inflation is enabled or not. - // at any given time, only one source will contribute to the staking rewards. the other will be zero. - // this method adds both sources together so it is accurate in both cases. - - params := s.keeper.mustGetParams(ctx) - bondDenom := s.keeper.stakingKeeper.BondDenom(ctx) - - totalSupply := s.keeper.bankKeeper.GetSupply(ctx, bondDenom).Amount - totalBonded := s.keeper.stakingKeeper.TotalBondedTokens(ctx) - rewardsPerSecond := params.StakingRewardsPerSecond - // need to convert these from sdk.Dec to sdkmath.LegacyDec - inflationRate := convertDecToLegacyDec(s.keeper.mintKeeper.GetMinter(ctx).Inflation) - communityTax := convertDecToLegacyDec(s.keeper.distrKeeper.GetCommunityTax(ctx)) - - return &types.QueryAnnualizedRewardsResponse{ - StakingRewards: CalculateStakingAnnualPercentage(totalSupply, totalBonded, inflationRate, communityTax, rewardsPerSecond), - }, nil -} - -// convertDecToLegacyDec is a helper method for converting between new and old Dec types -// current version of cosmos-sdk in this repo uses sdk.Dec -// this module uses sdkmath.LegacyDec in its parameters -// TODO: remove me after upgrade to cosmos-sdk v50 (LegacyDec is everywhere) -func convertDecToLegacyDec(in sdk.Dec) sdkmath.LegacyDec { - return sdkmath.LegacyNewDecFromBigIntWithPrec(in.BigInt(), sdk.Precision) -} diff --git a/x/community/keeper/grpc_query_test.go b/x/community/keeper/grpc_query_test.go deleted file mode 100644 index 8ed58b2d..00000000 --- a/x/community/keeper/grpc_query_test.go +++ /dev/null @@ -1,292 +0,0 @@ -package keeper_test - -import ( - "context" - "testing" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/community/keeper" - "github.com/0glabs/0g-chain/x/community/testutil" - "github.com/0glabs/0g-chain/x/community/types" -) - -type grpcQueryTestSuite struct { - testutil.Suite - - queryClient types.QueryClient -} - -func (suite *grpcQueryTestSuite) SetupTest() { - suite.Suite.SetupTest() - - queryHelper := baseapp.NewQueryServerTestHelper(suite.Ctx, suite.App.InterfaceRegistry()) - types.RegisterQueryServer(queryHelper, keeper.NewQueryServerImpl(suite.Keeper)) - - suite.queryClient = types.NewQueryClient(queryHelper) -} - -func TestGrpcQueryTestSuite(t *testing.T) { - suite.Run(t, new(grpcQueryTestSuite)) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryParams() { - p := types.NewParams( - time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - sdkmath.LegacyNewDec(1000), - sdkmath.LegacyNewDec(1000), - ) - suite.Keeper.SetParams(suite.Ctx, p) - - res, err := suite.queryClient.Params(context.Background(), &types.QueryParamsRequest{}) - suite.Require().NoError(err) - suite.Equal( - types.QueryParamsResponse{ - Params: p, - }, - *res, - ) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryBalance() { - var expCoins sdk.Coins - - testCases := []struct { - name string - setup func() - }{ - { - name: "handles response with no balance", - setup: func() { expCoins = sdk.Coins{} }, - }, - { - name: "handles response with balance", - setup: func() { - expCoins = sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100)), - sdk.NewCoin("usdx", sdkmath.NewInt(1000)), - ) - suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, expCoins) - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - tc.setup() - res, err := suite.queryClient.Balance(context.Background(), &types.QueryBalanceRequest{}) - suite.Require().NoError(err) - suite.Require().True(expCoins.IsEqual(res.Coins)) - }) - } -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalBalance() { - var expCoins sdk.DecCoins - - testCases := []struct { - name string - setup func() - }{ - { - name: "handles response with no balance", - setup: func() { expCoins = sdk.DecCoins{} }, - }, - { - name: "handles response with balance", - setup: func() { - expCoins = sdk.NewDecCoins( - sdk.NewDecCoin("ukava", sdkmath.NewInt(100)), - sdk.NewDecCoin("usdx", sdkmath.NewInt(1000)), - ) - - coins, _ := expCoins.TruncateDecimal() - - suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, coins) - }, - }, - { - name: "handles response with both x/community + x/distribution balance", - setup: func() { - decCoins1 := sdk.NewDecCoins( - sdk.NewDecCoin("ukava", sdkmath.NewInt(100)), - sdk.NewDecCoin("usdx", sdkmath.NewInt(1000)), - ) - - coins, _ := decCoins1.TruncateDecimal() - - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, coins) - suite.Require().NoError(err) - - decCoins2 := sdk.NewDecCoins( - sdk.NewDecCoin("ukava", sdkmath.NewInt(100)), - sdk.NewDecCoin("usdc", sdkmath.NewInt(1000)), - ) - - // Add to x/distribution community pool (just state, not actual coins) - dk := suite.App.GetDistrKeeper() - feePool := dk.GetFeePool(suite.Ctx) - feePool.CommunityPool = feePool.CommunityPool.Add(decCoins2...) - dk.SetFeePool(suite.Ctx, feePool) - - expCoins = decCoins1.Add(decCoins2...) - }, - }, - { - name: "handles response with only x/distribution balance", - setup: func() { - expCoins = sdk.NewDecCoins( - sdk.NewDecCoin("ukava", sdkmath.NewInt(100)), - sdk.NewDecCoin("usdc", sdkmath.NewInt(1000)), - ) - - // Add to x/distribution community pool (just state, not actual coins) - dk := suite.App.GetDistrKeeper() - feePool := dk.GetFeePool(suite.Ctx) - feePool.CommunityPool = feePool.CommunityPool.Add(expCoins...) - dk.SetFeePool(suite.Ctx, feePool) - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - tc.setup() - res, err := suite.queryClient.TotalBalance(context.Background(), &types.QueryTotalBalanceRequest{}) - suite.Require().NoError(err) - suite.Require().True(expCoins.IsEqual(res.Pool)) - }) - } -} - -// NOTE: this test makes use of the fact that there is always an initial 1e6 bonded tokens -// To adjust the bonded ratio, it adjusts the total supply by minting tokens. -func (suite *grpcQueryTestSuite) TestGrpcQueryAnnualizedRewards() { - bondedTokens := sdkmath.NewInt(1e6) - testCases := []struct { - name string - bondedRatio sdk.Dec - inflation sdk.Dec - rewardsPerSec sdkmath.LegacyDec - communityTax sdk.Dec - expectedRate sdkmath.LegacyDec - }{ - { - name: "sanity check: no inflation, no rewards => 0%", - bondedRatio: sdk.MustNewDecFromStr("0.3456"), - inflation: sdk.ZeroDec(), - rewardsPerSec: sdkmath.LegacyZeroDec(), - expectedRate: sdkmath.LegacyZeroDec(), - }, - { - name: "inflation sanity check: 100% inflation, 100% bonded => 100%", - bondedRatio: sdk.OneDec(), - inflation: sdk.OneDec(), - rewardsPerSec: sdkmath.LegacyZeroDec(), - expectedRate: sdkmath.LegacyOneDec(), - }, - { - name: "inflation sanity check: 100% community tax => 0%", - bondedRatio: sdk.OneDec(), - inflation: sdk.OneDec(), - communityTax: sdk.OneDec(), - rewardsPerSec: sdkmath.LegacyZeroDec(), - expectedRate: sdkmath.LegacyZeroDec(), - }, - { - name: "rewards per second sanity check: (totalBonded/SecondsPerYear) rps => 100%", - bondedRatio: sdk.OneDec(), // bonded tokens are constant in this test. ratio has no affect. - inflation: sdk.ZeroDec(), - rewardsPerSec: sdkmath.LegacyNewDecFromInt(bondedTokens).QuoInt(sdkmath.NewInt(keeper.SecondsPerYear)), - // expect ~100% - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.999999999999999984"), - }, - { - name: "inflation enabled: realistic example", - bondedRatio: sdk.MustNewDecFromStr("0.148"), - inflation: sdk.MustNewDecFromStr("0.595"), - communityTax: sdk.MustNewDecFromStr("0.9495"), - rewardsPerSec: sdkmath.LegacyZeroDec(), - // expect ~20.23% - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.203023625910000000"), - }, - { - name: "inflation disabled: simple example", - bondedRatio: sdk.OneDec(), // bonded tokens are constant in this test. ratio has no affect. - inflation: sdk.ZeroDec(), - rewardsPerSec: sdkmath.LegacyMustNewDecFromStr("0.01"), - // 1e6 bonded tokens => seconds per year / bonded tokens = 31.536 - // expect 31.536% - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.31536"), - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - // set inflation - mk := suite.App.GetMintKeeper() - minter := mk.GetMinter(suite.Ctx) - minter.Inflation = tc.inflation - mk.SetMinter(suite.Ctx, minter) - - // set community tax - communityTax := sdk.ZeroDec() - if !tc.communityTax.IsNil() { - communityTax = tc.communityTax - } - dk := suite.App.GetDistrKeeper() - distParams := dk.GetParams(suite.Ctx) - distParams.CommunityTax = communityTax - dk.SetParams(suite.Ctx, distParams) - - // set staking rewards per second - ck := suite.App.GetCommunityKeeper() - commParams, _ := ck.GetParams(suite.Ctx) - commParams.StakingRewardsPerSecond = tc.rewardsPerSec - ck.SetParams(suite.Ctx, commParams) - - // set bonded tokens - suite.adjustBondedRatio(tc.bondedRatio) - - // query for annualized rewards - res, err := suite.queryClient.AnnualizedRewards(suite.Ctx, &types.QueryAnnualizedRewardsRequest{}) - // verify results match expected - suite.Require().NoError(err) - suite.Equal(tc.expectedRate, res.StakingRewards) - }) - } -} - -// adjustBondRatio changes the ratio of bonded coins -// it leverages the fact that there is a constant number of bonded tokens -// and adjusts the total supply to make change the bonded ratio. -// returns the new total supply of the bond denom -func (suite *grpcQueryTestSuite) adjustBondedRatio(desiredRatio sdk.Dec) sdkmath.Int { - // from the InitGenesis validator - bondedTokens := sdkmath.NewInt(1e6) - bondDenom := suite.App.GetStakingKeeper().BondDenom(suite.Ctx) - - // first, burn all non-delegated coins (bonded ratio = 100%) - suite.App.DeleteGenesisValidatorCoins(suite.T(), suite.Ctx) - - if desiredRatio.Equal(sdk.OneDec()) { - return bondedTokens - } - - // mint new tokens to adjust the bond ratio - newTotalSupply := sdk.NewDecFromInt(bondedTokens).Quo(desiredRatio).TruncateInt() - coinsToMint := newTotalSupply.Sub(bondedTokens) - err := suite.App.FundAccount(suite.Ctx, app.RandomAddress(), sdk.NewCoins(sdk.NewCoin(bondDenom, coinsToMint))) - suite.Require().NoError(err) - - return newTotalSupply -} diff --git a/x/community/keeper/keeper.go b/x/community/keeper/keeper.go deleted file mode 100644 index 0bf0bb8c..00000000 --- a/x/community/keeper/keeper.go +++ /dev/null @@ -1,132 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/community/types" -) - -// Keeper of the community store -type Keeper struct { - key storetypes.StoreKey - cdc codec.Codec - - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - cdpKeeper types.CdpKeeper - distrKeeper types.DistributionKeeper - hardKeeper types.HardKeeper - moduleAddress sdk.AccAddress - mintKeeper types.MintKeeper - kavadistKeeper types.KavadistKeeper - stakingKeeper types.StakingKeeper - - // the address capable of executing a MsgUpdateParams message. Typically, this - // should be the x/gov module account. - authority sdk.AccAddress - - legacyCommunityPoolAddress sdk.AccAddress -} - -// NewKeeper creates a new community Keeper instance -func NewKeeper( - cdc codec.Codec, - key storetypes.StoreKey, - ak types.AccountKeeper, - bk types.BankKeeper, - ck types.CdpKeeper, - dk types.DistributionKeeper, - hk types.HardKeeper, - mk types.MintKeeper, - kk types.KavadistKeeper, - sk types.StakingKeeper, - authority sdk.AccAddress, -) Keeper { - // ensure community module account is set - addr := ak.GetModuleAddress(types.ModuleAccountName) - if addr == nil { - panic(fmt.Sprintf("%s module account has not been set", types.ModuleAccountName)) - } - legacyAddr := ak.GetModuleAddress(types.LegacyCommunityPoolModuleName) - if addr == nil { - panic("legacy community pool address not found") - } - if err := sdk.VerifyAddressFormat(authority); err != nil { - panic(fmt.Sprintf("invalid authority address: %s", err)) - } - - return Keeper{ - key: key, - cdc: cdc, - - accountKeeper: ak, - bankKeeper: bk, - cdpKeeper: ck, - distrKeeper: dk, - hardKeeper: hk, - mintKeeper: mk, - kavadistKeeper: kk, - stakingKeeper: sk, - moduleAddress: addr, - - authority: authority, - legacyCommunityPoolAddress: legacyAddr, - } -} - -// GetAuthority returns the x/community module's authority. -func (k Keeper) GetAuthority() sdk.AccAddress { - return k.authority -} - -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", "x/"+types.ModuleName) -} - -// GetModuleAccountBalance returns all the coins held by the community module account -func (k Keeper) GetModuleAccountBalance(ctx sdk.Context) sdk.Coins { - return k.bankKeeper.GetAllBalances(ctx, k.moduleAddress) -} - -// FundCommunityPool transfers coins from the sender to the community module account. -func (k Keeper) FundCommunityPool(ctx sdk.Context, sender sdk.AccAddress, amount sdk.Coins) error { - return k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleAccountName, amount) -} - -// DistributeFromCommunityPool transfers coins from the community pool to recipient. -func (k Keeper) DistributeFromCommunityPool(ctx sdk.Context, recipient sdk.AccAddress, amount sdk.Coins) error { - return k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, recipient, amount) -} - -// GetStakingRewardsState returns the staking reward state or the default state if not set -func (k Keeper) GetStakingRewardsState(ctx sdk.Context) types.StakingRewardsState { - store := ctx.KVStore(k.key) - - b := store.Get(types.StakingRewardsStateKey) - if b == nil { - return types.DefaultStakingRewardsState() - } - - state := types.StakingRewardsState{} - k.cdc.MustUnmarshal(b, &state) - - return state -} - -// SetStakingRewardsState validates and sets the staking rewards state in the store -func (k Keeper) SetStakingRewardsState(ctx sdk.Context, state types.StakingRewardsState) { - if err := state.Validate(); err != nil { - panic(fmt.Sprintf("invalid state: %s", err)) - } - - store := ctx.KVStore(k.key) - b := k.cdc.MustMarshal(&state) - - store.Set(types.StakingRewardsStateKey, b) -} diff --git a/x/community/keeper/keeper_test.go b/x/community/keeper/keeper_test.go deleted file mode 100644 index 413603bb..00000000 --- a/x/community/keeper/keeper_test.go +++ /dev/null @@ -1,188 +0,0 @@ -package keeper_test - -import ( - "strings" - "testing" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/community/keeper" - "github.com/0glabs/0g-chain/x/community/testutil" - "github.com/0glabs/0g-chain/x/community/types" -) - -// Test suite used for all keeper tests -type KeeperTestSuite struct { - testutil.Suite -} - -// The default state used by each test -func (suite *KeeperTestSuite) SetupTest() { - suite.Suite.SetupTest() -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} - -func (suite *KeeperTestSuite) TestCommunityPool() { - suite.SetupTest() - maccAddr := suite.App.GetAccountKeeper().GetModuleAddress(types.ModuleAccountName) - - funds := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10000)), - sdk.NewCoin("usdx", sdkmath.NewInt(100)), - ) - sender := suite.CreateFundedAccount(funds) - - suite.Run("FundCommunityPool", func() { - err := suite.Keeper.FundCommunityPool(suite.Ctx, sender, funds) - suite.Require().NoError(err) - - // check that community pool received balance - suite.App.CheckBalance(suite.T(), suite.Ctx, maccAddr, funds) - suite.Equal(funds, suite.Keeper.GetModuleAccountBalance(suite.Ctx)) - // check that sender had balance deducted - suite.App.CheckBalance(suite.T(), suite.Ctx, sender, sdk.NewCoins()) - }) - - // send it back - suite.Run("DistributeFromCommunityPool - valid", func() { - err := suite.Keeper.DistributeFromCommunityPool(suite.Ctx, sender, funds) - suite.Require().NoError(err) - - // community pool has funds deducted - suite.App.CheckBalance(suite.T(), suite.Ctx, maccAddr, sdk.NewCoins()) - suite.Equal(sdk.NewCoins(), suite.Keeper.GetModuleAccountBalance(suite.Ctx)) - // receiver receives the funds - suite.App.CheckBalance(suite.T(), suite.Ctx, sender, funds) - }) - - // can't send more than we have! - suite.Run("DistributeFromCommunityPool - insufficient funds", func() { - suite.Equal(sdk.NewCoins(), suite.Keeper.GetModuleAccountBalance(suite.Ctx)) - err := suite.Keeper.DistributeFromCommunityPool(suite.Ctx, sender, funds) - suite.Require().ErrorContains(err, "insufficient funds") - }) -} - -func (suite *KeeperTestSuite) TestGetAndSetStakingRewardsState() { - keeper := suite.Keeper - - defaultParams := keeper.GetStakingRewardsState(suite.Ctx) - suite.Equal(time.Time{}, defaultParams.LastAccumulationTime, "expected default returned accumulation time to be zero") - suite.Equal(sdkmath.LegacyZeroDec(), defaultParams.LastTruncationError, "expected default truncation error to be zero") - - suite.NotPanics(func() { keeper.SetStakingRewardsState(suite.Ctx, defaultParams) }, "expected setting default state to not panic") - - invalidParams := defaultParams - invalidParams.LastTruncationError = sdkmath.LegacyDec{} - - suite.Panics(func() { keeper.SetStakingRewardsState(suite.Ctx, invalidParams) }, "expected setting invalid state to panic") - - validParams := defaultParams - validParams.LastAccumulationTime = time.Date(2023, 9, 29, 11, 42, 53, 123456789, time.UTC) - validParams.LastTruncationError = sdkmath.LegacyMustNewDecFromStr("0.50000000000000000") - - suite.NotPanics(func() { keeper.SetStakingRewardsState(suite.Ctx, validParams) }, "expected setting valid state to not panic") - - suite.Equal(validParams, keeper.GetStakingRewardsState(suite.Ctx), "expected fetched state to equal set state") -} - -func (suite *KeeperTestSuite) TestGetAuthority_Default() { - suite.Equal( - authtypes.NewModuleAddress(govtypes.ModuleName), - suite.Keeper.GetAuthority(), - "expected fetched authority to equal x/gov address", - ) -} - -func (suite *KeeperTestSuite) TestGetAuthority_Any() { - tests := []struct { - name string - authority sdk.AccAddress - }{ - { - name: "gov", - authority: authtypes.NewModuleAddress(govtypes.ModuleName), - }, - { - name: "random", - authority: sdk.AccAddress("random"), - }, - } - - for _, tc := range tests { - suite.Run(tc.name, func() { - suite.NotPanics(func() { - suite.Keeper = keeper.NewKeeper( - suite.App.AppCodec(), - suite.App.GetKVStoreKey(types.StoreKey), - suite.App.GetAccountKeeper(), - suite.App.GetBankKeeper(), - suite.App.GetCDPKeeper(), - suite.App.GetDistrKeeper(), - suite.App.GetHardKeeper(), - suite.App.GetMintKeeper(), - suite.App.GetKavadistKeeper(), - suite.App.GetStakingKeeper(), - tc.authority, - ) - }) - - suite.Equalf( - tc.authority, - suite.Keeper.GetAuthority(), - "expected fetched authority to equal %s address", - tc.authority, - ) - }) - } -} - -func (suite *KeeperTestSuite) TestNewKeeper_InvalidAuthority() { - tests := []struct { - name string - authority sdk.AccAddress - panicStr string - }{ - { - name: "empty", - authority: sdk.AccAddress{}, - panicStr: "invalid authority address: addresses cannot be empty: unknown address", - }, - { - name: "too long", - authority: sdk.AccAddress(strings.Repeat("a", address.MaxAddrLen+1)), - panicStr: "invalid authority address: address max length is 255, got 256: unknown address", - }, - } - - for _, tc := range tests { - suite.Run(tc.name, func() { - suite.PanicsWithValue( - tc.panicStr, - func() { - suite.Keeper = keeper.NewKeeper( - suite.App.AppCodec(), - suite.App.GetKVStoreKey(types.StoreKey), - suite.App.GetAccountKeeper(), - suite.App.GetBankKeeper(), - suite.App.GetCDPKeeper(), - suite.App.GetDistrKeeper(), - suite.App.GetHardKeeper(), - suite.App.GetMintKeeper(), - suite.App.GetKavadistKeeper(), - suite.App.GetStakingKeeper(), - tc.authority, - ) - }) - }) - } -} diff --git a/x/community/keeper/migrations.go b/x/community/keeper/migrations.go deleted file mode 100644 index a89cd7d9..00000000 --- a/x/community/keeper/migrations.go +++ /dev/null @@ -1,27 +0,0 @@ -package keeper - -import ( - v2 "github.com/0glabs/0g-chain/x/community/migrations/v2" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// Migrator is a struct for handling in-place store migrations. -type Migrator struct { - keeper Keeper -} - -// NewMigrator returns a new Migrator. -func NewMigrator(keeper Keeper) Migrator { - return Migrator{ - keeper: keeper, - } -} - -// Migrate1to2 migrates from version 1 to 2. -func (m Migrator) Migrate1to2(ctx sdk.Context) error { - return v2.Migrate( - ctx, - ctx.KVStore(m.keeper.key), - m.keeper.cdc, - ) -} diff --git a/x/community/keeper/msg_server.go b/x/community/keeper/msg_server.go deleted file mode 100644 index 02a27744..00000000 --- a/x/community/keeper/msg_server.go +++ /dev/null @@ -1,76 +0,0 @@ -package keeper - -import ( - "context" - - "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - - "github.com/0glabs/0g-chain/x/community/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the community MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -// FundCommunityPool handles FundCommunityPool msgs. -func (s msgServer) FundCommunityPool(goCtx context.Context, msg *types.MsgFundCommunityPool) (*types.MsgFundCommunityPoolResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - - // above validation will fail if depositor is invalid - depositor := sdk.MustAccAddressFromBech32(msg.Depositor) - - if err := s.keeper.FundCommunityPool(ctx, depositor, msg.Amount); err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeyAction, types.AttributeValueFundCommunityPool), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Depositor), - sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), - ), - ) - - return &types.MsgFundCommunityPoolResponse{}, nil -} - -// UpdateParams handles UpdateParams msgs. -func (s msgServer) UpdateParams( - goCtx context.Context, - msg *types.MsgUpdateParams, -) (*types.MsgUpdateParamsResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if s.keeper.GetAuthority().String() != msg.Authority { - return nil, errors.Wrapf( - govtypes.ErrInvalidSigner, - "invalid authority; expected %s, got %s", - s.keeper.GetAuthority(), - msg.Authority, - ) - } - - if err := msg.Params.Validate(); err != nil { - return nil, errors.Wrap(types.ErrInvalidParams, err.Error()) - } - - s.keeper.SetParams(ctx, msg.Params) - - return &types.MsgUpdateParamsResponse{}, nil -} diff --git a/x/community/keeper/msg_server_test.go b/x/community/keeper/msg_server_test.go deleted file mode 100644 index a3bdc8fe..00000000 --- a/x/community/keeper/msg_server_test.go +++ /dev/null @@ -1,170 +0,0 @@ -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" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/community/keeper" - "github.com/0glabs/0g-chain/x/community/testutil" - "github.com/0glabs/0g-chain/x/community/types" -) - -type msgServerTestSuite struct { - testutil.Suite - - communityPool sdk.AccAddress - msgServer types.MsgServer -} - -func (suite *msgServerTestSuite) SetupTest() { - suite.Suite.SetupTest() - - suite.communityPool = suite.App.GetAccountKeeper().GetModuleAddress(types.ModuleAccountName) - suite.msgServer = keeper.NewMsgServerImpl(suite.Keeper) -} - -func TestMsgServerTestSuite(t *testing.T) { - suite.Run(t, new(msgServerTestSuite)) -} - -func (suite *msgServerTestSuite) TestMsgFundCommunityPool() { - singleCoin := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(2e6))) - multipleCoins := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(3e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(1e7)), - ) - testCases := []struct { - name string - setup func() *types.MsgFundCommunityPool - expectedBalance sdk.Coins - shouldPass bool - }{ - { - name: "valid funding of single coin", - setup: func() *types.MsgFundCommunityPool { - sender := app.RandomAddress() - suite.App.FundAccount(suite.Ctx, sender, singleCoin) - return &types.MsgFundCommunityPool{ - Amount: singleCoin, - Depositor: sender.String(), - } - }, - expectedBalance: singleCoin, - shouldPass: true, - }, - { - name: "valid funding of multiple coins", - setup: func() *types.MsgFundCommunityPool { - sender := app.RandomAddress() - suite.App.FundAccount(suite.Ctx, sender, multipleCoins) - return &types.MsgFundCommunityPool{ - Amount: multipleCoins, - Depositor: sender.String(), - } - }, - expectedBalance: multipleCoins, - shouldPass: true, - }, - { - name: "invalid - failing message validation", - setup: func() *types.MsgFundCommunityPool { - return &types.MsgFundCommunityPool{ - Amount: sdk.NewCoins(), - Depositor: app.RandomAddress().String(), - } - }, - expectedBalance: sdk.NewCoins(), - shouldPass: false, - }, - { - name: "invalid - failing tx, insufficient funds", - setup: func() *types.MsgFundCommunityPool { - return &types.MsgFundCommunityPool{ - Amount: singleCoin, - Depositor: app.RandomAddress().String(), - } - }, - expectedBalance: sdk.NewCoins(), - shouldPass: false, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - msg := tc.setup() - _, err := suite.msgServer.FundCommunityPool(sdk.WrapSDKContext(suite.Ctx), msg) - if tc.shouldPass { - suite.NoError(err) - } else { - suite.Error(err) - } - - balance := suite.Keeper.GetModuleAccountBalance(suite.Ctx) - suite.App.CheckBalance(suite.T(), suite.Ctx, suite.communityPool, balance) - }) - } -} - -func (suite *msgServerTestSuite) TestMsgUpdateParams() { - govAddr := authtypes.NewModuleAddress(govtypes.ModuleName) - - testCases := []struct { - name string - msg types.MsgUpdateParams - expectedError error - }{ - { - name: "valid", - msg: types.MsgUpdateParams{ - Authority: govAddr.String(), - Params: types.DefaultParams(), - }, - expectedError: nil, - }, - { - name: "invalid - bad authority", - msg: types.MsgUpdateParams{ - Authority: sdk.AccAddress{1, 2, 3}.String(), - Params: types.DefaultParams(), - }, - expectedError: govtypes.ErrInvalidSigner, - }, - { - name: "invalid - empty authority", - msg: types.MsgUpdateParams{ - Authority: "", - Params: types.DefaultParams(), - }, - expectedError: govtypes.ErrInvalidSigner, - }, - { - name: "invalid - parameters", - msg: types.MsgUpdateParams{ - Authority: govAddr.String(), - Params: types.Params{}, - }, - expectedError: types.ErrInvalidParams, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - _, err := suite.msgServer.UpdateParams(sdk.WrapSDKContext(suite.Ctx), &tc.msg) - if tc.expectedError == nil { - suite.NoError(err) - } else { - suite.ErrorIs(err, tc.expectedError) - } - }) - } -} diff --git a/x/community/keeper/params.go b/x/community/keeper/params.go deleted file mode 100644 index 4c3c6e90..00000000 --- a/x/community/keeper/params.go +++ /dev/null @@ -1,45 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/community/types" -) - -// GetParams returns the params from the store -func (k Keeper) GetParams(ctx sdk.Context) (types.Params, bool) { - store := ctx.KVStore(k.key) - - bz := store.Get(types.ParamsKey) - if bz == nil { - return types.Params{}, false - } - - params := types.Params{} - k.cdc.MustUnmarshal(bz, ¶ms) - - return params, true -} - -// SetParams sets params on the store -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - if err := params.Validate(); err != nil { - panic(fmt.Sprintf("invalid params: %s", err)) - } - - store := ctx.KVStore(k.key) - bz := k.cdc.MustMarshal(¶ms) - - store.Set(types.ParamsKey, bz) -} - -func (k Keeper) mustGetParams(ctx sdk.Context) types.Params { - params, found := k.GetParams(ctx) - if !found { - panic("invalid state: module parameters not found") - } - - return params -} diff --git a/x/community/keeper/params_test.go b/x/community/keeper/params_test.go deleted file mode 100644 index e16e19e4..00000000 --- a/x/community/keeper/params_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/community/keeper" - "github.com/0glabs/0g-chain/x/community/types" -) - -// Test suite used for all store tests -type StoreTestSuite struct { - suite.Suite - - App app.TestApp - Ctx sdk.Context - Keeper keeper.Keeper -} - -// The default state used by each test -func (suite *StoreTestSuite) SetupTest() { - app.SetSDKConfig() - suite.App = app.NewTestApp() - suite.Ctx = suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - suite.Keeper = suite.App.GetCommunityKeeper() -} - -func TestStoreTestSuite(t *testing.T) { - suite.Run(t, new(StoreTestSuite)) -} - -func (suite *StoreTestSuite) TestGetSetParams() { - suite.Run("get params returns not found on empty store", func() { - _, found := suite.Keeper.GetParams(suite.Ctx) - suite.Require().False(found) - }) - - suite.Run("set params cannot store invalid params", func() { - invalid := types.Params{UpgradeTimeDisableInflation: time.Date(-1, 1, 1, 0, 0, 0, 0, time.UTC)} - suite.Panics(func() { - suite.Keeper.SetParams(suite.Ctx, invalid) - }) - }) - - suite.Run("get params returns stored params", func() { - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) - - storedParams, found := suite.Keeper.GetParams(suite.Ctx) - suite.True(found) - suite.Equal(types.DefaultParams(), storedParams) - }) - - suite.Run("set overwrite previous value", func() { - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) - - params := types.NewParams( - time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - sdkmath.LegacyNewDec(1000), - sdkmath.LegacyNewDec(1000), - ) - suite.Keeper.SetParams(suite.Ctx, params) - - storedParams, found := suite.Keeper.GetParams(suite.Ctx) - suite.True(found) - suite.NotEqual(params, types.DefaultParams()) - suite.Equal(params, storedParams) - }) -} diff --git a/x/community/keeper/proposal_handler.go b/x/community/keeper/proposal_handler.go deleted file mode 100644 index 74f5e74f..00000000 --- a/x/community/keeper/proposal_handler.go +++ /dev/null @@ -1,41 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/community/types" -) - -// HandleCommunityPoolLendDepositProposal is a handler for executing a passed community pool lend deposit proposal. -func HandleCommunityPoolLendDepositProposal(ctx sdk.Context, k Keeper, p *types.CommunityPoolLendDepositProposal) error { - // move funds from community pool to x/community so hard position is held by this module. - err := k.distrKeeper.DistributeFromFeePool(ctx, p.Amount, k.moduleAddress) - if err != nil { - return err - } - // deposit funds into hard - return k.hardKeeper.Deposit(ctx, k.moduleAddress, p.Amount) -} - -// HandleCommunityPoolLendWithdrawProposal is a handler for executing a passed community pool lend withdraw proposal. -func HandleCommunityPoolLendWithdrawProposal(ctx sdk.Context, k Keeper, p *types.CommunityPoolLendWithdrawProposal) error { - // withdraw funds from x/hard to this module account - return k.hardKeeper.Withdraw(ctx, k.moduleAddress, p.Amount) -} - -// HandleCommunityCDPRepayDebtProposal is a handler for executing a passed community pool cdp repay debt proposal. -func HandleCommunityCDPRepayDebtProposal(ctx sdk.Context, k Keeper, p *types.CommunityCDPRepayDebtProposal) error { - // make debt repayment - return k.cdpKeeper.RepayPrincipal(ctx, k.moduleAddress, p.CollateralType, p.Payment) -} - -// HandleCommunityCDPWithdrawCollateralProposal is a handler for executing a -// passed community pool cdp withdraw collateral proposal. -func HandleCommunityCDPWithdrawCollateralProposal( - ctx sdk.Context, - k Keeper, - p *types.CommunityCDPWithdrawCollateralProposal, -) error { - // withdraw collateral - return k.cdpKeeper.WithdrawCollateral(ctx, k.moduleAddress, k.moduleAddress, p.Collateral, p.CollateralType) -} diff --git a/x/community/keeper/proposal_handler_test.go b/x/community/keeper/proposal_handler_test.go deleted file mode 100644 index 2da2fbda..00000000 --- a/x/community/keeper/proposal_handler_test.go +++ /dev/null @@ -1,562 +0,0 @@ -package keeper_test - -import ( - "fmt" - "testing" - "time" - - sdkmath "cosmossdk.io/math" - abcitypes "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/app" - cdpkeeper "github.com/0glabs/0g-chain/x/cdp/keeper" - "github.com/0glabs/0g-chain/x/community/keeper" - "github.com/0glabs/0g-chain/x/community/testutil" - "github.com/0glabs/0g-chain/x/community/types" - hardkeeper "github.com/0glabs/0g-chain/x/hard/keeper" - hardtypes "github.com/0glabs/0g-chain/x/hard/types" - pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" -) - -const chainID = app.TestChainId - -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } -func ukava(amt int64) sdk.Coins { - return sdk.NewCoins(c("ukava", amt)) -} - -func usdx(amt int64) sdk.Coins { - return sdk.NewCoins(c("usdx", amt)) -} - -func otherdenom(amt int64) sdk.Coins { - return sdk.NewCoins(c("other-denom", amt)) -} - -type proposalTestSuite struct { - suite.Suite - - App app.TestApp - Ctx sdk.Context - Keeper keeper.Keeper - MaccAddress sdk.AccAddress - - cdpKeeper cdpkeeper.Keeper - hardKeeper hardkeeper.Keeper -} - -func TestProposalTestSuite(t *testing.T) { - suite.Run(t, new(proposalTestSuite)) -} - -func (suite *proposalTestSuite) SetupTest() { - app.SetSDKConfig() - - genTime := tmtime.Now() - - hardGS, pricefeedGS := testutil.NewLendGenesisBuilder(). - WithMarket("ukava", "kava:usd", sdk.OneDec()). - WithMarket("usdx", "usdx:usd", sdk.OneDec()). - Build() - - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{ - Height: 1, - Time: genTime, - ChainID: chainID, - }) - - // Set UpgradeTimeDisableInflation to far future to not influence module - // account balances - params := types.Params{ - UpgradeTimeDisableInflation: time.Now().Add(100000 * time.Hour), - StakingRewardsPerSecond: sdkmath.LegacyNewDec(0), - } - communityGs := types.NewGenesisState(params, types.DefaultStakingRewardsState()) - - tApp.InitializeFromGenesisStatesWithTimeAndChainID( - genTime, chainID, - app.GenesisState{hardtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&communityGs)}, - testutil.NewCDPGenState(tApp.AppCodec(), "ukava", "kava", sdk.NewDec(2)), - ) - - suite.App = tApp - suite.Ctx = ctx - suite.Keeper = tApp.GetCommunityKeeper() - suite.MaccAddress = tApp.GetAccountKeeper().GetModuleAddress(types.ModuleAccountName) - suite.cdpKeeper = suite.App.GetCDPKeeper() - suite.hardKeeper = suite.App.GetHardKeeper() - - // give the community pool some funds - // ukava - suite.FundCommunityPool(ukava(2e10)) - // usdx - suite.FundCommunityPool(usdx(2e10)) - // other-denom - suite.FundCommunityPool(otherdenom(1e10)) -} - -func (suite *proposalTestSuite) NextBlock() { - newTime := suite.Ctx.BlockTime().Add(6 * time.Second) - newHeight := suite.Ctx.BlockHeight() + 1 - - suite.App.EndBlocker(suite.Ctx, abcitypes.RequestEndBlock{}) - suite.Ctx = suite.Ctx.WithBlockTime(newTime).WithBlockHeight(newHeight).WithChainID(chainID) - suite.App.BeginBlocker(suite.Ctx, abcitypes.RequestBeginBlock{}) -} - -func (suite *proposalTestSuite) FundCommunityPool(coins sdk.Coins) { - // mint to ephemeral account - ephemeralAcc := app.RandomAddress() - suite.NoError(suite.App.FundAccount(suite.Ctx, ephemeralAcc, coins)) - // fund community pool with newly minted coins - suite.NoError(suite.App.GetDistrKeeper().FundCommunityPool(suite.Ctx, coins, ephemeralAcc)) -} - -func (suite *proposalTestSuite) GetCommunityPoolBalance() sdk.Coins { - ak := suite.App.GetAccountKeeper() - bk := suite.App.GetBankKeeper() - - addr := ak.GetModuleAddress(types.ModuleAccountName) - - // Return x/community module account balance, no longer using x/distribution community pool - return bk.GetAllBalances(suite.Ctx, addr) -} - -func (suite *proposalTestSuite) CheckCommunityPoolBalance(expected sdk.Coins) { - actual := suite.GetCommunityPoolBalance() - // check that balance is expected - suite.True(expected.IsEqual(actual), fmt.Sprintf("unexpected balance in community pool\nexpected: %s\nactual: %s", expected, actual)) -} - -func (suite *proposalTestSuite) TestCommunityLendDepositProposal() { - testCases := []struct { - name string - proposals []*types.CommunityPoolLendDepositProposal - expectedErr string - expectedDeposits []sdk.Coins - }{ - { - name: "valid - one proposal, one denom", - proposals: []*types.CommunityPoolLendDepositProposal{ - {Amount: ukava(1e8)}, - }, - expectedErr: "", - expectedDeposits: []sdk.Coins{ukava(1e8)}, - }, - { - name: "valid - one proposal, multiple denoms", - proposals: []*types.CommunityPoolLendDepositProposal{ - {Amount: ukava(1e8).Add(usdx(1e8)...)}, - }, - expectedErr: "", - expectedDeposits: []sdk.Coins{ukava(1e8).Add(usdx(1e8)...)}, - }, - { - name: "valid - multiple proposals, same denom", - proposals: []*types.CommunityPoolLendDepositProposal{ - {Amount: ukava(1e8)}, - {Amount: ukava(1e9)}, - }, - expectedErr: "", - expectedDeposits: []sdk.Coins{ukava(1e8 + 1e9)}, - }, - { - name: "valid - multiple proposals, different denoms", - proposals: []*types.CommunityPoolLendDepositProposal{ - {Amount: ukava(1e8)}, - {Amount: usdx(1e8)}, - }, - expectedErr: "", - expectedDeposits: []sdk.Coins{ukava(1e8).Add(usdx(1e8)...)}, - }, - { - name: "invalid - insufficient balance", - proposals: []*types.CommunityPoolLendDepositProposal{ - { - Description: "more coins than i have!", - Amount: ukava(1e11), - }, - }, - expectedErr: "community pool does not have sufficient coins to distribute", - expectedDeposits: []sdk.Coins{}, - }, - { - name: "invalid - invalid lend deposit (unsupported denom)", - proposals: []*types.CommunityPoolLendDepositProposal{ - {Amount: otherdenom(1e9)}, - }, - expectedErr: "invalid deposit denom", - expectedDeposits: []sdk.Coins{}, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - for _, proposal := range tc.proposals { - err := keeper.HandleCommunityPoolLendDepositProposal(suite.Ctx, suite.Keeper, proposal) - if tc.expectedErr == "" { - suite.NoError(err) - } else { - suite.ErrorContains(err, tc.expectedErr) - } - } - - deposits := suite.hardKeeper.GetDepositsByUser(suite.Ctx, suite.MaccAddress) - suite.Len(deposits, len(tc.expectedDeposits), "expected a deposit to lend") - for _, amt := range tc.expectedDeposits { - suite.Equal(amt, deposits[0].Amount, "expected amount to match") - } - }) - } -} - -func (suite *proposalTestSuite) TestCommunityLendWithdrawProposal() { - testCases := []struct { - name string - initialDeposit sdk.Coins - proposals []*types.CommunityPoolLendWithdrawProposal - expectedErr string - expectedWithdrawal sdk.Coins - }{ - { - // in the week it would take a proposal to pass, the position would have grown - // to withdraw the entire position, it'd be safest to set a very high withdraw - name: "valid - requesting withdrawal of more than total will withdraw all", - initialDeposit: ukava(1e9), - proposals: []*types.CommunityPoolLendWithdrawProposal{ - {Amount: ukava(1e12)}, - }, - expectedErr: "", - expectedWithdrawal: ukava(1e9), - }, - { - name: "valid - single proposal, single denom, full withdrawal", - initialDeposit: ukava(1e9), - proposals: []*types.CommunityPoolLendWithdrawProposal{ - {Amount: ukava(1e9)}, - }, - expectedErr: "", - expectedWithdrawal: ukava(1e9), - }, - { - name: "valid - single proposal, multiple denoms, full withdrawal", - initialDeposit: ukava(1e9).Add(usdx(1e9)...), - proposals: []*types.CommunityPoolLendWithdrawProposal{ - {Amount: ukava(1e9).Add(usdx(1e9)...)}, - }, - expectedErr: "", - expectedWithdrawal: ukava(1e9).Add(usdx(1e9)...), - }, - { - name: "valid - single proposal, partial withdrawal", - initialDeposit: ukava(1e9).Add(usdx(1e9)...), - proposals: []*types.CommunityPoolLendWithdrawProposal{ - {Amount: ukava(1e8).Add(usdx(1e9)...)}, - }, - expectedErr: "", - expectedWithdrawal: ukava(1e8).Add(usdx(1e9)...), - }, - { - name: "valid - multiple proposals, full withdrawal", - initialDeposit: ukava(1e9).Add(usdx(1e9)...), - proposals: []*types.CommunityPoolLendWithdrawProposal{ - {Amount: ukava(1e9)}, - {Amount: usdx(1e9)}, - }, - expectedErr: "", - expectedWithdrawal: ukava(1e9).Add(usdx(1e9)...), - }, - { - name: "valid - multiple proposals, partial withdrawal", - initialDeposit: ukava(1e9).Add(usdx(1e9)...), - proposals: []*types.CommunityPoolLendWithdrawProposal{ - {Amount: ukava(1e8)}, - {Amount: usdx(1e8)}, - }, - expectedErr: "", - expectedWithdrawal: ukava(1e8).Add(usdx(1e8)...), - }, - { - name: "invalid - nonexistent position, has no deposits", - initialDeposit: sdk.NewCoins(), - proposals: []*types.CommunityPoolLendWithdrawProposal{ - {Amount: ukava(1e8)}, - }, - expectedErr: "deposit not found", - expectedWithdrawal: sdk.NewCoins(), - }, - { - name: "invalid - nonexistent position, has deposits of different denom", - initialDeposit: ukava(1e8), - proposals: []*types.CommunityPoolLendWithdrawProposal{ - {Amount: usdx(1e8)}, - }, - expectedErr: "no coins of this type deposited", - expectedWithdrawal: sdk.NewCoins(), - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - // Disable minting, so that the community pool balance doesn't change - // during the test - this is because staking denom is "ukava" and no - // longer "stake" which has an initial and changing balance instead - // of just 0 - suite.App.SetInflation(suite.Ctx, sdk.ZeroDec()) - - // setup initial deposit - if !tc.initialDeposit.IsZero() { - deposit := types.NewCommunityPoolLendDepositProposal("initial deposit", "has coins", tc.initialDeposit) - err := keeper.HandleCommunityPoolLendDepositProposal(suite.Ctx, suite.Keeper, deposit) - suite.NoError(err, "unexpected error while seeding lend deposit") - } - - beforeBalance := suite.GetCommunityPoolBalance() - - // run the proposals - for i, proposal := range tc.proposals { - fmt.Println("submitting proposal ", i, " ", suite.Ctx.ChainID()) - err := keeper.HandleCommunityPoolLendWithdrawProposal(suite.Ctx, suite.Keeper, proposal) - if tc.expectedErr == "" { - suite.NoError(err) - } else { - suite.ErrorContains(err, tc.expectedErr) - } - - suite.NextBlock() - } - - // expect funds to be removed from hard deposit - expectedRemaining := tc.initialDeposit.Sub(tc.expectedWithdrawal...) - deposits := suite.hardKeeper.GetDepositsByUser(suite.Ctx, suite.MaccAddress) - if expectedRemaining.IsZero() { - suite.Len(deposits, 0, "expected all deposits to be withdrawn") - } else { - suite.Len(deposits, 1, "expected user to have remaining deposit") - suite.Equal(expectedRemaining, deposits[0].Amount) - } - - // expect funds to be distributed back to community pool - suite.CheckCommunityPoolBalance(beforeBalance.Add(tc.expectedWithdrawal...)) - }) - } -} - -// expectation: funds in the community module will be used to repay cdps. -// if collateral is returned, it stays in the community module. -func (suite *proposalTestSuite) TestCommunityCDPRepayDebtProposal() { - initialModuleFunds := ukava(2e10).Add(otherdenom(1e9)...) - collateralType := "kava-a" - type debt struct { - collateral sdk.Coin - principal sdk.Coin - } - testcases := []struct { - name string - initialDebt *debt - proposal *types.CommunityCDPRepayDebtProposal - expectedErr string - expectedRepaid sdk.Coin - }{ - { - name: "valid - paid in full", - initialDebt: &debt{c("ukava", 1e10), c("usdx", 1e9)}, - proposal: types.NewCommunityCDPRepayDebtProposal( - "repaying my debts in full", - "title says it all", - collateralType, - c("usdx", 1e9), - ), - expectedErr: "", - expectedRepaid: c("usdx", 1e9), - }, - { - name: "valid - partial payment", - initialDebt: &debt{c("ukava", 1e10), c("usdx", 1e9)}, - proposal: types.NewCommunityCDPRepayDebtProposal( - "title goes here", - "description goes here", - collateralType, - c("usdx", 1e8), - ), - expectedErr: "", - expectedRepaid: c("usdx", 1e8), - }, - { - name: "invalid - insufficient funds", - initialDebt: &debt{c("ukava", 1e10), c("usdx", 1e9)}, - proposal: types.NewCommunityCDPRepayDebtProposal( - "title goes here", - "description goes here", - collateralType, - c("usdx", 1e10), // <-- more usdx than we have - ), - expectedErr: "insufficient balance", - expectedRepaid: c("usdx", 0), - }, - } - - for _, tc := range testcases { - suite.Run(tc.name, func() { - var err error - suite.SetupTest() - - // setup the community module with some initial funds - err = suite.App.FundModuleAccount(suite.Ctx, types.ModuleAccountName, initialModuleFunds) - suite.NoError(err, "failed to initially fund module account for cdp creation") - - // setup initial debt position - err = suite.cdpKeeper.AddCdp(suite.Ctx, suite.MaccAddress, tc.initialDebt.collateral, tc.initialDebt.principal, collateralType) - suite.NoError(err, "unexpected error while creating initial cdp") - - balanceBefore := suite.Keeper.GetModuleAccountBalance(suite.Ctx) - - // submit proposal - err = keeper.HandleCommunityCDPRepayDebtProposal(suite.Ctx, suite.Keeper, tc.proposal) - if tc.expectedErr == "" { - suite.NoError(err) - } else { - suite.ErrorContains(err, tc.expectedErr) - } - suite.NextBlock() - - cdps := suite.cdpKeeper.GetAllCdpsByCollateralType(suite.Ctx, collateralType) - expectedRemainingPrincipal := tc.initialDebt.principal.Sub(tc.expectedRepaid) - fullyRepaid := expectedRemainingPrincipal.IsZero() - - // expect repayment funds to be deducted from community module account - expectedModuleBalance := balanceBefore.Sub(tc.expectedRepaid) - // when fully repaid, the position is closed and collateral is returned. - if fullyRepaid { - suite.Len(cdps, 0, "expected position to have been closed on payment") - // expect balance to include recouped collateral - expectedModuleBalance = expectedModuleBalance.Add(tc.initialDebt.collateral) - } else { - suite.Len(cdps, 1, "expected debt position to remain open") - suite.Equal(suite.MaccAddress, cdps[0].Owner, "sanity check: unexpected owner") - // check the remaining principle on the cdp - suite.Equal(expectedRemainingPrincipal, cdps[0].Principal) - } - - // verify the balance changed as expected - moduleBalanceAfter := suite.Keeper.GetModuleAccountBalance(suite.Ctx) - suite.True(expectedModuleBalance.IsEqual(moduleBalanceAfter), "module balance changed unexpectedly") - }) - } -} - -// expectation: funds in the community module used as cdp collateral will be -// withdrawn and stays in the community module. -func (suite *proposalTestSuite) TestCommunityCDPWithdrawCollateralProposal() { - initialModuleFunds := ukava(2e10).Add(otherdenom(1e9)...) - collateralType := "kava-a" - type debt struct { - collateral sdk.Coin - principal sdk.Coin - } - testcases := []struct { - name string - initialDebt *debt - proposal *types.CommunityCDPWithdrawCollateralProposal - expectedErr string - expectedWithdrawn sdk.Coin - }{ - { - name: "valid - withdrawing max collateral", - initialDebt: &debt{ - c("ukava", 1e10), - c("usdx", 1e9), - }, - proposal: types.NewCommunityCDPWithdrawCollateralProposal( - "withdrawing max collateral", - "i might get liquidated", - collateralType, - c("ukava", 8e9-1), // Withdraw all collateral except 2*principal-1 amount - ), - expectedErr: "", - expectedWithdrawn: c("ukava", 8e9-1), - }, - { - name: "valid - withdrawing partial collateral", - initialDebt: &debt{ - c("ukava", 1e10), - c("usdx", 1e9), - }, - proposal: types.NewCommunityCDPWithdrawCollateralProposal( - "title goes here", - "description goes here", - collateralType, - c("ukava", 1e9), - ), - expectedErr: "", - expectedWithdrawn: c("ukava", 1e9), - }, - { - name: "invalid - withdrawing too much collateral", - initialDebt: &debt{ - c("ukava", 1e10), - c("usdx", 1e9), - }, - proposal: types.NewCommunityCDPWithdrawCollateralProposal( - "title goes here", - "description goes here", - collateralType, - c("ukava", 9e9), // <-- would be under collateralized - ), - expectedErr: "proposed collateral ratio is below liquidation ratio", - expectedWithdrawn: c("ukava", 0), - }, - } - - for _, tc := range testcases { - suite.Run(tc.name, func() { - var err error - suite.SetupTest() - - // setup the community module with some initial funds - err = suite.App.FundModuleAccount(suite.Ctx, types.ModuleAccountName, initialModuleFunds) - suite.NoError(err, "failed to initially fund module account for cdp creation") - - // setup initial debt position - err = suite.cdpKeeper.AddCdp(suite.Ctx, suite.MaccAddress, tc.initialDebt.collateral, tc.initialDebt.principal, collateralType) - suite.NoError(err, "unexpected error while creating initial cdp") - - balanceBefore := suite.Keeper.GetModuleAccountBalance(suite.Ctx) - - // submit proposal - err = keeper.HandleCommunityCDPWithdrawCollateralProposal(suite.Ctx, suite.Keeper, tc.proposal) - if tc.expectedErr == "" { - suite.NoError(err) - } else { - suite.Require().ErrorContains(err, tc.expectedErr) - } - suite.NextBlock() - - cdps := suite.cdpKeeper.GetAllCdpsByCollateralType(suite.Ctx, collateralType) - expectedRemainingCollateral := tc.initialDebt.collateral.Sub(tc.expectedWithdrawn) - - // expect withdrawn funds to add to community module account - expectedModuleBalance := balanceBefore.Add(tc.expectedWithdrawn) - - suite.Len(cdps, 1, "expected debt position to remain open") - suite.Equal(suite.MaccAddress, cdps[0].Owner, "sanity check: unexpected owner") - // check the remaining principle on the cdp - suite.Equal(expectedRemainingCollateral, cdps[0].Collateral) - - // verify the balance changed as expected - moduleBalanceAfter := suite.Keeper.GetModuleAccountBalance(suite.Ctx) - suite.True(expectedModuleBalance.IsEqual(moduleBalanceAfter), "module balance changed unexpectedly") - }) - } -} diff --git a/x/community/keeper/rewards.go b/x/community/keeper/rewards.go deleted file mode 100644 index 1f9198a3..00000000 --- a/x/community/keeper/rewards.go +++ /dev/null @@ -1,27 +0,0 @@ -package keeper - -import ( - sdkmath "cosmossdk.io/math" -) - -const SecondsPerYear = 365 * 24 * 3600 - -// CalculateStakingAnnualPercentage returns the annualized staking reward rate. -// It assumes that staking comes from one of two sources depending on if inflation is enabled or not. -func CalculateStakingAnnualPercentage(totalSupply, totalBonded sdkmath.Int, inflationRate, communityTax, rewardsPerSecond sdkmath.LegacyDec) sdkmath.LegacyDec { - // no rewards are given if no tokens are bonded, in addition avoid division by zero - if totalBonded.IsZero() { - return sdkmath.LegacyZeroDec() - } - - // the percent of inflationRate * totalSupply tokens that are distributed to stakers - percentInflationDistributedToStakers := sdkmath.LegacyOneDec().Sub(communityTax) - - // the total amount of tokens distributed to stakers in a year - amountGivenPerYear := inflationRate. - MulInt(totalSupply).Mul(percentInflationDistributedToStakers). // portion provided by inflation via mint & distribution modules - Add(rewardsPerSecond.Mul(sdkmath.LegacyNewDec(SecondsPerYear))) // portion provided by community module - - // divide by total bonded tokens to get the percent return - return amountGivenPerYear.QuoInt(totalBonded) -} diff --git a/x/community/keeper/rewards_test.go b/x/community/keeper/rewards_test.go deleted file mode 100644 index 45ea6bbe..00000000 --- a/x/community/keeper/rewards_test.go +++ /dev/null @@ -1,189 +0,0 @@ -package keeper_test - -import ( - "math/big" - "testing" - - sdkmath "cosmossdk.io/math" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/community/keeper" -) - -func TestStakingRewardsCalculator(t *testing.T) { - hugeInflation := new(big.Int).Exp(big.NewInt(2), big.NewInt(205), nil) - hugeRewardsPerSec := new(big.Int).Exp(big.NewInt(2), big.NewInt(230), nil) - - testCases := []struct { - name string - totalSupply sdkmath.Int - totalBonded sdkmath.Int - inflation sdkmath.LegacyDec - communityTax sdkmath.LegacyDec - perSecReward sdkmath.LegacyDec - expectedRate sdkmath.LegacyDec - }{ - { - name: "no inflation, no rewards per sec -> 0%", - totalSupply: sdkmath.ZeroInt(), - totalBonded: sdkmath.ZeroInt(), - inflation: sdkmath.LegacyZeroDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyZeroDec(), - expectedRate: sdkmath.LegacyZeroDec(), - }, - // - // - // inflation-only - // - // - { - name: "inflation only: no bonded tokens -> 0%", - totalSupply: sdk.NewInt(42), - totalBonded: sdkmath.ZeroInt(), - inflation: sdkmath.LegacyOneDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyZeroDec(), - expectedRate: sdkmath.LegacyZeroDec(), - }, - { - name: "inflation only: 0% inflation -> 0%", - totalSupply: sdk.NewInt(123), - totalBonded: sdkmath.NewInt(45), - inflation: sdkmath.LegacyZeroDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyZeroDec(), - expectedRate: sdkmath.LegacyZeroDec(), - }, - { - name: "inflation only: 100% bonded w/ 100% inflation -> 100%", - totalSupply: sdk.NewInt(42), - totalBonded: sdk.NewInt(42), - inflation: sdkmath.LegacyOneDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyZeroDec(), - expectedRate: sdkmath.LegacyOneDec(), - }, - { - name: "inflation only: 100% community tax -> 0%", - totalSupply: sdk.NewInt(123), - totalBonded: sdkmath.NewInt(45), - inflation: sdkmath.LegacyMustNewDecFromStr("0.853"), - communityTax: sdkmath.LegacyOneDec(), - perSecReward: sdkmath.LegacyZeroDec(), - expectedRate: sdkmath.LegacyZeroDec(), - }, - { - name: "inflation only: Oct 2023 case", - totalSupply: sdk.NewInt(857570000e6), - totalBonded: sdk.NewInt(127680000e6), - inflation: sdkmath.LegacyMustNewDecFromStr("0.595"), - communityTax: sdkmath.LegacyMustNewDecFromStr("0.9495"), - perSecReward: sdkmath.LegacyZeroDec(), - // expect 20.18% staking reward - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.201815746984649122"), // verified manually - }, - { - name: "inflation only: low inflation", - totalSupply: sdk.NewInt(857570000e6), - totalBonded: sdk.NewInt(127680000e6), - inflation: sdkmath.LegacyMustNewDecFromStr("0.0000000001"), - communityTax: sdkmath.LegacyMustNewDecFromStr("0.9495"), - perSecReward: sdkmath.LegacyZeroDec(), - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.000000000033918612"), // verified manually, rounded would be 0.000000000033918613 - }, - { - name: "inflation only: absurdly high inflation", - totalSupply: sdk.NewInt(857570000e6), - totalBonded: sdk.NewInt(127680000e6), - inflation: sdkmath.LegacyNewDecFromBigInt(hugeInflation), // 2^205. a higher exponent than this overflows. - communityTax: sdkmath.LegacyMustNewDecFromStr("0.9495"), - perSecReward: sdkmath.LegacyZeroDec(), - // https://www.wolframalpha.com/input?i=%282%5E205%29+*+%281+-+0.9495%29+*+%28857570000e6+%2F127680000e6%29 - expectedRate: sdkmath.LegacyMustNewDecFromStr("17441635052648297161685283657196753398188161373334495592570113.113824561403508771"), // verified manually, would round up - }, - // - // - // rewards-only - // - // - { - name: "rps only: no bonded tokens -> 0%", - totalSupply: sdk.NewInt(42), - totalBonded: sdkmath.ZeroInt(), - inflation: sdkmath.LegacyZeroDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyMustNewDecFromStr("1234567.123456"), - expectedRate: sdkmath.LegacyZeroDec(), - }, - { - name: "rps only: rps = total bonded / seconds in year -> basically 100%", - totalSupply: sdk.NewInt(12345), - totalBonded: sdkmath.NewInt(1234), - inflation: sdkmath.LegacyZeroDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyNewDec(1234).Quo(sdkmath.LegacyNewDec(keeper.SecondsPerYear)), - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.999999999999987228"), // <-- for 6-decimal token, this is negligible rounding - }, - { - name: "rps only: 10M kava / year rewards", - totalSupply: sdk.NewInt(870950000e6), - totalBonded: sdkmath.NewInt(130380000e6), - inflation: sdkmath.LegacyZeroDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyMustNewDecFromStr("317097.919837645865043125"), // 10 million kava per year - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.076698880196349133"), // verified manually - }, - { - name: "rps only: 25M kava / year rewards", - totalSupply: sdk.NewInt(870950000e6), - totalBonded: sdkmath.NewInt(130380000e6), - inflation: sdkmath.LegacyZeroDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyMustNewDecFromStr("792744.799594114662607813"), // 25 million kava per year - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.191747200490872833"), // verified manually - }, - { - name: "rps only: too much kava / year rewards", - totalSupply: sdk.NewInt(870950000e6), - totalBonded: sdkmath.NewInt(130380000e6), - inflation: sdkmath.LegacyZeroDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyNewDecFromBigInt(hugeRewardsPerSec), // 2^230. a higher exponent than this overflows. - // https://www.wolframalpha.com/input?i=%28%28365+*+24+*+3600%29+%2F+130380000e6%29+*+%282%5E230%29 - expectedRate: sdkmath.LegacyMustNewDecFromStr("417344440850566075319340506352140425426634017001007267992800590.431305795858260469"), // verified manually - }, - { - name: "rps only: low kava / year rewards", - totalSupply: sdk.NewInt(870950000e6), - totalBonded: sdkmath.NewInt(130380000e6), - inflation: sdkmath.LegacyZeroDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyMustNewDecFromStr("0.1"), - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.000000024187758858"), // verified manually, rounded would be 0.000000024187758859 - }, - { - name: "rps only: 1 ukava / year rewards", - totalSupply: sdk.NewInt(870950000e6), - totalBonded: sdkmath.NewInt(130380000e6), - inflation: sdkmath.LegacyZeroDec(), - communityTax: sdkmath.LegacyZeroDec(), - perSecReward: sdkmath.LegacyMustNewDecFromStr("0.000000031709791984"), // 1 ukava per year - expectedRate: sdkmath.LegacyMustNewDecFromStr("0.000000000000007669"), // verified manually, rounded would be 0.000000000000007670 - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - rewardRate := keeper.CalculateStakingAnnualPercentage( - tc.totalSupply, - tc.totalBonded, - tc.inflation, - tc.communityTax, - tc.perSecReward) - require.Equal(t, tc.expectedRate, rewardRate) - }) - } -} diff --git a/x/community/keeper/staking.go b/x/community/keeper/staking.go deleted file mode 100644 index 2d13dbc4..00000000 --- a/x/community/keeper/staking.go +++ /dev/null @@ -1,98 +0,0 @@ -package keeper - -import ( - "time" - - sdkmath "cosmossdk.io/math" - "github.com/0glabs/0g-chain/x/community/types" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -const nanosecondsInOneSecond = int64(1000000000) - -// PayoutAccumulatedStakingRewards calculates and transfers taking rewards to the fee collector address -func (k Keeper) PayoutAccumulatedStakingRewards(ctx sdk.Context) { - // get module parameters which define the amount of rewards to payout per second - params := k.mustGetParams(ctx) - currentBlockTime := ctx.BlockTime() - state := k.GetStakingRewardsState(ctx) - - // we have un-initialized state -- set accumulation time and exit since there is nothing to do - if state.LastAccumulationTime.IsZero() { - state.LastAccumulationTime = currentBlockTime - - k.SetStakingRewardsState(ctx, state) - - return - } - - // get the denom for staking - stakingRewardDenom := k.stakingKeeper.BondDenom(ctx) - - // we fetch the community pool balance to ensure only accumulate rewards up to the current balance - communityPoolBalance := sdkmath.LegacyNewDecFromInt(k.bankKeeper.GetBalance(ctx, k.moduleAddress, stakingRewardDenom).Amount) - - // calculate staking reward payout capped to community pool balance - truncatedRewards, truncationError := calculateStakingRewards( - currentBlockTime, - state.LastAccumulationTime, - state.LastTruncationError, - params.StakingRewardsPerSecond, - communityPoolBalance, - ) - - // only payout if the truncated rewards are non-zero - if !truncatedRewards.IsZero() { - transferAmount := sdk.NewCoins(sdk.NewCoin(stakingRewardDenom, truncatedRewards)) - - if err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleAccountName, authtypes.FeeCollectorName, transferAmount); err != nil { - // we check for a valid balance and rewards can never be negative so panic since this will only - // occur in cases where the chain is running in an invalid state - panic(err) - } - - // emit event with amount transferred - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeStakingRewardsPaid, - sdk.NewAttribute(types.AttributeKeyStakingRewardAmount, transferAmount.String()), - ), - ) - - } - - // update accumulation state - state.LastAccumulationTime = currentBlockTime - // if the community pool balance is zero, this also resets the truncation error - state.LastTruncationError = truncationError - - // save state - k.SetStakingRewardsState(ctx, state) -} - -// calculateStakingRewards takes the currentBlockTime, state of last accumulation, rewards per second, and the community pool balance -// in order to calculate the total payout since the last accumulation time. It returns the truncated payout amount and the truncation error. -func calculateStakingRewards(currentBlockTime, lastAccumulationTime time.Time, lastTruncationError, stakingRewardsPerSecond, communityPoolBalance sdkmath.LegacyDec) (sdkmath.Int, sdkmath.LegacyDec) { - // we get the duration since we last accumulated, then use nanoseconds for full precision available - durationSinceLastPayout := currentBlockTime.Sub(lastAccumulationTime) - nanosecondsSinceLastPayout := sdkmath.LegacyNewDec(durationSinceLastPayout.Nanoseconds()) - - // We multiply by nanoseconds first, then divide by conversion to avoid loss of precision. - // This multiplication is also tested against very large values so we are safe from overflow - // in normal operations. - accumulatedRewards := nanosecondsSinceLastPayout.Mul(stakingRewardsPerSecond).QuoInt64(nanosecondsInOneSecond) - // Ensure we add any error from previous truncations - accumulatedRewards = accumulatedRewards.Add(lastTruncationError) - - if communityPoolBalance.LT(accumulatedRewards) { - accumulatedRewards = communityPoolBalance - } - - // we truncate since we can only transfer whole units - truncatedRewards := accumulatedRewards.TruncateDec() - // the truncation error to carry over to the next accumulation - truncationError := accumulatedRewards.Sub(truncatedRewards) - - return truncatedRewards.TruncateInt(), truncationError -} diff --git a/x/community/keeper/staking_test.go b/x/community/keeper/staking_test.go deleted file mode 100644 index c995c44d..00000000 --- a/x/community/keeper/staking_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/community/keeper" - "github.com/0glabs/0g-chain/x/community/testutil" -) - -func TestKeeperPayoutAccumulatedStakingRewards(t *testing.T) { - testFunc := func(ctx sdk.Context, k keeper.Keeper) { - k.PayoutAccumulatedStakingRewards(ctx) - } - suite.Run(t, testutil.NewStakingRewardsTestSuite(testFunc)) -} diff --git a/x/community/migrations/v2/store.go b/x/community/migrations/v2/store.go deleted file mode 100644 index a801eeb6..00000000 --- a/x/community/migrations/v2/store.go +++ /dev/null @@ -1,35 +0,0 @@ -package v2 - -import ( - "time" - - storetypes "github.com/cosmos/cosmos-sdk/store/types" - - sdkmath "cosmossdk.io/math" - "github.com/0glabs/0g-chain/x/community/types" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// Migrate migrates the x/community module state from the consensus version 1 to -// version 2. Specifically, sets new parameters in the module state. -func Migrate( - ctx sdk.Context, - store storetypes.KVStore, - cdc codec.BinaryCodec, -) error { - params := types.NewParams( - time.Time{}, - sdkmath.LegacyNewDec(0), - sdkmath.LegacyNewDec(0), - ) - - if err := params.Validate(); err != nil { - return err - } - - bz := cdc.MustMarshal(¶ms) - store.Set(types.ParamsKey, bz) - - return nil -} diff --git a/x/community/migrations/v2/store_test.go b/x/community/migrations/v2/store_test.go deleted file mode 100644 index d55535b8..00000000 --- a/x/community/migrations/v2/store_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package v2_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/stretchr/testify/require" - - "github.com/0glabs/0g-chain/app" - v2 "github.com/0glabs/0g-chain/x/community/migrations/v2" - "github.com/0glabs/0g-chain/x/community/types" - "github.com/cosmos/cosmos-sdk/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestMigrateStore(t *testing.T) { - tApp := app.NewTestApp() - cdc := tApp.AppCodec() - storeKey := sdk.NewKVStoreKey("community") - ctx := testutil.DefaultContext(storeKey, sdk.NewTransientStoreKey("transient_test")) - store := ctx.KVStore(storeKey) - - require.Nil( - t, - store.Get(types.ParamsKey), - "params shouldn't exist in store before migration", - ) - - require.NoError(t, v2.Migrate(ctx, store, cdc)) - - paramsBytes := store.Get(types.ParamsKey) - require.NotNil(t, paramsBytes, "params should be in store after migration") - - var params types.Params - cdc.MustUnmarshal(paramsBytes, ¶ms) - - t.Logf("params: %+v", params) - - require.Equal( - t, - types.NewParams( - time.Time{}, - sdkmath.LegacyNewDec(0), - sdkmath.LegacyNewDec(0), - ), - params, - "params should be correct after migration", - ) -} diff --git a/x/community/module.go b/x/community/module.go deleted file mode 100644 index 5d9e9c1c..00000000 --- a/x/community/module.go +++ /dev/null @@ -1,148 +0,0 @@ -package community - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/0glabs/0g-chain/x/community/client/cli" - "github.com/0glabs/0g-chain/x/community/keeper" - "github.com/0glabs/0g-chain/x/community/types" -) - -// ConsensusVersion defines the current module consensus version. -const ConsensusVersion = 2 - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name returns the module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -// Deprecated: unused but necessary to fulfill AppModuleBasic interface -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - gs := types.DefaultGenesisState() - return cdc.MustMarshalJSON(&gs) -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - err := cdc.UnmarshalJSON(bz, &gs) - if err != nil { - return err - } - return gs.Validate() -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// GetTxCmd returns the root tx command for the module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -//____________________________________________________________________________ - -// AppModule app module type -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, ak types.AccountKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: ak, - } -} - -// Name module name -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// RegisterInvariants register module invariants -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion } - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) - - m := keeper.NewMigrator(am.keeper) - if err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2); err != nil { - panic(fmt.Sprintf("failed to migrate x/community from version 1 to 2: %v", err)) - } -} - -// InitGenesis module init-genesis -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { - var genState types.GenesisState - cdc.MustUnmarshalJSON(gs, &genState) - - InitGenesis(ctx, am.keeper, am.accountKeeper, genState) - return []abci.ValidatorUpdate{} -} - -// ExportGenesis module export genesis -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(&gs) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { - BeginBlocker(ctx, am.keeper) -} - -// EndBlock module end-block -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/community/module_test.go b/x/community/module_test.go deleted file mode 100644 index 6a972bf0..00000000 --- a/x/community/module_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package community_test - -import ( - "testing" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/stretchr/testify/require" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/community/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -func TestItCreatesModuleAccountOnInitBlock(t *testing.T) { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1}) - tApp.InitializeFromGenesisStates() - - accKeeper := tApp.GetAccountKeeper() - acc := accKeeper.GetAccount(ctx, authtypes.NewModuleAddress(types.ModuleName)) - require.NotNil(t, acc) -} diff --git a/x/community/spec/01_concepts.md b/x/community/spec/01_concepts.md deleted file mode 100644 index 8a520410..00000000 --- a/x/community/spec/01_concepts.md +++ /dev/null @@ -1,37 +0,0 @@ - - -# Concepts - -## Community Pool - -The x/community module contains the community pool funds and provides proposal -handlers to manage community pool funds. - -### Funding - -The x/community module account can be funded by any account sending a -community/FundCommunityPool message. These funds may be deposited/withdrawn to -lend via the CommunityPoolLendDepositProposal & -CommunityPoolLendWithdrawProposal. - -### Rewards - -Rewards payout behavior for staking depends on the module parameters, and will -change based on the "switchover" time parameter `upgrade_time_disable_inflation`. - -If the current block is *before* the switchover time and the -`staking_rewards_per_second` parameter is set to 0, no staking rewards will be -paid from the `x/community` module and will continue to come from other modules -such as `x/mint` and `x/distribution`. - -On the first block after the switchover time, the `staking_rewards_per_second` -parameter is updated to reflect the parameter -`upgrade_time_set_staking_rewards_per_second`, and staking rewards are paid out -every block from the community pool, instead of from minted coins from `x/mint` -and `x/kavadist`. The payout is calculated with the `staking_rewards_per_second` -parameter. - -In addition to these payout changes, inflation in `x/mint` and `x/kavadist` is -disabled after the switchover time. diff --git a/x/community/spec/02_state.md b/x/community/spec/02_state.md deleted file mode 100644 index b2dbcb2a..00000000 --- a/x/community/spec/02_state.md +++ /dev/null @@ -1,75 +0,0 @@ - - -# State - -## Parameters and Genesis State - -`Params` define the module parameters, containing the information required to -set the current staking rewards per second at a future date. When the -`upgrade_time_disable_inflation` time is reached, `staking_rewards_per_second` -will be set to `upgrade_time_set_staking_rewards_per_second`. - -```protobuf -// Params defines the parameters of the community module. -message Params { - option (gogoproto.equal) = true; - - // upgrade_time_disable_inflation is the time at which to disable mint and kavadist module inflation. - // If set to 0, inflation will be disabled from block 1. - google.protobuf.Timestamp upgrade_time_disable_inflation = 1 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - - // staking_rewards_per_second is the amount paid out to delegators each block from the community account - string staking_rewards_per_second = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", - (gogoproto.nullable) = false - ]; - - // upgrade_time_set_staking_rewards_per_second is the initial staking_rewards_per_second to set - // and use when the disable inflation time is reached - string upgrade_time_set_staking_rewards_per_second = 3 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", - (gogoproto.nullable) = false - ]; -} -``` - -`GenesisState` defines the state that must be persisted when the blockchain -stops/restarts in order for normal function of the module to resume. It contains -the parameters and staking rewards state to keep track of payout between blocks. - -```protobuf -// GenesisState defines the community module's genesis state. -message GenesisState { - // params defines all the parameters related to commmunity - Params params = 1 [(gogoproto.nullable) = false]; - - // StakingRewardsState stores the internal staking reward data required to - // track staking rewards across blocks - StakingRewardsState staking_rewards_state = 2 [(gogoproto.nullable) = false]; -} - -// StakingRewardsState represents the state of staking reward accumulation between blocks. -message StakingRewardsState { - // last_accumulation_time represents the last block time which rewards where calculated and distributed. - // This may be zero to signal accumulation should start on the next interval. - google.protobuf.Timestamp last_accumulation_time = 1 [ - (gogoproto.stdtime) = true, - (gogoproto.nullable) = false - ]; - - // accumulated_truncation_error represents the sum of previous errors due to truncation on payout - // This value will always be on the interval [0, 1). - string last_truncation_error = 2 [ - (cosmos_proto.scalar) = "cosmos.Dec", - (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", - (gogoproto.nullable) = false - ]; -} -``` diff --git a/x/community/spec/03_messages.md b/x/community/spec/03_messages.md deleted file mode 100644 index 5e52b2ba..00000000 --- a/x/community/spec/03_messages.md +++ /dev/null @@ -1,22 +0,0 @@ - - -# Messages - -## FundCommunityPool - -Send coins directly from the sender to the community module account. - -The transaction fails if the amount cannot be transferred from the sender to the community module account. - -https://github.com/0glabs/0g-chain/blob/1d36429fe34cc5829d636d73b7c34751a925791b/proto/kava/community/v1beta1/tx.proto#L21-L30 - -## UpdateParams - -Update module parameters via gov proposal. - -The transaction fails if the message is not submitted through a gov proposal. -The message `authority` must be the x/gov module account address. - -https://github.com/0glabs/0g-chain/blob/1d36429fe34cc5829d636d73b7c34751a925791b/proto/kava/community/v1beta1/tx.proto#L35-L44 diff --git a/x/community/spec/04_events.md b/x/community/spec/04_events.md deleted file mode 100644 index 367693fd..00000000 --- a/x/community/spec/04_events.md +++ /dev/null @@ -1,53 +0,0 @@ - - -# Events - -The community module emits the following events: - -## Handlers - -### MsgFundCommunityPool - -| Type | Attribute Key | Attribute Value | -| ------- | ------------- | ------------------- | -| message | module | community | -| message | action | fund_community_pool | -| message | sender | {senderAddress} | -| message | amount | {amountCoins} | - -## Keeper events - -In addition to handlers events, the bank keeper will produce events when the -following methods are called (or any method which ends up calling them) - -### CheckAndDisableMintAndKavaDistInflation - -```json -{ - "type": "inflation_stop", - "attributes": [ - { - "key": "inflation_disable_time", - "value": "{{RFC3339 formatted time inflation was disabled}}", - "index": true - } - ] -} -``` - -### PayoutAccumulatedStakingRewards - -```json -{ - "type": "staking_rewards_paid", - "attributes": [ - { - "key": "staking_reward_amount", - "value": "{{sdk.Coins being paid to validators}}", - "index": true - } - ] -} -``` diff --git a/x/community/spec/05_params.md b/x/community/spec/05_params.md deleted file mode 100644 index e046e236..00000000 --- a/x/community/spec/05_params.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# Parameters - -The community module contains the following parameters: - -| Key | Type | Example | -| ------------------------------------------- | ------------- | ---------------------- | -| upgrade_time_disable_inflation | string (time) | "2023-11-01T00:00:00Z" | -| staking_rewards_per_second | string | "744191" | -| upgrade_time_set_staking_rewards_per_second | string | "0" | diff --git a/x/community/spec/README.md b/x/community/spec/README.md deleted file mode 100644 index 16b3a581..00000000 --- a/x/community/spec/README.md +++ /dev/null @@ -1,19 +0,0 @@ - - -# `community` - - - -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** - -## Abstract - -`x/community` is an implementation of a Cosmos SDK Module that provides governance for the community pool of funds controlled by Kava DAO. diff --git a/x/community/staking_rewards_abci_test.go b/x/community/staking_rewards_abci_test.go deleted file mode 100644 index a13ab079..00000000 --- a/x/community/staking_rewards_abci_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package community_test - -import ( - "testing" - - "github.com/0glabs/0g-chain/x/community" - "github.com/0glabs/0g-chain/x/community/keeper" - "github.com/0glabs/0g-chain/x/community/testutil" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" -) - -func TestABCIPayoutAccumulatedStakingRewards(t *testing.T) { - testFunc := func(ctx sdk.Context, k keeper.Keeper) { - community.BeginBlocker(ctx, k) - } - suite.Run(t, testutil.NewStakingRewardsTestSuite(testFunc)) -} diff --git a/x/community/testutil/cdp_genesis.go b/x/community/testutil/cdp_genesis.go deleted file mode 100644 index eb7309b7..00000000 --- a/x/community/testutil/cdp_genesis.go +++ /dev/null @@ -1,57 +0,0 @@ -package testutil - -import ( - "time" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/app" - cdptypes "github.com/0glabs/0g-chain/x/cdp/types" -) - -func NewCDPGenState(cdc codec.JSONCodec, denom, asset string, liquidationRatio sdk.Dec) app.GenesisState { - cdpGenesis := cdptypes.GenesisState{ - Params: cdptypes.Params{ - GlobalDebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - SurplusAuctionThreshold: cdptypes.DefaultSurplusThreshold, - SurplusAuctionLot: cdptypes.DefaultSurplusLot, - DebtAuctionThreshold: cdptypes.DefaultDebtThreshold, - DebtAuctionLot: cdptypes.DefaultDebtLot, - LiquidationBlockInterval: cdptypes.DefaultBeginBlockerExecutionBlockInterval, - CollateralParams: cdptypes.CollateralParams{ - { - Denom: denom, - Type: asset + "-a", - LiquidationRatio: liquidationRatio, - DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: sdk.MustNewDecFromStr("0.05"), - AuctionSize: sdk.NewInt(100), - SpotMarketID: asset + ":usd", - LiquidationMarketID: asset + ":usd", - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"), - CheckCollateralizationIndexCount: sdk.NewInt(10), - ConversionFactor: sdk.NewInt(6), - }, - }, - DebtParam: cdptypes.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: sdk.NewInt(6), - DebtFloor: sdk.NewInt(10000000), - }, - }, - StartingCdpID: cdptypes.DefaultCdpStartingID, - DebtDenom: cdptypes.DefaultDebtDenom, - GovDenom: cdptypes.DefaultGovDenom, - CDPs: cdptypes.CDPs{}, - PreviousAccumulationTimes: cdptypes.GenesisAccumulationTimes{ - cdptypes.NewGenesisAccumulationTime(asset+"-a", time.Time{}, sdk.OneDec()), - }, - TotalPrincipals: cdptypes.GenesisTotalPrincipals{ - cdptypes.NewGenesisTotalPrincipal(asset+"-a", sdk.ZeroInt()), - }, - } - return app.GenesisState{cdptypes.ModuleName: cdc.MustMarshalJSON(&cdpGenesis)} -} diff --git a/x/community/testutil/consolidate.go b/x/community/testutil/consolidate.go deleted file mode 100644 index 49b2ab9d..00000000 --- a/x/community/testutil/consolidate.go +++ /dev/null @@ -1,180 +0,0 @@ -package testutil - -import ( - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - - "github.com/0glabs/0g-chain/app" - types "github.com/0glabs/0g-chain/x/community/types" - kavadisttypes "github.com/0glabs/0g-chain/x/kavadist/types" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" -) - -func (suite *disableInflationTestSuite) TestStartCommunityFundConsolidation() { - tests := []struct { - name string - initialFeePoolCoins sdk.DecCoins - initialKavadistBalance sdk.Coins - }{ - { - "basic test with both balances and dust", - sdk.NewDecCoins( - sdk.NewDecCoinFromDec("ukava", sdk.NewDecWithPrec(123456, 2)), - sdk.NewDecCoinFromDec("usdx", sdk.NewDecWithPrec(654321, 3)), - ), - sdk.NewCoins( - sdk.NewInt64Coin("ukava", 10_000), - sdk.NewInt64Coin("usdx", 10_000), - ), - }, - { - "empty x/distribution feepool", - sdk.DecCoins(nil), - sdk.NewCoins( - sdk.NewInt64Coin("ukava", 10_000), - sdk.NewInt64Coin("usdx", 10_000), - ), - }, - { - "empty x/kavadist balance", - sdk.NewDecCoins( - sdk.NewDecCoinFromDec("ukava", sdk.NewDecWithPrec(123456, 2)), - sdk.NewDecCoinFromDec("usdx", sdk.NewDecWithPrec(654321, 3)), - ), - sdk.Coins{}, - }, - { - "both x/distribution feepool and x/kavadist balance empty", - sdk.DecCoins(nil), - sdk.Coins{}, - }, - } - - for _, tc := range tests { - suite.Run(tc.name, func() { - suite.SetupTest() - ak := suite.App.GetAccountKeeper() - - initialFeePool := distrtypes.FeePool{ - CommunityPool: tc.initialFeePoolCoins, - } - - initialFeePoolCoins, initialFeePoolDust := initialFeePool.CommunityPool.TruncateDecimal() - - // More coins than initial feepool/communitypool - fundCoins := sdk.NewCoins( - sdk.NewInt64Coin("ukava", 10_000), - sdk.NewInt64Coin("usdx", 10_000), - ) - - // Always fund x/distribution with enough coins to cover feepool - err := suite.App.FundModuleAccount( - suite.Ctx, - distrtypes.ModuleName, - fundCoins, - ) - suite.NoError(err, "x/distribution account should be funded without error") - - err = suite.App.FundModuleAccount( - suite.Ctx, - kavadisttypes.ModuleName, - tc.initialKavadistBalance, - ) - suite.NoError(err, "x/kavadist account should be funded without error") - - suite.App.GetDistrKeeper().SetFeePool(suite.Ctx, initialFeePool) - - // Ensure the feepool was set before migration - feePoolBefore := suite.App.GetDistrKeeper().GetFeePool(suite.Ctx) - suite.Equal(initialFeePool, feePoolBefore, "initial feepool should be set") - communityBalanceBefore := suite.App.GetCommunityKeeper().GetModuleAccountBalance(suite.Ctx) - - kavadistAcc := ak.GetModuleAccount(suite.Ctx, kavadisttypes.KavaDistMacc) - kavaDistCoinsBefore := suite.App.GetBankKeeper().GetAllBalances(suite.Ctx, kavadistAcc.GetAddress()) - suite.Equal( - tc.initialKavadistBalance, - kavaDistCoinsBefore, - "x/kavadist balance should be funded", - ) - - expectedKavaDistCoins := sdk.NewCoins(sdk.NewCoin("ukava", kavaDistCoinsBefore.AmountOf("ukava"))) - - // ------------- - // Run upgrade - - params, found := suite.Keeper.GetParams(suite.Ctx) - suite.Require().True(found) - params.UpgradeTimeDisableInflation = suite.Ctx.BlockTime().Add(-time.Minute) - suite.Keeper.SetParams(suite.Ctx, params) - - err = suite.Keeper.StartCommunityFundConsolidation(suite.Ctx) - suite.NoError(err, "consolidation should not error") - - // ------------- - // Check results - suite.Run("module balances after consolidation should moved", func() { - feePoolAfter := suite.App.GetDistrKeeper().GetFeePool(suite.Ctx) - suite.Equal( - initialFeePoolDust, - feePoolAfter.CommunityPool, - "x/distribution community pool should be sent to x/community", - ) - - kavaDistCoinsAfter := suite.App.GetBankKeeper().GetAllBalances(suite.Ctx, kavadistAcc.GetAddress()) - suite.Equal( - expectedKavaDistCoins, - kavaDistCoinsAfter, - "x/kavadist balance should ony contain ukava", - ) - - totalExpectedCommunityPoolCoins := communityBalanceBefore. - Add(initialFeePoolCoins...). // x/distribution fee pool - Add(tc.initialKavadistBalance...) // x/kavadist module balance - - communityBalanceAfter := suite.App.GetCommunityKeeper().GetModuleAccountBalance(suite.Ctx) - - // Use .IsAllGTE to avoid types.Coins(nil) vs types.Coins{} mismatch - suite.Truef( - totalExpectedCommunityPoolCoins.IsAllGTE(communityBalanceAfter), - "x/community balance should be increased by the truncated x/distribution community pool, got %s, expected %s", - communityBalanceAfter, - totalExpectedCommunityPoolCoins, - ) - }) - - suite.Run("bank transfer events should be emitted", func() { - communityAcc := ak.GetModuleAccount(suite.Ctx, types.ModuleAccountName) - distributionAcc := ak.GetModuleAccount(suite.Ctx, distrtypes.ModuleName) - kavadistAcc := ak.GetModuleAccount(suite.Ctx, kavadisttypes.KavaDistMacc) - - events := suite.Ctx.EventManager().Events() - - suite.NoError( - app.EventsContains( - events, - sdk.NewEvent( - banktypes.EventTypeTransfer, - sdk.NewAttribute(banktypes.AttributeKeyRecipient, communityAcc.GetAddress().String()), - sdk.NewAttribute(banktypes.AttributeKeySender, distributionAcc.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, initialFeePoolCoins.String()), - ), - ), - ) - - suite.NoError( - app.EventsContains( - events, - sdk.NewEvent( - banktypes.EventTypeTransfer, - sdk.NewAttribute(banktypes.AttributeKeyRecipient, communityAcc.GetAddress().String()), - sdk.NewAttribute(banktypes.AttributeKeySender, kavadistAcc.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, kavaDistCoinsBefore.Sub(expectedKavaDistCoins...).String()), - ), - ), - ) - }) - }) - } -} diff --git a/x/community/testutil/disable_inflation.go b/x/community/testutil/disable_inflation.go deleted file mode 100644 index 39902b08..00000000 --- a/x/community/testutil/disable_inflation.go +++ /dev/null @@ -1,203 +0,0 @@ -package testutil - -import ( - "time" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/community" - "github.com/0glabs/0g-chain/x/community/keeper" - "github.com/0glabs/0g-chain/x/community/types" - kavadisttypes "github.com/0glabs/0g-chain/x/kavadist/types" -) - -type testFunc func(sdk.Context, keeper.Keeper) - -// Test suite used for all abci inflation tests -type disableInflationTestSuite struct { - suite.Suite - - App app.TestApp - Ctx sdk.Context - Keeper keeper.Keeper - - genesisMintState *minttypes.GenesisState - genesisKavadistState *kavadisttypes.GenesisState - genesisDistrState *distrtypes.GenesisState - - testFunc testFunc -} - -func NewDisableInflationTestSuite(tf testFunc) *disableInflationTestSuite { - suite := &disableInflationTestSuite{} - suite.testFunc = tf - return suite -} - -// The default state used by each test -func (suite *disableInflationTestSuite) SetupTest() { - app.SetSDKConfig() - tApp := app.NewTestApp() - suite.App = tApp - suite.Ctx = suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - suite.Keeper = suite.App.GetCommunityKeeper() - - // Set up x/mint and x/kavadist gen state - mintGen := minttypes.DefaultGenesisState() - mintGen.Params.InflationMax = sdk.NewDecWithPrec(595, 3) - mintGen.Params.InflationMin = sdk.NewDecWithPrec(595, 3) - suite.genesisMintState = mintGen - - kavadistGen := kavadisttypes.DefaultGenesisState() - kavadistGen.Params.Active = true - suite.genesisKavadistState = kavadistGen - - distrGen := distrtypes.DefaultGenesisState() - distrGen.Params.CommunityTax = sdk.MustNewDecFromStr("0.949500000000000000") - suite.genesisDistrState = distrGen - - appCodec := tApp.AppCodec() - suite.App.InitializeFromGenesisStates( - app.GenesisState{minttypes.ModuleName: appCodec.MustMarshalJSON(mintGen)}, - app.GenesisState{kavadisttypes.ModuleName: appCodec.MustMarshalJSON(kavadistGen)}, - app.GenesisState{distrtypes.ModuleName: appCodec.MustMarshalJSON(distrGen)}, - ) -} - -func (suite *disableInflationTestSuite) TestDisableInflation() { - validateState := func(upgraded bool, expectedDisableTime time.Time, originalStakingRewards sdkmath.LegacyDec, setStakingRewards sdkmath.LegacyDec, msg string) { - params, found := suite.Keeper.GetParams(suite.Ctx) - suite.Require().True(found) - mintParams := suite.App.GetMintKeeper().GetParams(suite.Ctx) - kavadistParams := suite.App.GetKavadistKeeper().GetParams(suite.Ctx) - distrParams := suite.App.GetDistrKeeper().GetParams(suite.Ctx) - - disableTimeMsg := "expected inflation disable time to match" - expectedMintState := suite.genesisMintState - expectedKavadistState := suite.genesisKavadistState - expectedDistrState := suite.genesisDistrState - expectedStakingRewards := originalStakingRewards - msgSuffix := "before upgrade" - - // The state expected after upgrade time is reached - if upgraded { - // Disable upgrade time is reset when run. - // - // This allows the time to be set and run again if required. - // In addition, with zero time not upgrading, achieves idempotence - // without extra logic or state. - expectedDisableTime = time.Time{} - disableTimeMsg = "expected inflation disable time to be reset" - expectedStakingRewards = setStakingRewards - - expectedMintState.Params.InflationMin = sdk.ZeroDec() - expectedMintState.Params.InflationMax = sdk.ZeroDec() - - expectedKavadistState.Params.Active = false - - expectedDistrState.Params.CommunityTax = sdk.ZeroDec() - - msgSuffix = "after upgrade" - - suite.Require().NoError( - app.EventsContains( - suite.Ctx.EventManager().Events(), - sdk.NewEvent( - types.EventTypeInflationStop, - sdk.NewAttribute( - types.AttributeKeyInflationDisableTime, - suite.Ctx.BlockTime().Format(time.RFC3339), - ), - ), - )) - } - - suite.Require().Equal(expectedMintState.Params.InflationMin, mintParams.InflationMin, msg+": expected mint inflation min to match state "+msgSuffix) - suite.Require().Equal(expectedMintState.Params.InflationMax, mintParams.InflationMax, msg+": expected mint inflation max to match state "+msgSuffix) - suite.Require().Equal(expectedKavadistState.Params.Active, kavadistParams.Active, msg+":expected kavadist active flag match state "+msgSuffix) - suite.Require().Equal(expectedDistrState.Params.CommunityTax, distrParams.CommunityTax, msg+":expected x/distribution community tax to match state "+msgSuffix) - suite.Require().Equal(expectedDisableTime, params.UpgradeTimeDisableInflation, msg+": "+disableTimeMsg) - - // we always check staking rewards per second matches the passed in expectation - suite.Require().Equal(expectedStakingRewards, params.StakingRewardsPerSecond, msg+": "+"staking rewards per second to match "+msgSuffix) - // we don't modify or zero out the initial rewards per second for upgrade time - suite.Require().Equal(setStakingRewards, params.UpgradeTimeSetStakingRewardsPerSecond, msg+": "+"set staking rewards per second to match "+msgSuffix) - } - - blockTime := suite.Ctx.BlockTime() - testCases := []struct { - name string - upgradeTime time.Time - setStakingRewards sdkmath.LegacyDec - shouldUpgrade bool - }{ - {"zero upgrade time -- should not upgrade", time.Time{}, sdkmath.LegacyNewDec(1001), false}, - {"upgrade time in future -- should not upgrade", blockTime.Add(1 * time.Second), sdkmath.LegacyNewDec(1002), false}, - {"upgrade time in past -- should upgrade", blockTime.Add(-1 * time.Second), sdkmath.LegacyNewDec(1003), true}, - {"upgrade time equal to block time -- should upgrade", blockTime, sdkmath.LegacyNewDec(1004), true}, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - params, found := suite.Keeper.GetParams(suite.Ctx) - suite.Require().True(found) - - // these should not match in order to assure assertions test correct behavior - suite.Require().NotEqual(params.StakingRewardsPerSecond, tc.setStakingRewards, "set staking rewards can not match initial staking rewards") - - // ensure state is as we expect before running upgrade or updating time - validateState(false, time.Time{}, params.StakingRewardsPerSecond, params.UpgradeTimeSetStakingRewardsPerSecond, "initial state") - - // set inflation disable time - params.UpgradeTimeDisableInflation = tc.upgradeTime - // set upgrade time set staking rewards per second - params.UpgradeTimeSetStakingRewardsPerSecond = tc.setStakingRewards - suite.Keeper.SetParams(suite.Ctx, params) - - // run test function - suite.testFunc(suite.Ctx, suite.Keeper) - - // run assertions to ensure upgrade did or did not run - validateState(tc.shouldUpgrade, tc.upgradeTime, params.StakingRewardsPerSecond, tc.setStakingRewards, "first begin blocker run") - - // test idempotence only if upgrade should have been ran - if tc.shouldUpgrade { - // reset mint and kavadist state to their initial values - err := suite.App.GetMintKeeper().SetParams(suite.Ctx, suite.genesisMintState.Params) - suite.Require().NoError(err) - suite.App.GetKavadistKeeper().SetParams(suite.Ctx, suite.genesisKavadistState.Params) - - // modify staking rewards per second to ensure they are not overridden again - params, found := suite.Keeper.GetParams(suite.Ctx) - suite.Require().True(found) - params.StakingRewardsPerSecond = params.StakingRewardsPerSecond.Add(sdkmath.LegacyOneDec()) - suite.Keeper.SetParams(suite.Ctx, params) - - // run begin blocker again - community.BeginBlocker(suite.Ctx, suite.Keeper) - - // ensure begin blocker is idempotent and never runs twice - validateState(false, time.Time{}, params.StakingRewardsPerSecond, tc.setStakingRewards, "second begin blocker run") - } - }) - } -} - -func (suite *disableInflationTestSuite) TestPanicsOnMissingParameters() { - suite.SetupTest() - - store := suite.Ctx.KVStore(suite.App.GetKVStoreKey(types.StoreKey)) - store.Delete(types.ParamsKey) - - suite.PanicsWithValue("invalid state: module parameters not found", func() { - suite.testFunc(suite.Ctx, suite.Keeper) - }) -} diff --git a/x/community/testutil/main.go b/x/community/testutil/main.go deleted file mode 100644 index 4142ce38..00000000 --- a/x/community/testutil/main.go +++ /dev/null @@ -1,47 +0,0 @@ -package testutil - -import ( - "github.com/stretchr/testify/suite" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/community/keeper" - "github.com/0glabs/0g-chain/x/community/types" -) - -// Test suite used for all community tests -type Suite struct { - suite.Suite - App app.TestApp - Ctx sdk.Context - Keeper keeper.Keeper - - MaccAddress sdk.AccAddress -} - -// The default state used by each test -func (suite *Suite) SetupTest() { - app.SetSDKConfig() - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - suite.App = tApp.InitializeFromGenesisStates() - - suite.Ctx = ctx - suite.Keeper = tApp.GetCommunityKeeper() - communityPoolAddress := tApp.GetAccountKeeper().GetModuleAddress(types.ModuleAccountName) - // hello, greppers! - suite.Equal("kava17d2wax0zhjrrecvaszuyxdf5wcu5a0p4qlx3t5", communityPoolAddress.String()) - suite.MaccAddress = communityPoolAddress -} - -// CreateFundedAccount creates a random account and mints `coins` to it. -func (suite *Suite) CreateFundedAccount(coins sdk.Coins) sdk.AccAddress { - addr := app.RandomAddress() - err := suite.App.FundAccount(suite.Ctx, addr, coins) - suite.Require().NoError(err) - return addr -} diff --git a/x/community/testutil/pricefeed_genesis_builder.go b/x/community/testutil/pricefeed_genesis_builder.go deleted file mode 100644 index 087e7f18..00000000 --- a/x/community/testutil/pricefeed_genesis_builder.go +++ /dev/null @@ -1,61 +0,0 @@ -package testutil - -import ( - "time" - - sdkmath "cosmossdk.io/math" - hardtypes "github.com/0glabs/0g-chain/x/hard/types" - pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// lendGenesisBuilder builds the Hard and Pricefeed genesis states for setting up Kava Lend -type lendGenesisBuilder struct { - hardMarkets []hardtypes.MoneyMarket - pfMarkets []pricefeedtypes.Market - prices []pricefeedtypes.PostedPrice -} - -func NewLendGenesisBuilder() lendGenesisBuilder { - return lendGenesisBuilder{} -} - -func (b lendGenesisBuilder) Build() (hardtypes.GenesisState, pricefeedtypes.GenesisState) { - hardGS := hardtypes.DefaultGenesisState() - hardGS.Params.MoneyMarkets = b.hardMarkets - - pricefeedGS := pricefeedtypes.DefaultGenesisState() - pricefeedGS.Params.Markets = b.pfMarkets - pricefeedGS.PostedPrices = b.prices - return hardGS, pricefeedGS -} - -func (b lendGenesisBuilder) WithMarket(denom, spotMarketId string, price sdk.Dec) lendGenesisBuilder { - // add hard money market - b.hardMarkets = append(b.hardMarkets, - hardtypes.NewMoneyMarket( - denom, - hardtypes.NewBorrowLimit(false, sdk.NewDec(1e15), sdk.MustNewDecFromStr("0.6")), - spotMarketId, - sdkmath.NewInt(1e6), - hardtypes.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), - sdk.MustNewDecFromStr("0.05"), - sdk.ZeroDec(), - ), - ) - - // add pricefeed - b.pfMarkets = append(b.pfMarkets, - pricefeedtypes.Market{MarketID: spotMarketId, BaseAsset: denom, QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - ) - b.prices = append(b.prices, - pricefeedtypes.PostedPrice{ - MarketID: spotMarketId, - OracleAddress: sdk.AccAddress{}, - Price: price, - Expiry: time.Now().Add(100 * time.Hour), - }, - ) - - return b -} diff --git a/x/community/testutil/staking_rewards.go b/x/community/testutil/staking_rewards.go deleted file mode 100644 index 150951b5..00000000 --- a/x/community/testutil/staking_rewards.go +++ /dev/null @@ -1,421 +0,0 @@ -package testutil - -import ( - "fmt" - "math" - "math/rand" - "time" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/community" - "github.com/0glabs/0g-chain/x/community/keeper" - "github.com/0glabs/0g-chain/x/community/types" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// StakingRewardsTestSuite tests staking rewards per second logic -type stakingRewardsTestSuite struct { - suite.Suite - - App app.TestApp - Keeper keeper.Keeper - - testFunc testFunc -} - -func NewStakingRewardsTestSuite(tf testFunc) *stakingRewardsTestSuite { - suite := &stakingRewardsTestSuite{} - suite.testFunc = tf - return suite -} - -// The default state used by each test -func (suite *stakingRewardsTestSuite) SetupTest() { - app.SetSDKConfig() - - tApp := app.NewTestApp() - tApp.InitializeFromGenesisStates() - - suite.App = tApp - suite.Keeper = suite.App.GetCommunityKeeper() -} - -func (suite *stakingRewardsTestSuite) TestStakingRewards() { - testCases := []struct { - // name of subtest - name string - - // block time of first block - periodStart time.Time - // block time of last block - periodEnd time.Time - - // block time n will be periodStart + rand(range_min...range_max)*(n-1) up to periodEnd - blockTimeRangeMin float64 - blockTimeRangeMax float64 - - // rewards per second to set in state - rewardsPerSecond sdkmath.LegacyDec - - // the amount of ukava to mint and transfer to the community pool - // to use to pay for rewards - communityPoolFunds sdkmath.Int - - // how many total rewards are expected to be accumulated in ukava - expectedRewardsTotal sdkmath.Int - }{ - // ** These take a long time to run ** - //{ - // name: "one year with 0.5 to 1 second block times", - // periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - // periodEnd: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC), - // blockTimeRangeMin: 0.5, - // blockTimeRangeMax: 1, - // rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("1585489.599188229325215626"), - // expectedRewardsTotal: sdkmath.NewInt(49999999999999), // 50 million KAVA per year - //}, - //{ - // name: "one year with 5.5 to 6.5 second blocktimes", - // periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - // periodEnd: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC), - // blockTimeRangeMin: 5.5, - // blockTimeRangeMax: 6.5, - // rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("1585489.599188229325215626"), // 50 million kava per year - // communityPoolFunds: sdkmath.NewInt(50000000000000), - // expectedRewardsTotal: sdkmath.NewInt(49999999999999), // truncation results in 1 ukava error - //}, - // - // - // One Day of blocks with different block time variations - // - // - { - name: "one day with sub-second block times and 50 million KAVA per year", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2023, 1, 2, 0, 0, 0, 0, time.UTC), - blockTimeRangeMin: 0.1, - blockTimeRangeMax: 1, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("1585489.599188229325215626"), // 50 million kava per year - communityPoolFunds: sdkmath.NewInt(200000000000), - expectedRewardsTotal: sdkmath.NewInt(136986301369), // 50 million / 365 days - 1 ukava - - }, - { - name: "one day with 5.5 to 6.5 second block times and 50 million KAVA per year", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2023, 1, 2, 0, 0, 0, 0, time.UTC), - blockTimeRangeMin: 5.5, - blockTimeRangeMax: 6.5, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("1585489.599188229325215626"), // 50 million kava per year - communityPoolFunds: sdkmath.NewInt(200000000000), - expectedRewardsTotal: sdkmath.NewInt(136986301369), // 50 million / 365 days - 1 ukava - }, - // - // - // Total time span under 1 second - // - // - { - name: "single 6.9 second time span and 25 million KAVA per year", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2023, 1, 1, 0, 0, 6, 900000000, time.UTC), - blockTimeRangeMin: 10, // forces only two blocks -- one time span - blockTimeRangeMax: 10, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("792744.799594114662607813"), // 25 million kava per year - communityPoolFunds: sdkmath.NewInt(10000000), - expectedRewardsTotal: sdkmath.NewInt(5469939), // per second rate * 6.9 - }, - { - name: "multiple blocks across sub-second time span nd 10 million KAVA per year", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2023, 1, 1, 0, 0, 0, 800000000, time.UTC), - blockTimeRangeMin: 0.1, // multiple blocks in a sub-second time span - blockTimeRangeMax: 0.2, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("317097.919837645865043125"), // 10 million kava per year - communityPoolFunds: sdkmath.NewInt(300000), - expectedRewardsTotal: sdkmath.NewInt(253678), // per second rate * 0.8 - }, - // - // - // Variations of community pool balance - // - // - { - name: "community pool exact funds -- should spend community to zero and not panic", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2023, 1, 2, 0, 0, 0, 0, time.UTC), - blockTimeRangeMin: 5.5, - blockTimeRangeMax: 6.2, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("317097.919837645865043125"), // 10 million kava per year - communityPoolFunds: sdkmath.NewInt(27397260273), - expectedRewardsTotal: sdkmath.NewInt(27397260273), - }, - { - name: "community pool under funded -- should spend community pool to down to zero and not panic", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2023, 1, 2, 0, 0, 0, 0, time.UTC), - blockTimeRangeMin: 5.5, - blockTimeRangeMax: 6.5, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("1585489.599188229325215626"), // 25 million kava per year - communityPoolFunds: sdkmath.NewInt(100000000000), // under funded - expectedRewardsTotal: sdkmath.NewInt(100000000000), // rewards max is the community pool balance - }, - { - name: "community pool no funds -- should pay zero rewards and not panic", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2023, 1, 2, 0, 0, 0, 0, time.UTC), - blockTimeRangeMin: 5.5, - blockTimeRangeMax: 6.5, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("792744.799594114662607813"), // 25 million kava per year - communityPoolFunds: sdkmath.NewInt(0), - expectedRewardsTotal: sdkmath.NewInt(0), - }, - // - // - // Disabled - // - // - { - name: "zero rewards per second results in zero rewards paid", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2023, 1, 2, 0, 0, 0, 0, time.UTC), - blockTimeRangeMin: 5.5, - blockTimeRangeMax: 6.5, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("0.000000000000000000"), // 25 million kava per year - communityPoolFunds: sdkmath.NewInt(100000000000000), - expectedRewardsTotal: sdkmath.NewInt(0), - }, - // - // - // Test underlying calculations are safe and overflow/underflow bounds are reasonable - // - // - { - name: "does not overflow with extremely large per second value and extremely large single block durations", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2033, 1, 1, 0, 0, 0, 0, time.UTC), - blockTimeRangeMin: 315619200, // a single 10 year long block in seconds (w/ 3 leap years) - blockTimeRangeMax: 315619200, // a single 10 year long block in seconds (w/ 3 leap years) - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("100000000000000000000000000.000000000000000000"), // 100 million kava per second in 18 decimal form - communityPoolFunds: newIntFromString("40000000000000000000000000000000000"), - expectedRewardsTotal: newIntFromString("31561920000000000000000000000000000"), // 10 years worth of rewards (with three leap years) - }, - { - name: "able to accumulate decimal ukava units across blocks", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2023, 1, 2, 0, 0, 0, 0, time.UTC), - blockTimeRangeMin: 5.5, - blockTimeRangeMax: 6.5, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("0.100000000000000000"), // blocks are not long enough to accumulate a single ukava with this rate - communityPoolFunds: sdkmath.NewInt(10000), - expectedRewardsTotal: sdkmath.NewInt(8640), - }, - { - name: "down to 1 ukava per year can be accumulated -- we are safe from underflow at reasonably small values", - periodStart: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), - periodEnd: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC), - blockTimeRangeMin: 60, // large block times speed up this test case - blockTimeRangeMax: 120, - rewardsPerSecond: sdkmath.LegacyMustNewDecFromStr("0.000000031709791984"), - communityPoolFunds: sdkmath.NewInt(1), - expectedRewardsTotal: sdkmath.NewInt(1), - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - // keepers - keeper := suite.Keeper - accountKeeper := suite.App.GetAccountKeeper() - bankKeeper := suite.App.GetBankKeeper() - - // initial context at height 1 - height := int64(1) - blockTime := tc.periodStart - ctx := suite.App.NewContext(true, tmproto.Header{Height: height, Time: blockTime}) - - // ensure community pool balance matches the test expectations - poolAcc := accountKeeper.GetModuleAccount(ctx, types.ModuleName) - // community pool balance should start at zero - suite.Require().True(bankKeeper.GetBalance(ctx, poolAcc.GetAddress(), "ukava").Amount.IsZero(), "expected community pool to start with zero coins in test genesis") - // fund withexact amount from test case - suite.App.FundAccount(ctx, poolAcc.GetAddress(), sdk.NewCoins(sdk.NewCoin("ukava", tc.communityPoolFunds))) - - // get starting balance of fee collector to substract later in case this is non-zero in genesis - feeCollectorAcc := accountKeeper.GetModuleAccount(ctx, authtypes.FeeCollectorName) - initialFeeCollectorBalance := bankKeeper.GetBalance(ctx, feeCollectorAcc.GetAddress(), "ukava").Amount - - // set rewards per second in state - params, found := keeper.GetParams(ctx) - suite.Require().True(found) - params.StakingRewardsPerSecond = tc.rewardsPerSecond - keeper.SetParams(ctx, params) - - stakingRewardEvents := sdk.Events{} - - for { - // run community begin blocker logic - suite.testFunc(ctx, keeper) - - // accumulate event rewards from events - stakingRewardEvents = append(stakingRewardEvents, filterStakingRewardEvents(ctx.EventManager().Events())...) - - // exit loop if we are at last block - if blockTime.Equal(tc.periodEnd) { - break - } - - // create random block duration in nanoseconds - randomBlockDurationInSeconds := tc.blockTimeRangeMin + rand.Float64()*(tc.blockTimeRangeMax-tc.blockTimeRangeMin) - nextBlockDuration := time.Duration(randomBlockDurationInSeconds * math.Pow10(9)) - - // move to next block by incrementing height, adding random duration, and settings new context - height++ - blockTime = blockTime.Add(nextBlockDuration) - // set last block to exact end of period if we go past - if blockTime.After(tc.periodEnd) { - blockTime = tc.periodEnd - } - ctx = suite.App.NewContext(true, tmproto.Header{Height: height, Time: blockTime}) - } - - endingFeeCollectorBalance := bankKeeper.GetBalance(ctx, feeCollectorAcc.GetAddress(), "ukava").Amount - feeCollectorBalanceAdded := endingFeeCollectorBalance.Sub(initialFeeCollectorBalance) - - // assert fee pool was payed the correct rewards - suite.Equal(tc.expectedRewardsTotal.String(), feeCollectorBalanceAdded.String(), "expected fee collector balance to match") - - if tc.expectedRewardsTotal.IsZero() { - suite.Equal(0, len(stakingRewardEvents), "expected no events to be emitted") - } else { - // we add up all reward coin events - eventCoins := getRewardCoinsFromEvents(stakingRewardEvents) - - // assert events emitted match expected rewards - suite.Equal( - tc.expectedRewardsTotal.String(), - eventCoins.AmountOf("ukava").String(), - "expected event coins to match", - ) - } - - // assert the community pool deducted the same amount - expectedCommunityPoolBalance := tc.communityPoolFunds.Sub(tc.expectedRewardsTotal) - actualCommunityPoolBalance := bankKeeper.GetBalance(ctx, poolAcc.GetAddress(), "ukava").Amount - suite.Equal(expectedCommunityPoolBalance.String(), actualCommunityPoolBalance.String(), "expected community pool balance to match") - }) - } - -} - -func (suite *stakingRewardsTestSuite) TestStakingRewardsDoNotAccumulateWhenPoolIsDrained() { - app := suite.App - keeper := suite.Keeper - accountKeeper := suite.App.GetAccountKeeper() - bankKeeper := suite.App.GetBankKeeper() - - // first block - blockTime := time.Now() - ctx := app.NewContext(true, tmproto.Header{Height: 1, Time: blockTime}) - - poolAcc := accountKeeper.GetModuleAccount(ctx, types.ModuleName) - feeCollectorAcc := accountKeeper.GetModuleAccount(ctx, authtypes.FeeCollectorName) - - // set state to pay staking rewards - params, _ := keeper.GetParams(ctx) - // we set a decimal amount that ensures after 10 seconds we overspend the community pool - // with enough truncation error that we would have an ending balance of 20.000001 if it was - // carried over after the pool run out of funds - params.StakingRewardsPerSecond = sdkmath.LegacyMustNewDecFromStr("1000000.099999999999999999") // > 1 KAVA per second - keeper.SetParams(ctx, params) - - // fund community pool account - app.FundAccount(ctx, poolAcc.GetAddress(), sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10000000)))) // 10 KAVA - initialFeeCollectorBalance := bankKeeper.GetBalance(ctx, feeCollectorAcc.GetAddress(), "ukava").Amount - - // run first block (no rewards hapeen on first block) - community.BeginBlocker(ctx, keeper) - - // run second block 10 seconds in future and spend all community pool rewards - blockTime = blockTime.Add(10 * time.Second) - ctx = app.NewContext(true, tmproto.Header{Height: 2, Time: blockTime}) - community.BeginBlocker(ctx, keeper) - - // run third block 10 seconds in future which no rewards will be paid - blockTime = blockTime.Add(10 * time.Second) - ctx = app.NewContext(true, tmproto.Header{Height: 3, Time: blockTime}) - community.BeginBlocker(ctx, keeper) - - // run fourth block 10 seconds in future which no rewards will be paid - blockTime = blockTime.Add(10 * time.Second) - ctx = app.NewContext(true, tmproto.Header{Height: 4, Time: blockTime}) - community.BeginBlocker(ctx, keeper) - - // refund the community pool with 100 KAVA -- plenty of funds - app.FundAccount(ctx, poolAcc.GetAddress(), sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100000000)))) // 100 KAVA - - // run fifth block 10 seconds in future which no rewards will be paid - blockTime = blockTime.Add(10 * time.Second) - ctx = app.NewContext(true, tmproto.Header{Height: 5, Time: blockTime}) - community.BeginBlocker(ctx, keeper) - - // assert that only 20 total KAVA has been distributed in rewards - // and blocks where community pool had d - rewards := bankKeeper.GetBalance(ctx, feeCollectorAcc.GetAddress(), "ukava").Amount.Sub(initialFeeCollectorBalance) - suite.Require().Equal(sdkmath.NewInt(20000000).String(), rewards.String()) -} - -func (suite *stakingRewardsTestSuite) TestPanicsOnMissingParameters() { - suite.SetupTest() - - ctx := suite.App.NewContext(true, tmproto.Header{Height: 1, Time: time.Now()}) - store := ctx.KVStore(suite.App.GetKVStoreKey(types.StoreKey)) - store.Delete(types.ParamsKey) - - suite.PanicsWithValue("invalid state: module parameters not found", func() { - suite.testFunc(ctx, suite.Keeper) - }) -} - -// newIntFromString returns a new sdkmath.Int from a string -func newIntFromString(str string) sdkmath.Int { - num, ok := sdkmath.NewIntFromString(str) - if !ok { - panic(fmt.Sprintf("overflow creating Int from %s", str)) - } - return num -} - -func filterStakingRewardEvents(events sdk.Events) (rewardEvents sdk.Events) { - for _, event := range events { - if event.Type == types.EventTypeStakingRewardsPaid { - rewardEvents = append(rewardEvents, event) - } - } - - return -} - -func getRewardCoinsFromEvents(events sdk.Events) sdk.Coins { - coins := sdk.NewCoins() - - for _, event := range events { - if event.Type == types.EventTypeStakingRewardsPaid { - rewards, err := sdk.ParseCoinNormalized(string(event.Attributes[0].Value)) - if err != nil { - panic(err) - } - - coins = coins.Add(rewards) - } - } - - return coins -} diff --git a/x/community/types/codec.go b/x/community/types/codec.go deleted file mode 100644 index 9c20c18f..00000000 --- a/x/community/types/codec.go +++ /dev/null @@ -1,54 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/legacy" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - legacy.RegisterAminoMsg(cdc, &MsgFundCommunityPool{}, "community/MsgFundCommunityPool") - legacy.RegisterAminoMsg(cdc, &MsgUpdateParams{}, "community/MsgUpdateParams") - - cdc.RegisterConcrete(&CommunityPoolLendDepositProposal{}, "kava/CommunityPoolLendDepositProposal", nil) - cdc.RegisterConcrete(&CommunityPoolLendWithdrawProposal{}, "kava/CommunityPoolLendWithdrawProposal", nil) - cdc.RegisterConcrete(&CommunityCDPRepayDebtProposal{}, "kava/CommunityCDPRepayDebtProposal", nil) - cdc.RegisterConcrete(&CommunityCDPWithdrawCollateralProposal{}, "kava/CommunityCDPWithdrawCollateralProposal", nil) -} - -// RegisterInterfaces registers proto messages under their interfaces for unmarshalling, -// in addition to registering the msg service for handling tx msgs. -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgFundCommunityPool{}, - &MsgUpdateParams{}, - ) - registry.RegisterImplementations((*govv1beta1.Content)(nil), - &CommunityPoolLendDepositProposal{}, - &CommunityPoolLendWithdrawProposal{}, - &CommunityCDPRepayDebtProposal{}, - &CommunityCDPWithdrawCollateralProposal{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/community/types/errors.go b/x/community/types/errors.go deleted file mode 100644 index 64f4b109..00000000 --- a/x/community/types/errors.go +++ /dev/null @@ -1,5 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -var ErrInvalidParams = errorsmod.Register(ModuleName, 1, "invalid params") diff --git a/x/community/types/events.go b/x/community/types/events.go deleted file mode 100644 index c9c0d126..00000000 --- a/x/community/types/events.go +++ /dev/null @@ -1,13 +0,0 @@ -package types - -// Community module event types -const ( - EventTypeInflationStop = "inflation_stop" - EventTypeStakingRewardsPaid = "staking_rewards_paid" - - AttributeKeyStakingRewardAmount = "staking_reward_amount" - AttributeKeyInflationDisableTime = "inflation_disable_time" - - AttributeValueFundCommunityPool = "fund_community_pool" - AttributeValueCategory = ModuleName -) diff --git a/x/community/types/expected_keepers.go b/x/community/types/expected_keepers.go deleted file mode 100644 index c372473f..00000000 --- a/x/community/types/expected_keepers.go +++ /dev/null @@ -1,69 +0,0 @@ -package types - -import ( - sdkmath "cosmossdk.io/math" - kavadisttypes "github.com/0glabs/0g-chain/x/kavadist/types" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" -) - -// AccountKeeper defines the contract required for account APIs. -type AccountKeeper interface { - GetModuleAccount(ctx sdk.Context, moduleName string) authtypes.ModuleAccountI - GetModuleAddress(name string) sdk.AccAddress -} - -// BankKeeper defines the contract needed to be fulfilled for banking dependencies. -type BankKeeper interface { - GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error - - GetSupply(ctx sdk.Context, denom string) sdk.Coin -} - -// CdpKeeper defines the contract needed to be fulfilled for cdp dependencies. -type CdpKeeper interface { - RepayPrincipal(ctx sdk.Context, owner sdk.AccAddress, collateralType string, payment sdk.Coin) error - WithdrawCollateral(ctx sdk.Context, owner, depositor sdk.AccAddress, collateral sdk.Coin, collateralType string) error -} - -// HardKeeper defines the contract needed to be fulfilled for Kava Lend dependencies. -type HardKeeper interface { - Deposit(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error - Withdraw(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error -} - -// DistributionKeeper defines the contract needed to be fulfilled for distribution dependencies. -type DistributionKeeper interface { - DistributeFromFeePool(ctx sdk.Context, amount sdk.Coins, receiveAddr sdk.AccAddress) error - FundCommunityPool(ctx sdk.Context, amount sdk.Coins, sender sdk.AccAddress) error - GetFeePoolCommunityCoins(ctx sdk.Context) sdk.DecCoins - GetFeePool(ctx sdk.Context) distrtypes.FeePool - SetFeePool(ctx sdk.Context, feePool distrtypes.FeePool) - GetParams(ctx sdk.Context) distrtypes.Params - SetParams(ctx sdk.Context, params distrtypes.Params) error - GetCommunityTax(ctx sdk.Context) sdk.Dec -} - -type MintKeeper interface { - GetParams(ctx sdk.Context) (params minttypes.Params) - SetParams(ctx sdk.Context, params minttypes.Params) error - GetMinter(ctx sdk.Context) (minter minttypes.Minter) -} - -type KavadistKeeper interface { - GetParams(ctx sdk.Context) (params kavadisttypes.Params) - SetParams(ctx sdk.Context, params kavadisttypes.Params) -} - -// StakingKeeper expected interface for the staking keeper -type StakingKeeper interface { - BondDenom(ctx sdk.Context) string - TotalBondedTokens(ctx sdk.Context) sdkmath.Int -} diff --git a/x/community/types/genesis.go b/x/community/types/genesis.go deleted file mode 100644 index 2d75fdec..00000000 --- a/x/community/types/genesis.go +++ /dev/null @@ -1,26 +0,0 @@ -package types - -// NewGenesisState returns a new genesis state object -func NewGenesisState(params Params, stakingRewardsState StakingRewardsState) GenesisState { - return GenesisState{ - Params: params, - StakingRewardsState: stakingRewardsState, - } -} - -// DefaultGenesisState returns default genesis state -func DefaultGenesisState() GenesisState { - return NewGenesisState( - DefaultParams(), - DefaultStakingRewardsState(), - ) -} - -// Validate checks the params are valid -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - - return gs.StakingRewardsState.Validate() -} diff --git a/x/community/types/genesis.pb.go b/x/community/types/genesis.pb.go deleted file mode 100644 index 8931aee8..00000000 --- a/x/community/types/genesis.pb.go +++ /dev/null @@ -1,383 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/community/v1beta1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// GenesisState defines the community module's genesis state. -type GenesisState struct { - // params defines all the parameters related to commmunity - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - // StakingRewardsState stores the internal staking reward data required to - // track staking rewards across blocks - StakingRewardsState StakingRewardsState `protobuf:"bytes,2,opt,name=staking_rewards_state,json=stakingRewardsState,proto3" json:"staking_rewards_state"` -} - -func (m *GenesisState) Reset() { *m = GenesisState{} } -func (m *GenesisState) String() string { return proto.CompactTextString(m) } -func (*GenesisState) ProtoMessage() {} -func (*GenesisState) Descriptor() ([]byte, []int) { - return fileDescriptor_ccf84d82ea3861e0, []int{0} -} -func (m *GenesisState) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisState) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisState.Merge(m, src) -} -func (m *GenesisState) XXX_Size() int { - return m.Size() -} -func (m *GenesisState) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisState.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisState proto.InternalMessageInfo - -func (m *GenesisState) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -func (m *GenesisState) GetStakingRewardsState() StakingRewardsState { - if m != nil { - return m.StakingRewardsState - } - return StakingRewardsState{} -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "kava.community.v1beta1.GenesisState") -} - -func init() { - proto.RegisterFile("kava/community/v1beta1/genesis.proto", fileDescriptor_ccf84d82ea3861e0) -} - -var fileDescriptor_ccf84d82ea3861e0 = []byte{ - // 261 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xc9, 0x4e, 0x2c, 0x4b, - 0xd4, 0x4f, 0xce, 0xcf, 0xcd, 0x2d, 0xcd, 0xcb, 0x2c, 0xa9, 0xd4, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, - 0x49, 0x34, 0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, - 0x17, 0x12, 0x03, 0xa9, 0xd2, 0x83, 0xab, 0xd2, 0x83, 0xaa, 0x92, 0x12, 0x49, 0xcf, 0x4f, 0xcf, - 0x07, 0x2b, 0xd1, 0x07, 0xb1, 0x20, 0xaa, 0xa5, 0x94, 0x71, 0x98, 0x59, 0x90, 0x58, 0x94, 0x98, - 0x0b, 0x35, 0x52, 0x0a, 0x97, 0xc5, 0xc5, 0x25, 0x89, 0xd9, 0x99, 0x79, 0xe9, 0x10, 0x55, 0x4a, - 0x9b, 0x19, 0xb9, 0x78, 0xdc, 0x21, 0x4e, 0x09, 0x2e, 0x49, 0x2c, 0x49, 0x15, 0xb2, 0xe1, 0x62, - 0x83, 0x18, 0x23, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0x6d, 0x24, 0xa7, 0x87, 0xdd, 0x69, 0x7a, 0x01, - 0x60, 0x55, 0x4e, 0x2c, 0x27, 0xee, 0xc9, 0x33, 0x04, 0x41, 0xf5, 0x08, 0xa5, 0x72, 0x89, 0x42, - 0xcd, 0x8f, 0x2f, 0x4a, 0x2d, 0x4f, 0x2c, 0x4a, 0x29, 0x8e, 0x2f, 0x06, 0x19, 0x2b, 0xc1, 0x04, - 0x36, 0x4c, 0x1b, 0x97, 0x61, 0xc1, 0x10, 0x4d, 0x41, 0x10, 0x3d, 0x60, 0x97, 0x40, 0x4d, 0x16, - 0x2e, 0xc6, 0x22, 0xe5, 0x76, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, - 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0x3a, - 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x20, 0x2b, 0xf4, 0x0d, 0xd2, 0x73, 0x12, 0x93, 0x8a, 0xf5, - 0x0d, 0xd2, 0x75, 0x93, 0x33, 0x12, 0x33, 0xf3, 0xf4, 0x2b, 0x90, 0x42, 0xa3, 0xa4, 0xb2, 0x20, - 0xb5, 0x38, 0x89, 0x0d, 0x1c, 0x08, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x10, 0xbe, 0x7c, - 0x73, 0xa5, 0x01, 0x00, 0x00, -} - -func (m *GenesisState) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.StakingRewardsState.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *GenesisState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.StakingRewardsState.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *GenesisState) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field StakingRewardsState", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.StakingRewardsState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/community/types/genesis_test.go b/x/community/types/genesis_test.go deleted file mode 100644 index 9fecea13..00000000 --- a/x/community/types/genesis_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/0glabs/0g-chain/x/community/types" -) - -func TestDefaultGenesisState(t *testing.T) { - defaultGen := types.DefaultGenesisState() - - require.NoError(t, defaultGen.Validate()) - require.Equal(t, types.DefaultParams(), defaultGen.Params) - require.Equal(t, types.DefaultStakingRewardsState(), defaultGen.StakingRewardsState) -} - -func TestGenesisState_ValidateParams(t *testing.T) { - for _, tc := range paramTestCases { - t.Run(tc.name, func(t *testing.T) { - genState := types.DefaultGenesisState() - genState.Params = tc.params - - err := genState.Validate() - - if tc.expectedErr == "" { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), tc.expectedErr) - } - }) - } -} - -func TestGenesisState_ValidateStakingRewardsState(t *testing.T) { - for _, tc := range stakingRewardsStateTestCases { - t.Run(tc.name, func(t *testing.T) { - genState := types.DefaultGenesisState() - genState.StakingRewardsState = tc.stakingRewardsState - - err := genState.Validate() - - if tc.expectedErr == "" { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), tc.expectedErr) - } - }) - } -} diff --git a/x/community/types/keys.go b/x/community/types/keys.go deleted file mode 100644 index dc6f0a35..00000000 --- a/x/community/types/keys.go +++ /dev/null @@ -1,28 +0,0 @@ -package types - -const ( - // module name - ModuleName = "community" - - // ModuleAccountName is the name of the module's account - ModuleAccountName = ModuleName - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey is the top-level router key for the module - RouterKey = ModuleName - - // Query endpoints supported by community - QueryBalance = "balance" - - // LegacyCommunityPoolModuleName is the module account name used by the legacy community pool - // It is used to determine the address of the old community pool to be returned with the legacy balance. - LegacyCommunityPoolModuleName = "distribution" -) - -// key prefixes for store -var ( - ParamsKey = []byte{0x01} - StakingRewardsStateKey = []byte{0x02} -) diff --git a/x/community/types/msg.go b/x/community/types/msg.go deleted file mode 100644 index ff04fb6a..00000000 --- a/x/community/types/msg.go +++ /dev/null @@ -1,102 +0,0 @@ -package types - -import ( - 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/auth/migrations/legacytx" -) - -// ensure Msg interface compliance at compile time -var ( - _ sdk.Msg = &MsgFundCommunityPool{} - _ legacytx.LegacyMsg = &MsgFundCommunityPool{} - _ sdk.Msg = &MsgUpdateParams{} - _ legacytx.LegacyMsg = &MsgUpdateParams{} -) - -// NewMsgFundCommunityPool returns a new MsgFundCommunityPool -func NewMsgFundCommunityPool(depositor sdk.AccAddress, amount sdk.Coins) MsgFundCommunityPool { - return MsgFundCommunityPool{ - Depositor: depositor.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgFundCommunityPool) Route() string { return ModuleName } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgFundCommunityPool) Type() string { return sdk.MsgTypeURL(&msg) } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgFundCommunityPool) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if msg.Amount.IsAnyNil() || !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "'%s'", msg.Amount) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgFundCommunityPool) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgFundCommunityPool) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - panic(err) - } - return []sdk.AccAddress{depositor} -} - -// NewMsgUpdateParams returns a new MsgUpdateParams -func NewMsgUpdateParams(authority sdk.AccAddress, params Params) MsgUpdateParams { - return MsgUpdateParams{ - Authority: authority.String(), - Params: params, - } -} - -// Route return the message type used for routing the message. -func (msg MsgUpdateParams) Route() string { return ModuleName } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgUpdateParams) Type() string { return sdk.MsgTypeURL(&msg) } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgUpdateParams) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Authority) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if err := msg.Params.Validate(); err != nil { - return errorsmod.Wrap(ErrInvalidParams, err.Error()) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgUpdateParams) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgUpdateParams) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.Authority) - if err != nil { - panic(err) - } - return []sdk.AccAddress{depositor} -} diff --git a/x/community/types/msg_test.go b/x/community/types/msg_test.go deleted file mode 100644 index efdcd10d..00000000 --- a/x/community/types/msg_test.go +++ /dev/null @@ -1,163 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/community/types" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -func TestFundCommunityPool_ValidateBasic(t *testing.T) { - validCoins := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewIntFromUint64(1e6)), - sdk.NewCoin("some-denom", sdkmath.NewIntFromUint64(1e4)), - ) - testCases := []struct { - name string - shouldPass bool - message types.MsgFundCommunityPool - }{ - { - name: "valid message", - shouldPass: true, - message: types.NewMsgFundCommunityPool(app.RandomAddress(), validCoins), - }, - { - name: "invalid - bad depositor", - shouldPass: false, - message: types.MsgFundCommunityPool{ - Depositor: "not-an-address", - Amount: validCoins, - }, - }, - { - name: "invalid - empty coins", - shouldPass: false, - message: types.MsgFundCommunityPool{ - Depositor: app.RandomAddress().String(), - Amount: sdk.NewCoins(), - }, - }, - { - name: "invalid - nil coins", - shouldPass: false, - message: types.MsgFundCommunityPool{ - Depositor: app.RandomAddress().String(), - Amount: nil, - }, - }, - { - name: "invalid - zero coins", - shouldPass: false, - message: types.MsgFundCommunityPool{ - Depositor: app.RandomAddress().String(), - Amount: sdk.NewCoins( - sdk.NewCoin("ukava", sdk.ZeroInt()), - ), - }, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.message.ValidateBasic() - if tc.shouldPass { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } -} - -func TestMsgUpdateParams_ValidateBasic(t *testing.T) { - testCases := []struct { - name string - message types.MsgUpdateParams - expectedErr error - }{ - { - name: "valid message", - message: types.NewMsgUpdateParams(app.RandomAddress(), types.DefaultParams()), - expectedErr: nil, - }, - { - name: "invalid - bad authority", - message: types.MsgUpdateParams{ - Authority: "not-an-address", - Params: types.DefaultParams(), - }, - expectedErr: sdkerrors.ErrInvalidAddress, - }, - { - name: "invalid - empty authority", - message: types.MsgUpdateParams{ - Authority: "", - Params: types.DefaultParams(), - }, - expectedErr: sdkerrors.ErrInvalidAddress, - }, - { - name: "invalid - invalid params", - message: types.MsgUpdateParams{ - Authority: app.RandomAddress().String(), - Params: types.Params{}, - }, - expectedErr: types.ErrInvalidParams, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.message.ValidateBasic() - if tc.expectedErr == nil { - require.NoError(t, err) - } else { - require.ErrorIs(t, err, tc.expectedErr) - } - }) - } -} - -func TestFundCommunityPool_GetSigners(t *testing.T) { - t.Run("valid", func(t *testing.T) { - address := app.RandomAddress() - signers := types.MsgFundCommunityPool{ - Depositor: address.String(), - }.GetSigners() - require.Len(t, signers, 1) - require.Equal(t, address, signers[0]) - }) - - t.Run("panics when depositor is invalid", func(t *testing.T) { - require.Panics(t, func() { - types.MsgFundCommunityPool{ - Depositor: "not-an-address", - }.GetSigners() - }) - }) -} - -func TestMsgUpdateParams_GetSigners(t *testing.T) { - t.Run("valid", func(t *testing.T) { - address := app.RandomAddress() - signers := types.MsgUpdateParams{ - Authority: address.String(), - }.GetSigners() - require.Len(t, signers, 1) - require.Equal(t, address, signers[0]) - }) - - t.Run("panics when depositor is invalid", func(t *testing.T) { - require.Panics(t, func() { - types.MsgUpdateParams{ - Authority: "not-an-address", - }.GetSigners() - }) - }) -} diff --git a/x/community/types/params.go b/x/community/types/params.go deleted file mode 100644 index f6fd1aef..00000000 --- a/x/community/types/params.go +++ /dev/null @@ -1,65 +0,0 @@ -package types - -import ( - fmt "fmt" - "time" - - sdkmath "cosmossdk.io/math" -) - -var ( - DefaultUpgradeTimeDisableInflation = time.Time{} - // DefaultStakingRewardsPerSecond is zero and should be set by genesis or upgrade - DefaultStakingRewardsPerSecond = sdkmath.LegacyNewDec(0) - // DefaultStakingRewardsPerSecond is zero and should be set by genesis or upgrade - DefaultUpgradeTimeSetStakingRewardsPerSecond = sdkmath.LegacyNewDec(0) -) - -// NewParams returns a new params object -func NewParams( - upgradeTime time.Time, - stakingRewardsPerSecond sdkmath.LegacyDec, - upgradeTimeSetstakingRewardsPerSecond sdkmath.LegacyDec, -) Params { - return Params{ - UpgradeTimeDisableInflation: upgradeTime, - StakingRewardsPerSecond: stakingRewardsPerSecond, - UpgradeTimeSetStakingRewardsPerSecond: upgradeTimeSetstakingRewardsPerSecond, - } -} - -// DefaultParams returns default params -func DefaultParams() Params { - return NewParams( - DefaultUpgradeTimeDisableInflation, - DefaultStakingRewardsPerSecond, - DefaultUpgradeTimeSetStakingRewardsPerSecond, - ) -} - -// Validate checks the params are valid -func (p Params) Validate() error { - // p.UpgradeTimeDisableInflation.IsZero() is a valid state. It's taken to mean inflation will be disabled on the block 1. - - if err := validateDecNotNilNonNegative(p.StakingRewardsPerSecond, "StakingRewardsPerSecond"); err != nil { - return err - } - - if err := validateDecNotNilNonNegative(p.UpgradeTimeSetStakingRewardsPerSecond, "UpgradeTimeSetStakingRewardsPerSecond"); err != nil { - return err - } - - return nil -} - -func validateDecNotNilNonNegative(value sdkmath.LegacyDec, name string) error { - if value.IsNil() { - return fmt.Errorf("%s should not be nil", name) - } - - if value.IsNegative() { - return fmt.Errorf("%s should not be negative: %s", name, value) - } - - return nil -} diff --git a/x/community/types/params.pb.go b/x/community/types/params.pb.go deleted file mode 100644 index 437eba26..00000000 --- a/x/community/types/params.pb.go +++ /dev/null @@ -1,468 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/community/v1beta1/params.proto - -package types - -import ( - cosmossdk_io_math "cosmossdk.io/math" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// Params defines the parameters of the community module. -type Params struct { - // upgrade_time_disable_inflation is the time at which to disable mint and kavadist module inflation. - // If set to 0, inflation will be disabled from block 1. - UpgradeTimeDisableInflation time.Time `protobuf:"bytes,1,opt,name=upgrade_time_disable_inflation,json=upgradeTimeDisableInflation,proto3,stdtime" json:"upgrade_time_disable_inflation"` - // staking_rewards_per_second is the amount paid out to delegators each block from the community account - StakingRewardsPerSecond cosmossdk_io_math.LegacyDec `protobuf:"bytes,2,opt,name=staking_rewards_per_second,json=stakingRewardsPerSecond,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"staking_rewards_per_second"` - // upgrade_time_set_staking_rewards_per_second is the initial staking_rewards_per_second to set - // and use when the disable inflation time is reached - UpgradeTimeSetStakingRewardsPerSecond cosmossdk_io_math.LegacyDec `protobuf:"bytes,3,opt,name=upgrade_time_set_staking_rewards_per_second,json=upgradeTimeSetStakingRewardsPerSecond,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"upgrade_time_set_staking_rewards_per_second"` -} - -func (m *Params) Reset() { *m = Params{} } -func (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_0a48475520900507, []int{0} -} -func (m *Params) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Params.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Params) XXX_Merge(src proto.Message) { - xxx_messageInfo_Params.Merge(m, src) -} -func (m *Params) XXX_Size() int { - return m.Size() -} -func (m *Params) XXX_DiscardUnknown() { - xxx_messageInfo_Params.DiscardUnknown(m) -} - -var xxx_messageInfo_Params proto.InternalMessageInfo - -func (m *Params) GetUpgradeTimeDisableInflation() time.Time { - if m != nil { - return m.UpgradeTimeDisableInflation - } - return time.Time{} -} - -func init() { - proto.RegisterType((*Params)(nil), "kava.community.v1beta1.Params") -} - -func init() { - proto.RegisterFile("kava/community/v1beta1/params.proto", fileDescriptor_0a48475520900507) -} - -var fileDescriptor_0a48475520900507 = []byte{ - // 390 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x92, 0xb1, 0x6a, 0xe3, 0x30, - 0x18, 0x80, 0xad, 0xdc, 0x11, 0xee, 0x7c, 0x9b, 0x39, 0xee, 0x72, 0x0e, 0xd8, 0xe1, 0x8e, 0x83, - 0x40, 0x1b, 0x29, 0x69, 0xb7, 0x8e, 0x21, 0x14, 0x0a, 0x1d, 0x42, 0xd2, 0xa9, 0x8b, 0x90, 0x6d, - 0x45, 0x11, 0xb1, 0x2d, 0x63, 0xc9, 0x69, 0xf3, 0x10, 0x85, 0x3c, 0x42, 0x1f, 0xa2, 0x0f, 0x91, - 0x31, 0x74, 0x2a, 0x1d, 0xd2, 0x92, 0x2c, 0x7d, 0x85, 0x6e, 0xc5, 0x96, 0x53, 0x52, 0x28, 0x1d, - 0xba, 0xe9, 0xff, 0xf5, 0xe9, 0xd3, 0xff, 0x4b, 0xbf, 0xf9, 0x6f, 0x42, 0xa6, 0x04, 0xf9, 0x22, - 0x8a, 0xb2, 0x98, 0xab, 0x19, 0x9a, 0x76, 0x3c, 0xaa, 0x48, 0x07, 0x25, 0x24, 0x25, 0x91, 0x84, - 0x49, 0x2a, 0x94, 0xb0, 0x7e, 0xe5, 0x10, 0x7c, 0x85, 0x60, 0x09, 0xd9, 0x7f, 0x7c, 0x21, 0x23, - 0x21, 0x71, 0x41, 0x21, 0x1d, 0xe8, 0x23, 0xf6, 0x4f, 0x26, 0x98, 0xd0, 0xf9, 0x7c, 0x55, 0x66, - 0x5d, 0x26, 0x04, 0x0b, 0x29, 0x2a, 0x22, 0x2f, 0x1b, 0x21, 0xc5, 0x23, 0x2a, 0x15, 0x89, 0x12, - 0x0d, 0xfc, 0x7d, 0xae, 0x98, 0xd5, 0x7e, 0x71, 0xb5, 0xc5, 0x4d, 0x27, 0x4b, 0x58, 0x4a, 0x02, - 0x8a, 0x73, 0x0a, 0x07, 0x5c, 0x12, 0x2f, 0xa4, 0x98, 0xc7, 0xa3, 0x90, 0x28, 0x2e, 0xe2, 0x1a, - 0x68, 0x80, 0xe6, 0x8f, 0x03, 0x1b, 0x6a, 0x29, 0xdc, 0x4a, 0xe1, 0xd9, 0x56, 0xda, 0xfd, 0xb6, - 0x58, 0xb9, 0xc6, 0xfc, 0xc1, 0x05, 0x83, 0x7a, 0xe9, 0xca, 0xf7, 0x7a, 0xda, 0x74, 0xb2, 0x15, - 0x59, 0xb1, 0x69, 0x4b, 0x45, 0x26, 0x3c, 0x66, 0x38, 0xa5, 0x17, 0x24, 0x0d, 0x24, 0x4e, 0x68, - 0x8a, 0x25, 0xf5, 0x45, 0x1c, 0xd4, 0x2a, 0x0d, 0xd0, 0xfc, 0xde, 0xed, 0xe4, 0xaa, 0xfb, 0x95, - 0x5b, 0xd7, 0x6d, 0xca, 0x60, 0x02, 0xb9, 0x40, 0x11, 0x51, 0x63, 0x78, 0x4a, 0x19, 0xf1, 0x67, - 0x3d, 0xea, 0xdf, 0xde, 0xb4, 0xcc, 0xf2, 0x15, 0x7a, 0xd4, 0x1f, 0xfc, 0x2e, 0xa5, 0x03, 0xed, - 0xec, 0xd3, 0x74, 0x58, 0x18, 0xad, 0x2b, 0x60, 0xee, 0xbd, 0xe9, 0x4d, 0x52, 0x85, 0x3f, 0xa8, - 0xe0, 0xcb, 0x67, 0x2b, 0xf8, 0xbf, 0xd3, 0xf5, 0x90, 0xaa, 0xe1, 0xfb, 0xf5, 0x1c, 0x7d, 0x7d, - 0xba, 0x76, 0x41, 0xf7, 0x78, 0xb1, 0x76, 0xc0, 0x72, 0xed, 0x80, 0xc7, 0xb5, 0x03, 0xe6, 0x1b, - 0xc7, 0x58, 0x6e, 0x1c, 0xe3, 0x6e, 0xe3, 0x18, 0xe7, 0xfb, 0x8c, 0xab, 0x71, 0xe6, 0xe5, 0x13, - 0x80, 0xda, 0x2c, 0x24, 0x9e, 0x44, 0x6d, 0xd6, 0xf2, 0xc7, 0x84, 0xc7, 0xe8, 0x72, 0x67, 0x78, - 0xd4, 0x2c, 0xa1, 0xd2, 0xab, 0x16, 0x1f, 0x71, 0xf8, 0x12, 0x00, 0x00, 0xff, 0xff, 0x68, 0x69, - 0x63, 0xfc, 0x5b, 0x02, 0x00, 0x00, -} - -func (this *Params) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*Params) - if !ok { - that2, ok := that.(Params) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if !this.UpgradeTimeDisableInflation.Equal(that1.UpgradeTimeDisableInflation) { - return false - } - if !this.StakingRewardsPerSecond.Equal(that1.StakingRewardsPerSecond) { - return false - } - if !this.UpgradeTimeSetStakingRewardsPerSecond.Equal(that1.UpgradeTimeSetStakingRewardsPerSecond) { - return false - } - return true -} -func (m *Params) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Params) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.UpgradeTimeSetStakingRewardsPerSecond.Size() - i -= size - if _, err := m.UpgradeTimeSetStakingRewardsPerSecond.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.StakingRewardsPerSecond.Size() - i -= size - if _, err := m.StakingRewardsPerSecond.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - n1, err1 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.UpgradeTimeDisableInflation, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.UpgradeTimeDisableInflation):]) - if err1 != nil { - return 0, err1 - } - i -= n1 - i = encodeVarintParams(dAtA, i, uint64(n1)) - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintParams(dAtA []byte, offset int, v uint64) int { - offset -= sovParams(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.UpgradeTimeDisableInflation) - n += 1 + l + sovParams(uint64(l)) - l = m.StakingRewardsPerSecond.Size() - n += 1 + l + sovParams(uint64(l)) - l = m.UpgradeTimeSetStakingRewardsPerSecond.Size() - n += 1 + l + sovParams(uint64(l)) - return n -} - -func sovParams(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozParams(x uint64) (n int) { - return sovParams(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Params) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Params: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field UpgradeTimeDisableInflation", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.UpgradeTimeDisableInflation, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field StakingRewardsPerSecond", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.StakingRewardsPerSecond.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field UpgradeTimeSetStakingRewardsPerSecond", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.UpgradeTimeSetStakingRewardsPerSecond.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParams(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParams - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipParams(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParams - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParams - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParams - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthParams - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupParams - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthParams - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthParams = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowParams = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupParams = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/community/types/params_test.go b/x/community/types/params_test.go deleted file mode 100644 index 8983666e..00000000 --- a/x/community/types/params_test.go +++ /dev/null @@ -1,103 +0,0 @@ -package types_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - "github.com/0glabs/0g-chain/x/community/types" -) - -type paramTestCase struct { - name string - params types.Params - expectedErr string -} - -var paramTestCases = []paramTestCase{ - { - name: "default params are valid", - params: types.DefaultParams(), - expectedErr: "", - }, - { - name: "valid params", - params: types.Params{ - UpgradeTimeDisableInflation: time.Time{}, - StakingRewardsPerSecond: sdkmath.LegacyNewDec(1000), - UpgradeTimeSetStakingRewardsPerSecond: sdkmath.LegacyNewDec(1000), - }, - expectedErr: "", - }, - { - name: "rewards per second are allowed to be zero", - params: types.Params{ - UpgradeTimeDisableInflation: time.Time{}, - StakingRewardsPerSecond: sdkmath.LegacyNewDec(0), - UpgradeTimeSetStakingRewardsPerSecond: sdkmath.LegacyNewDec(1000), - }, - expectedErr: "", - }, - { - name: "nil rewards per second", - params: types.Params{ - UpgradeTimeDisableInflation: time.Time{}, - StakingRewardsPerSecond: sdkmath.LegacyDec{}, - UpgradeTimeSetStakingRewardsPerSecond: sdkmath.LegacyNewDec(1000), - }, - expectedErr: "StakingRewardsPerSecond should not be nil", - }, - { - name: "negative rewards per second", - params: types.Params{ - UpgradeTimeDisableInflation: time.Time{}, - StakingRewardsPerSecond: sdkmath.LegacyNewDec(-5), - UpgradeTimeSetStakingRewardsPerSecond: sdkmath.LegacyNewDec(1000), - }, - expectedErr: "StakingRewardsPerSecond should not be negative", - }, - { - name: "upgrade time set rewards per second are allowed to be zero", - params: types.Params{ - UpgradeTimeDisableInflation: time.Time{}, - StakingRewardsPerSecond: sdkmath.LegacyNewDec(1000), - UpgradeTimeSetStakingRewardsPerSecond: sdkmath.LegacyNewDec(0), - }, - expectedErr: "", - }, - { - name: "nil upgrade time set rewards per second", - params: types.Params{ - UpgradeTimeDisableInflation: time.Time{}, - StakingRewardsPerSecond: sdkmath.LegacyNewDec(1000), - UpgradeTimeSetStakingRewardsPerSecond: sdkmath.LegacyDec{}, - }, - expectedErr: "UpgradeTimeSetStakingRewardsPerSecond should not be nil", - }, - { - name: "upgrade time set negative rewards per second", - params: types.Params{ - UpgradeTimeDisableInflation: time.Time{}, - StakingRewardsPerSecond: sdkmath.LegacyNewDec(1000), - UpgradeTimeSetStakingRewardsPerSecond: sdkmath.LegacyNewDec(-5), - }, - expectedErr: "UpgradeTimeSetStakingRewardsPerSecond should not be negative", - }, -} - -func TestParamsValidate(t *testing.T) { - for _, tc := range paramTestCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.params.Validate() - - if tc.expectedErr == "" { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), tc.expectedErr) - } - }) - } -} diff --git a/x/community/types/proposal.go b/x/community/types/proposal.go deleted file mode 100644 index 9000fc29..00000000 --- a/x/community/types/proposal.go +++ /dev/null @@ -1,259 +0,0 @@ -package types - -import ( - "errors" - fmt "fmt" - "strings" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - govcodec "github.com/cosmos/cosmos-sdk/x/gov/codec" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -const ( - // ProposalTypeCommunityPoolLendDeposit defines the type for a CommunityPoolLendDepositProposal - ProposalTypeCommunityPoolLendDeposit = "CommunityPoolLendDeposit" - // ProposalTypeCommunityPoolLendWithdraw defines the type for a CommunityPoolLendDepositProposal - ProposalTypeCommunityPoolLendWithdraw = "CommunityPoolLendWithdraw" - // ProposalTypeCommunityCDPRepayDebt defines the type for a CommunityCDPRepayDebtProposal - ProposalTypeCommunityCDPRepayDebt = "CommunityCDPRepayDebt" - // ProposalTypeCommunityCDPWithdrawCollateral defines the type for a CommunityCDPWithdrawCollateralProposal - ProposalTypeCommunityCDPWithdrawCollateral = "CommunityCDPWithdrawCollateral" -) - -// Assert CommunityPoolLendDepositProposal implements govtypes.Content at compile-time -var ( - _ govv1beta1.Content = &CommunityPoolLendDepositProposal{} - _ govv1beta1.Content = &CommunityPoolLendWithdrawProposal{} - _ govv1beta1.Content = &CommunityCDPRepayDebtProposal{} - _ govv1beta1.Content = &CommunityCDPWithdrawCollateralProposal{} -) - -func init() { - govv1beta1.RegisterProposalType(ProposalTypeCommunityPoolLendDeposit) - govcodec.ModuleCdc.Amino.RegisterConcrete(&CommunityPoolLendDepositProposal{}, "kava/CommunityPoolLendDepositProposal", nil) - govv1beta1.RegisterProposalType(ProposalTypeCommunityPoolLendWithdraw) - govcodec.ModuleCdc.Amino.RegisterConcrete(&CommunityPoolLendWithdrawProposal{}, "kava/CommunityPoolLendWithdrawProposal", nil) - govv1beta1.RegisterProposalType(ProposalTypeCommunityCDPRepayDebt) - govcodec.ModuleCdc.Amino.RegisterConcrete(&CommunityCDPRepayDebtProposal{}, "kava/CommunityCDPRepayDebtProposal", nil) - govv1beta1.RegisterProposalType(ProposalTypeCommunityCDPWithdrawCollateral) - govcodec.ModuleCdc.Amino.RegisterConcrete(&CommunityCDPWithdrawCollateralProposal{}, "kava/CommunityCDPWithdrawCollateralProposal", nil) -} - -////////////////// -// Lend Proposals -////////////////// - -// NewCommunityPoolLendDepositProposal creates a new community pool deposit proposal. -func NewCommunityPoolLendDepositProposal(title, description string, amount sdk.Coins) *CommunityPoolLendDepositProposal { - return &CommunityPoolLendDepositProposal{ - Title: title, - Description: description, - Amount: amount, - } -} - -// GetTitle returns the title of a community pool lend deposit proposal. -func (p *CommunityPoolLendDepositProposal) GetTitle() string { return p.Title } - -// GetDescription returns the description of a community pool lend deposit proposal. -func (p *CommunityPoolLendDepositProposal) GetDescription() string { return p.Description } - -// GetDescription returns the routing key of a community pool lend deposit proposal. -func (p *CommunityPoolLendDepositProposal) ProposalRoute() string { return ModuleName } - -// ProposalType returns the type of a community pool lend deposit proposal. -func (p *CommunityPoolLendDepositProposal) ProposalType() string { - return ProposalTypeCommunityPoolLendDeposit -} - -// String implements fmt.Stringer -func (p *CommunityPoolLendDepositProposal) String() string { - var b strings.Builder - b.WriteString(fmt.Sprintf(`Community Pool Lend Deposit Proposal: - Title: %s - Description: %s - Amount: %s -`, p.Title, p.Description, p.Amount)) - return b.String() -} - -// ValidateBasic stateless validation of a community pool lend deposit proposal. -func (p *CommunityPoolLendDepositProposal) ValidateBasic() error { - if err := govv1beta1.ValidateAbstract(p); err != nil { - return err - } - // ensure the proposal has valid amount - if !p.Amount.IsValid() || p.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "deposit amount %s", p.Amount) - } - return p.Amount.Validate() -} - -// NewCommunityPoolLendWithdrawProposal creates a new community pool lend withdraw proposal. -func NewCommunityPoolLendWithdrawProposal(title, description string, amount sdk.Coins) *CommunityPoolLendWithdrawProposal { - return &CommunityPoolLendWithdrawProposal{ - Title: title, - Description: description, - Amount: amount, - } -} - -// GetTitle returns the title of a community pool withdraw proposal. -func (p *CommunityPoolLendWithdrawProposal) GetTitle() string { return p.Title } - -// GetDescription returns the description of a community pool withdraw proposal. -func (p *CommunityPoolLendWithdrawProposal) GetDescription() string { return p.Description } - -// GetDescription returns the routing key of a community pool withdraw proposal. -func (p *CommunityPoolLendWithdrawProposal) ProposalRoute() string { return ModuleName } - -// ProposalType returns the type of a community pool withdraw proposal. -func (p *CommunityPoolLendWithdrawProposal) ProposalType() string { - return ProposalTypeCommunityPoolLendWithdraw -} - -// String implements fmt.Stringer -func (p *CommunityPoolLendWithdrawProposal) String() string { - var b strings.Builder - b.WriteString(fmt.Sprintf(`Community Pool Lend Withdraw Proposal: - Title: %s - Description: %s - Amount: %s -`, p.Title, p.Description, p.Amount)) - return b.String() -} - -// ValidateBasic stateless validation of a community pool withdraw proposal. -func (p *CommunityPoolLendWithdrawProposal) ValidateBasic() error { - if err := govv1beta1.ValidateAbstract(p); err != nil { - return err - } - // ensure the proposal has valid amount - if !p.Amount.IsValid() || p.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "withdraw amount %s", p.Amount) - } - return p.Amount.Validate() -} - -///////////////// -// CDP Proposals -///////////////// - -// NewCommunityCDPRepayDebtProposal creates a new community pool cdp debt repay proposal. -func NewCommunityCDPRepayDebtProposal( - title string, - description string, - collateralType string, - payment sdk.Coin, -) *CommunityCDPRepayDebtProposal { - return &CommunityCDPRepayDebtProposal{ - Title: title, - Description: description, - CollateralType: collateralType, - Payment: payment, - } -} - -// GetTitle returns the title of the proposal. -func (p *CommunityCDPRepayDebtProposal) GetTitle() string { return p.Title } - -// GetDescription returns the description of the proposal. -func (p *CommunityCDPRepayDebtProposal) GetDescription() string { return p.Description } - -// GetDescription returns the routing key of the proposal. -func (p *CommunityCDPRepayDebtProposal) ProposalRoute() string { return ModuleName } - -// ProposalType returns the type of the proposal. -func (p *CommunityCDPRepayDebtProposal) ProposalType() string { - return ProposalTypeCommunityCDPRepayDebt -} - -// String implements fmt.Stringer -func (p *CommunityCDPRepayDebtProposal) String() string { - var b strings.Builder - b.WriteString(fmt.Sprintf(`Community CDP Repay Debt Proposal: - Title: %s - Description: %s - Collateral Type: %s - Payment: %s -`, p.Title, p.Description, p.CollateralType, p.Payment)) - return b.String() -} - -// ValidateBasic stateless validation of the proposal. -func (p *CommunityCDPRepayDebtProposal) ValidateBasic() error { - if err := govv1beta1.ValidateAbstract(p); err != nil { - return err - } - // ensure collateral type is set - if strings.TrimSpace(p.CollateralType) == "" { - return errors.New("cdp collateral type cannot be blank") - } - // ensure the proposal has payment amount - if !p.Payment.IsValid() || p.Payment.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "payment amount %s", p.Payment) - } - return nil -} - -// NewCommunityCDPRepayDebtProposal creates a new community pool cdp debt repay proposal. -func NewCommunityCDPWithdrawCollateralProposal( - title string, - description string, - collateralType string, - collateral sdk.Coin, -) *CommunityCDPWithdrawCollateralProposal { - return &CommunityCDPWithdrawCollateralProposal{ - Title: title, - Description: description, - CollateralType: collateralType, - Collateral: collateral, - } -} - -// GetTitle returns the title of the proposal. -func (p *CommunityCDPWithdrawCollateralProposal) GetTitle() string { return p.Title } - -// GetDescription returns the description of the proposal. -func (p *CommunityCDPWithdrawCollateralProposal) GetDescription() string { return p.Description } - -// GetDescription returns the routing key of the proposal. -func (p *CommunityCDPWithdrawCollateralProposal) ProposalRoute() string { return ModuleName } - -// ProposalType returns the type of the proposal. -func (p *CommunityCDPWithdrawCollateralProposal) ProposalType() string { - return ProposalTypeCommunityCDPWithdrawCollateral -} - -// String implements fmt.Stringer -func (p *CommunityCDPWithdrawCollateralProposal) String() string { - var b strings.Builder - b.WriteString(fmt.Sprintf(`Community CDP Withdraw Collateral Proposal: - Title: %s - Description: %s - Collateral Type: %s - Collateral: %s -`, p.Title, p.Description, p.CollateralType, p.Collateral)) - return b.String() -} - -// ValidateBasic stateless validation of the proposal. -func (p *CommunityCDPWithdrawCollateralProposal) ValidateBasic() error { - if err := govv1beta1.ValidateAbstract(p); err != nil { - return err - } - - // ensure collateral type is set - if strings.TrimSpace(p.CollateralType) == "" { - return errors.New("cdp collateral type cannot be blank") - } - - // ensure the proposal has collateral amount - if !p.Collateral.IsValid() || p.Collateral.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "collateral amount %s", p.Collateral) - } - return nil -} diff --git a/x/community/types/proposal.pb.go b/x/community/types/proposal.pb.go deleted file mode 100644 index b1b289ad..00000000 --- a/x/community/types/proposal.pb.go +++ /dev/null @@ -1,1288 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/community/v1beta1/proposal.proto - -package types - -import ( - fmt "fmt" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// CommunityPoolLendDepositProposal deposits from the community pool into lend -type CommunityPoolLendDepositProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,3,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *CommunityPoolLendDepositProposal) Reset() { *m = CommunityPoolLendDepositProposal{} } -func (*CommunityPoolLendDepositProposal) ProtoMessage() {} -func (*CommunityPoolLendDepositProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_64aa83b2ed448ec1, []int{0} -} -func (m *CommunityPoolLendDepositProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityPoolLendDepositProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityPoolLendDepositProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CommunityPoolLendDepositProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityPoolLendDepositProposal.Merge(m, src) -} -func (m *CommunityPoolLendDepositProposal) XXX_Size() int { - return m.Size() -} -func (m *CommunityPoolLendDepositProposal) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityPoolLendDepositProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityPoolLendDepositProposal proto.InternalMessageInfo - -// CommunityPoolLendWithdrawProposal withdraws a lend position back to the community pool -type CommunityPoolLendWithdrawProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,3,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *CommunityPoolLendWithdrawProposal) Reset() { *m = CommunityPoolLendWithdrawProposal{} } -func (*CommunityPoolLendWithdrawProposal) ProtoMessage() {} -func (*CommunityPoolLendWithdrawProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_64aa83b2ed448ec1, []int{1} -} -func (m *CommunityPoolLendWithdrawProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityPoolLendWithdrawProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityPoolLendWithdrawProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CommunityPoolLendWithdrawProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityPoolLendWithdrawProposal.Merge(m, src) -} -func (m *CommunityPoolLendWithdrawProposal) XXX_Size() int { - return m.Size() -} -func (m *CommunityPoolLendWithdrawProposal) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityPoolLendWithdrawProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityPoolLendWithdrawProposal proto.InternalMessageInfo - -// CommunityCDPRepayDebtProposal repays a cdp debt position owned by the community module -// This proposal exists primarily to allow committees to repay community module cdp debts. -type CommunityCDPRepayDebtProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - CollateralType string `protobuf:"bytes,3,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Payment types.Coin `protobuf:"bytes,4,opt,name=payment,proto3" json:"payment"` -} - -func (m *CommunityCDPRepayDebtProposal) Reset() { *m = CommunityCDPRepayDebtProposal{} } -func (*CommunityCDPRepayDebtProposal) ProtoMessage() {} -func (*CommunityCDPRepayDebtProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_64aa83b2ed448ec1, []int{2} -} -func (m *CommunityCDPRepayDebtProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityCDPRepayDebtProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityCDPRepayDebtProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CommunityCDPRepayDebtProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityCDPRepayDebtProposal.Merge(m, src) -} -func (m *CommunityCDPRepayDebtProposal) XXX_Size() int { - return m.Size() -} -func (m *CommunityCDPRepayDebtProposal) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityCDPRepayDebtProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityCDPRepayDebtProposal proto.InternalMessageInfo - -// CommunityCDPWithdrawCollateralProposal withdraws cdp collateral owned by the community module -// This proposal exists primarily to allow committees to withdraw community module cdp collateral. -type CommunityCDPWithdrawCollateralProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - CollateralType string `protobuf:"bytes,3,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Collateral types.Coin `protobuf:"bytes,4,opt,name=collateral,proto3" json:"collateral"` -} - -func (m *CommunityCDPWithdrawCollateralProposal) Reset() { - *m = CommunityCDPWithdrawCollateralProposal{} -} -func (*CommunityCDPWithdrawCollateralProposal) ProtoMessage() {} -func (*CommunityCDPWithdrawCollateralProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_64aa83b2ed448ec1, []int{3} -} -func (m *CommunityCDPWithdrawCollateralProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityCDPWithdrawCollateralProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityCDPWithdrawCollateralProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CommunityCDPWithdrawCollateralProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityCDPWithdrawCollateralProposal.Merge(m, src) -} -func (m *CommunityCDPWithdrawCollateralProposal) XXX_Size() int { - return m.Size() -} -func (m *CommunityCDPWithdrawCollateralProposal) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityCDPWithdrawCollateralProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityCDPWithdrawCollateralProposal proto.InternalMessageInfo - -func init() { - proto.RegisterType((*CommunityPoolLendDepositProposal)(nil), "kava.community.v1beta1.CommunityPoolLendDepositProposal") - proto.RegisterType((*CommunityPoolLendWithdrawProposal)(nil), "kava.community.v1beta1.CommunityPoolLendWithdrawProposal") - proto.RegisterType((*CommunityCDPRepayDebtProposal)(nil), "kava.community.v1beta1.CommunityCDPRepayDebtProposal") - proto.RegisterType((*CommunityCDPWithdrawCollateralProposal)(nil), "kava.community.v1beta1.CommunityCDPWithdrawCollateralProposal") -} - -func init() { - proto.RegisterFile("kava/community/v1beta1/proposal.proto", fileDescriptor_64aa83b2ed448ec1) -} - -var fileDescriptor_64aa83b2ed448ec1 = []byte{ - // 426 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x93, 0x4f, 0x8b, 0xd3, 0x40, - 0x18, 0xc6, 0x33, 0x76, 0x5d, 0x75, 0x16, 0x14, 0xc2, 0x22, 0x71, 0xc1, 0x24, 0x2e, 0xa8, 0x3d, - 0xb8, 0x99, 0xae, 0x9e, 0xf4, 0x22, 0x34, 0xc5, 0x93, 0x87, 0x12, 0x04, 0xc1, 0x8b, 0x4c, 0x92, - 0x21, 0x1d, 0x9a, 0xcc, 0x3b, 0x64, 0xa6, 0xd5, 0x7c, 0x03, 0x8f, 0x1e, 0x3d, 0xf6, 0xec, 0xf7, - 0x10, 0xaa, 0xa7, 0x1e, 0x3c, 0x78, 0x52, 0x69, 0xbf, 0x88, 0xe4, 0x6f, 0x03, 0x82, 0x08, 0x82, - 0xb0, 0xa7, 0x4c, 0xde, 0x79, 0x9e, 0x99, 0xe7, 0xc7, 0xc3, 0xe0, 0xbb, 0x73, 0xba, 0xa4, 0x24, - 0x82, 0x2c, 0x5b, 0x08, 0xae, 0x0b, 0xb2, 0x3c, 0x0f, 0x99, 0xa6, 0xe7, 0x44, 0xe6, 0x20, 0x41, - 0xd1, 0xd4, 0x93, 0x39, 0x68, 0x30, 0x6f, 0x96, 0x32, 0xaf, 0x93, 0x79, 0x8d, 0xec, 0xc4, 0x8e, - 0x40, 0x65, 0xa0, 0x48, 0x48, 0x15, 0xeb, 0xbc, 0x11, 0x70, 0x51, 0xfb, 0x4e, 0x8e, 0x13, 0x48, - 0xa0, 0x5a, 0x92, 0x72, 0x55, 0x4f, 0x4f, 0x3f, 0x23, 0xec, 0xfa, 0xed, 0x59, 0x53, 0x80, 0xf4, - 0x39, 0x13, 0xf1, 0x84, 0x49, 0x50, 0x5c, 0x4f, 0x9b, 0x8b, 0xcd, 0x63, 0x7c, 0x59, 0x73, 0x9d, - 0x32, 0x0b, 0xb9, 0x68, 0x78, 0x2d, 0xa8, 0x7f, 0x4c, 0x17, 0x1f, 0xc5, 0x4c, 0x45, 0x39, 0x97, - 0x9a, 0x83, 0xb0, 0x2e, 0x55, 0x7b, 0xfd, 0x91, 0x19, 0xe1, 0x43, 0x9a, 0xc1, 0x42, 0x68, 0x6b, - 0xe0, 0x0e, 0x86, 0x47, 0x0f, 0x6f, 0x79, 0x75, 0x46, 0xaf, 0xcc, 0xd8, 0x06, 0xf7, 0x7c, 0xe0, - 0x62, 0x3c, 0x5a, 0x7f, 0x77, 0x8c, 0x8f, 0x3f, 0x9c, 0x61, 0xc2, 0xf5, 0x6c, 0x11, 0x96, 0x7c, - 0xa4, 0x01, 0xaa, 0x3f, 0x67, 0x2a, 0x9e, 0x13, 0x5d, 0x48, 0xa6, 0x2a, 0x83, 0x0a, 0x9a, 0xa3, - 0x9f, 0x5c, 0x7d, 0xb7, 0x72, 0x8c, 0x0f, 0x2b, 0xc7, 0x38, 0xfd, 0x82, 0xf0, 0x9d, 0xdf, 0x58, - 0x5e, 0x72, 0x3d, 0x8b, 0x73, 0xfa, 0xe6, 0xa2, 0xc1, 0x7c, 0x42, 0xf8, 0x76, 0x07, 0xe3, 0x4f, - 0xa6, 0x01, 0x93, 0xb4, 0x98, 0xb0, 0xf0, 0xdf, 0x5b, 0xb9, 0x8f, 0x6f, 0x44, 0x90, 0xa6, 0x54, - 0xb3, 0x9c, 0xa6, 0xaf, 0xcb, 0x14, 0xd6, 0xa0, 0x52, 0x5d, 0xdf, 0x8f, 0x5f, 0x14, 0x92, 0x99, - 0x8f, 0xf1, 0x15, 0x49, 0x8b, 0x8c, 0x09, 0x6d, 0x1d, 0xb8, 0xe8, 0xcf, 0xc8, 0x07, 0x25, 0x72, - 0xd0, 0xea, 0x7b, 0x1c, 0x5f, 0x11, 0xbe, 0xd7, 0xe7, 0x68, 0xfb, 0xf0, 0xbb, 0xbb, 0xfe, 0x1f, - 0xd0, 0x53, 0x8c, 0xf7, 0x93, 0xbf, 0x65, 0xea, 0x59, 0xf6, 0x58, 0xe3, 0x67, 0xeb, 0xad, 0x8d, - 0x36, 0x5b, 0x1b, 0xfd, 0xdc, 0xda, 0xe8, 0xfd, 0xce, 0x36, 0x36, 0x3b, 0xdb, 0xf8, 0xb6, 0xb3, - 0x8d, 0x57, 0x0f, 0x7a, 0xa5, 0x8f, 0x92, 0x94, 0x86, 0x8a, 0x8c, 0x92, 0xb3, 0x68, 0x46, 0xb9, - 0x20, 0x6f, 0x7b, 0xcf, 0xbb, 0xaa, 0x3f, 0x3c, 0xac, 0x9e, 0xe1, 0xa3, 0x5f, 0x01, 0x00, 0x00, - 0xff, 0xff, 0x1a, 0xff, 0x79, 0xa8, 0xfd, 0x03, 0x00, 0x00, -} - -func (m *CommunityPoolLendDepositProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CommunityPoolLendDepositProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityPoolLendDepositProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CommunityPoolLendWithdrawProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CommunityPoolLendWithdrawProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityPoolLendWithdrawProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CommunityCDPRepayDebtProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CommunityCDPRepayDebtProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityCDPRepayDebtProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Payment.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintProposal(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CommunityCDPWithdrawCollateralProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CommunityCDPWithdrawCollateralProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityCDPWithdrawCollateralProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Collateral.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintProposal(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintProposal(dAtA []byte, offset int, v uint64) int { - offset -= sovProposal(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *CommunityPoolLendDepositProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func (m *CommunityPoolLendWithdrawProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func (m *CommunityCDPRepayDebtProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = m.Payment.Size() - n += 1 + l + sovProposal(uint64(l)) - return n -} - -func (m *CommunityCDPWithdrawCollateralProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = m.Collateral.Size() - n += 1 + l + sovProposal(uint64(l)) - return n -} - -func sovProposal(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozProposal(x uint64) (n int) { - return sovProposal(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *CommunityPoolLendDepositProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CommunityPoolLendDepositProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityPoolLendDepositProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommunityPoolLendWithdrawProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CommunityPoolLendWithdrawProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityPoolLendWithdrawProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommunityCDPRepayDebtProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CommunityCDPRepayDebtProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityCDPRepayDebtProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Payment", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Payment.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommunityCDPWithdrawCollateralProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CommunityCDPWithdrawCollateralProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityCDPWithdrawCollateralProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Collateral", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Collateral.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipProposal(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProposal - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProposal - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProposal - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthProposal - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupProposal - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthProposal - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthProposal = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowProposal = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupProposal = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/community/types/proposal_test.go b/x/community/types/proposal_test.go deleted file mode 100644 index ed9dc9ce..00000000 --- a/x/community/types/proposal_test.go +++ /dev/null @@ -1,330 +0,0 @@ -package types_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/0glabs/0g-chain/x/community/types" -) - -func TestLendProposals_ValidateBasic(t *testing.T) { - // each proposalData is tested with Deposit and Withdraw proposals - type proposalData struct { - Title string - Description string - Amount sdk.Coins - } - testCases := []struct { - name string - proposal proposalData - expectedErr string - }{ - { - name: "valid proposal", - proposal: proposalData{ - Title: "I'm a lend proposal", - Description: "I interact with lend", - Amount: sdk.NewCoins(sdk.NewInt64Coin("ukava", 1e10)), - }, - expectedErr: "", - }, - { - name: "invalid - fails gov validation", - proposal: proposalData{ - Description: "I have no title.", - }, - expectedErr: "invalid proposal content", - }, - { - name: "invalid - nil coins", - proposal: proposalData{ - Title: "Error profoundly", - Description: "My coins are nil", - Amount: nil, - }, - expectedErr: "invalid coins", - }, - { - name: "invalid - empty coins", - proposal: proposalData{ - Title: "Error profoundly", - Description: "My coins are empty", - Amount: sdk.NewCoins(), - }, - expectedErr: "invalid coins", - }, - { - name: "invalid - zero coins", - proposal: proposalData{ - Title: "Error profoundly", - Description: "My coins are zero", - Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdk.ZeroInt())), - }, - expectedErr: "invalid coins", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - t.Run("CommunityPoolLendDepositProposal", func(t *testing.T) { - deposit := types.NewCommunityPoolLendDepositProposal( - tc.proposal.Title, - tc.proposal.Description, - tc.proposal.Amount, - ) - err := deposit.ValidateBasic() - if tc.expectedErr != "" { - require.ErrorContains(t, err, tc.expectedErr) - return - } - - require.NoError(t, err) - require.Equal(t, deposit.Title, deposit.GetTitle()) - require.Equal(t, deposit.Description, deposit.GetDescription()) - require.Equal(t, types.ModuleName, deposit.ProposalRoute()) - require.Equal(t, types.ProposalTypeCommunityPoolLendDeposit, deposit.ProposalType()) - }) - - t.Run("CommunityPoolLendWithdrawProposal", func(t *testing.T) { - withdrawl := types.NewCommunityPoolLendWithdrawProposal( - tc.proposal.Title, - tc.proposal.Description, - tc.proposal.Amount, - ) - err := withdrawl.ValidateBasic() - if tc.expectedErr != "" { - require.ErrorContains(t, err, tc.expectedErr) - return - } - - require.NoError(t, err) - require.Equal(t, withdrawl.Title, withdrawl.GetTitle()) - require.Equal(t, withdrawl.Description, withdrawl.GetDescription()) - require.Equal(t, types.ModuleName, withdrawl.ProposalRoute()) - require.Equal(t, types.ProposalTypeCommunityPoolLendWithdraw, withdrawl.ProposalType()) - }) - }) - } -} - -func TestCommunityPoolLendDepositProposal_Stringer(t *testing.T) { - proposal := types.NewCommunityPoolLendDepositProposal( - "Title", - "Description", - sdk.NewCoins(sdk.NewInt64Coin("ukava", 42)), - ) - require.Equal(t, `Community Pool Lend Deposit Proposal: - Title: Title - Description: Description - Amount: 42ukava -`, proposal.String()) -} - -func TestCommunityPoolLendWithdrawProposal_Stringer(t *testing.T) { - proposal := types.NewCommunityPoolLendWithdrawProposal( - "Title", - "Description", - sdk.NewCoins(sdk.NewInt64Coin("ukava", 42)), - ) - require.Equal(t, `Community Pool Lend Withdraw Proposal: - Title: Title - Description: Description - Amount: 42ukava -`, proposal.String()) -} - -func TestCommunityCDPRepayDebtProposal_ValidateBasic(t *testing.T) { - type proposalData struct { - Title string - Description string - CollateralType string - Payment sdk.Coin - } - testCases := []struct { - name string - proposal proposalData - expectedErr string - }{ - { - name: "valid proposal", - proposal: proposalData{ - Title: "Repay my debt plz", - Description: "I interact with cdp", - CollateralType: "type-a", - Payment: sdk.NewInt64Coin("ukava", 1e6), - }, - expectedErr: "", - }, - { - name: "invalid - fails gov validation", - proposal: proposalData{ - Description: "I have no title.", - }, - expectedErr: "invalid proposal content", - }, - { - name: "invalid - empty collateral type", - proposal: proposalData{ - Title: "Error profoundly", - Description: "I have no collateral type", - }, - expectedErr: "collateral type cannot be blank", - }, - { - name: "invalid - empty coins", - proposal: proposalData{ - Title: "Error profoundly", - Description: "My coins are empty", - CollateralType: "type-a", - Payment: sdk.Coin{}, - }, - expectedErr: "invalid coins", - }, - { - name: "invalid - zero coins", - proposal: proposalData{ - Title: "Error profoundly", - Description: "My coins are zero", - CollateralType: "type-a", - Payment: sdk.NewInt64Coin("ukava", 0), - }, - expectedErr: "invalid coins", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - repayDebt := types.NewCommunityCDPRepayDebtProposal( - tc.proposal.Title, - tc.proposal.Description, - tc.proposal.CollateralType, - tc.proposal.Payment, - ) - err := repayDebt.ValidateBasic() - if tc.expectedErr != "" { - require.ErrorContains(t, err, tc.expectedErr) - return - } - - require.NoError(t, err) - require.Equal(t, repayDebt.Title, repayDebt.GetTitle()) - require.Equal(t, repayDebt.Description, repayDebt.GetDescription()) - require.Equal(t, types.ModuleName, repayDebt.ProposalRoute()) - require.Equal(t, types.ProposalTypeCommunityCDPRepayDebt, repayDebt.ProposalType()) - }) - } -} - -func TestCommunityCDPRepayDebtProposal_Stringer(t *testing.T) { - proposal := types.NewCommunityCDPRepayDebtProposal( - "title", - "description", - "collateral-type", - sdk.NewInt64Coin("ukava", 42), - ) - require.Equal(t, `Community CDP Repay Debt Proposal: - Title: title - Description: description - Collateral Type: collateral-type - Payment: 42ukava -`, proposal.String()) -} - -func TestCommunityCDPWithdrawCollateralProposal_ValidateBasic(t *testing.T) { - type proposalData struct { - Title string - Description string - CollateralType string - Collateral sdk.Coin - } - testCases := []struct { - name string - proposal proposalData - expectedErr string - }{ - { - name: "valid proposal", - proposal: proposalData{ - Title: "withdraw my collateral plz", - Description: "I interact with cdp", - CollateralType: "type-a", - Collateral: sdk.NewInt64Coin("ukava", 1e6), - }, - expectedErr: "", - }, - { - name: "invalid - fails gov validation", - proposal: proposalData{ - Description: "I have no title.", - }, - expectedErr: "invalid proposal content", - }, - { - name: "invalid - empty collateral type", - proposal: proposalData{ - Title: "Error profoundly", - Description: "I have no collateral type", - }, - expectedErr: "collateral type cannot be blank", - }, - { - name: "invalid - empty coins", - proposal: proposalData{ - Title: "Error profoundly", - Description: "My coins are empty", - CollateralType: "type-a", - Collateral: sdk.Coin{}, - }, - expectedErr: "invalid coins", - }, - { - name: "invalid - zero coins", - proposal: proposalData{ - Title: "Error profoundly", - Description: "My coins are zero", - CollateralType: "type-a", - Collateral: sdk.NewInt64Coin("ukava", 0), - }, - expectedErr: "invalid coins", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - repayDebt := types.NewCommunityCDPWithdrawCollateralProposal( - tc.proposal.Title, - tc.proposal.Description, - tc.proposal.CollateralType, - tc.proposal.Collateral, - ) - err := repayDebt.ValidateBasic() - if tc.expectedErr != "" { - require.ErrorContains(t, err, tc.expectedErr) - return - } - - require.NoError(t, err) - require.Equal(t, repayDebt.Title, repayDebt.GetTitle()) - require.Equal(t, repayDebt.Description, repayDebt.GetDescription()) - require.Equal(t, types.ModuleName, repayDebt.ProposalRoute()) - require.Equal(t, types.ProposalTypeCommunityCDPWithdrawCollateral, repayDebt.ProposalType()) - }) - } -} - -func TestCommunityCDPWithdrawCollateralProposal_Stringer(t *testing.T) { - proposal := types.NewCommunityCDPWithdrawCollateralProposal( - "title", - "description", - "collateral-type", - sdk.NewInt64Coin("ukava", 42), - ) - require.Equal(t, `Community CDP Withdraw Collateral Proposal: - Title: title - Description: description - Collateral Type: collateral-type - Collateral: 42ukava -`, proposal.String()) -} diff --git a/x/community/types/query.pb.go b/x/community/types/query.pb.go deleted file mode 100644 index 8c798579..00000000 --- a/x/community/types/query.pb.go +++ /dev/null @@ -1,1574 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/community/v1beta1/query.proto - -package types - -import ( - context "context" - cosmossdk_io_math "cosmossdk.io/math" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// QueryParams defines the request type for querying x/community params. -type QueryParamsRequest struct { -} - -func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } -func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryParamsRequest) ProtoMessage() {} -func (*QueryParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_f236f06c43149273, []int{0} -} -func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsRequest.Merge(m, src) -} -func (m *QueryParamsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo - -// QueryParamsResponse defines the response type for querying x/community params. -type QueryParamsResponse struct { - // params represents the community module parameters - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` -} - -func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } -func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryParamsResponse) ProtoMessage() {} -func (*QueryParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_f236f06c43149273, []int{1} -} -func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsResponse.Merge(m, src) -} -func (m *QueryParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo - -func (m *QueryParamsResponse) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -// QueryBalanceRequest defines the request type for querying x/community balance. -type QueryBalanceRequest struct { -} - -func (m *QueryBalanceRequest) Reset() { *m = QueryBalanceRequest{} } -func (m *QueryBalanceRequest) String() string { return proto.CompactTextString(m) } -func (*QueryBalanceRequest) ProtoMessage() {} -func (*QueryBalanceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_f236f06c43149273, []int{2} -} -func (m *QueryBalanceRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryBalanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryBalanceRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryBalanceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryBalanceRequest.Merge(m, src) -} -func (m *QueryBalanceRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryBalanceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryBalanceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryBalanceRequest proto.InternalMessageInfo - -// QueryBalanceResponse defines the response type for querying x/community balance. -type QueryBalanceResponse struct { - Coins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=coins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"coins"` -} - -func (m *QueryBalanceResponse) Reset() { *m = QueryBalanceResponse{} } -func (m *QueryBalanceResponse) String() string { return proto.CompactTextString(m) } -func (*QueryBalanceResponse) ProtoMessage() {} -func (*QueryBalanceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_f236f06c43149273, []int{3} -} -func (m *QueryBalanceResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryBalanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryBalanceResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryBalanceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryBalanceResponse.Merge(m, src) -} -func (m *QueryBalanceResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryBalanceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryBalanceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryBalanceResponse proto.InternalMessageInfo - -func (m *QueryBalanceResponse) GetCoins() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Coins - } - return nil -} - -// QueryTotalBalanceRequest defines the request type for querying total community pool balance. -type QueryTotalBalanceRequest struct { -} - -func (m *QueryTotalBalanceRequest) Reset() { *m = QueryTotalBalanceRequest{} } -func (m *QueryTotalBalanceRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalBalanceRequest) ProtoMessage() {} -func (*QueryTotalBalanceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_f236f06c43149273, []int{4} -} -func (m *QueryTotalBalanceRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalBalanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalBalanceRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTotalBalanceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalBalanceRequest.Merge(m, src) -} -func (m *QueryTotalBalanceRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalBalanceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalBalanceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalBalanceRequest proto.InternalMessageInfo - -// QueryTotalBalanceResponse defines the response type for querying total -// community pool balance. This matches the x/distribution CommunityPool query response. -type QueryTotalBalanceResponse struct { - // pool defines community pool's coins. - Pool github_com_cosmos_cosmos_sdk_types.DecCoins `protobuf:"bytes,1,rep,name=pool,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.DecCoins" json:"pool"` -} - -func (m *QueryTotalBalanceResponse) Reset() { *m = QueryTotalBalanceResponse{} } -func (m *QueryTotalBalanceResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalBalanceResponse) ProtoMessage() {} -func (*QueryTotalBalanceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_f236f06c43149273, []int{5} -} -func (m *QueryTotalBalanceResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalBalanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalBalanceResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTotalBalanceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalBalanceResponse.Merge(m, src) -} -func (m *QueryTotalBalanceResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalBalanceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalBalanceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalBalanceResponse proto.InternalMessageInfo - -func (m *QueryTotalBalanceResponse) GetPool() github_com_cosmos_cosmos_sdk_types.DecCoins { - if m != nil { - return m.Pool - } - return nil -} - -// QueryAnnualizedRewardsRequest defines the request type for querying the annualized rewards. -type QueryAnnualizedRewardsRequest struct { -} - -func (m *QueryAnnualizedRewardsRequest) Reset() { *m = QueryAnnualizedRewardsRequest{} } -func (m *QueryAnnualizedRewardsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAnnualizedRewardsRequest) ProtoMessage() {} -func (*QueryAnnualizedRewardsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_f236f06c43149273, []int{6} -} -func (m *QueryAnnualizedRewardsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAnnualizedRewardsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAnnualizedRewardsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryAnnualizedRewardsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAnnualizedRewardsRequest.Merge(m, src) -} -func (m *QueryAnnualizedRewardsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryAnnualizedRewardsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAnnualizedRewardsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAnnualizedRewardsRequest proto.InternalMessageInfo - -// QueryAnnualizedRewardsResponse defines the response type for querying the annualized rewards. -type QueryAnnualizedRewardsResponse struct { - // staking_rewards is the calculated annualized staking rewards percentage rate - StakingRewards cosmossdk_io_math.LegacyDec `protobuf:"bytes,1,opt,name=staking_rewards,json=stakingRewards,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"staking_rewards"` -} - -func (m *QueryAnnualizedRewardsResponse) Reset() { *m = QueryAnnualizedRewardsResponse{} } -func (m *QueryAnnualizedRewardsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAnnualizedRewardsResponse) ProtoMessage() {} -func (*QueryAnnualizedRewardsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_f236f06c43149273, []int{7} -} -func (m *QueryAnnualizedRewardsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAnnualizedRewardsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAnnualizedRewardsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryAnnualizedRewardsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAnnualizedRewardsResponse.Merge(m, src) -} -func (m *QueryAnnualizedRewardsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryAnnualizedRewardsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAnnualizedRewardsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAnnualizedRewardsResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.community.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.community.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryBalanceRequest)(nil), "kava.community.v1beta1.QueryBalanceRequest") - proto.RegisterType((*QueryBalanceResponse)(nil), "kava.community.v1beta1.QueryBalanceResponse") - proto.RegisterType((*QueryTotalBalanceRequest)(nil), "kava.community.v1beta1.QueryTotalBalanceRequest") - proto.RegisterType((*QueryTotalBalanceResponse)(nil), "kava.community.v1beta1.QueryTotalBalanceResponse") - proto.RegisterType((*QueryAnnualizedRewardsRequest)(nil), "kava.community.v1beta1.QueryAnnualizedRewardsRequest") - proto.RegisterType((*QueryAnnualizedRewardsResponse)(nil), "kava.community.v1beta1.QueryAnnualizedRewardsResponse") -} - -func init() { - proto.RegisterFile("kava/community/v1beta1/query.proto", fileDescriptor_f236f06c43149273) -} - -var fileDescriptor_f236f06c43149273 = []byte{ - // 612 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0x31, 0x6f, 0xd3, 0x40, - 0x14, 0xc7, 0x63, 0x68, 0x8b, 0xb8, 0x22, 0x10, 0x47, 0x41, 0xad, 0x29, 0x4e, 0x31, 0x82, 0x56, - 0x6d, 0xe2, 0x4b, 0x52, 0xc1, 0xc4, 0x42, 0x88, 0x98, 0x18, 0xc0, 0x30, 0x75, 0x89, 0xce, 0xce, - 0xc9, 0xb1, 0xe2, 0xdc, 0xb9, 0xb9, 0x4b, 0x21, 0x88, 0x85, 0x6e, 0x0c, 0x48, 0x48, 0x7c, 0x03, - 0x46, 0x66, 0xc4, 0x67, 0xe8, 0x58, 0xc1, 0x82, 0x18, 0x0a, 0x4a, 0xf8, 0x20, 0xc8, 0xe7, 0x97, - 0x28, 0xa1, 0x71, 0x94, 0x4e, 0x89, 0xdf, 0xbd, 0xff, 0xfb, 0xff, 0xee, 0xbd, 0x67, 0x23, 0xbb, - 0x45, 0x0f, 0x28, 0xf1, 0x45, 0xbb, 0xdd, 0xe5, 0xa1, 0xea, 0x91, 0x83, 0xb2, 0xc7, 0x14, 0x2d, - 0x93, 0xfd, 0x2e, 0xeb, 0xf4, 0x9c, 0xb8, 0x23, 0x94, 0xc0, 0x37, 0x92, 0x1c, 0x67, 0x94, 0xe3, - 0x40, 0x8e, 0x69, 0xf9, 0x42, 0xb6, 0x85, 0x24, 0x1e, 0x95, 0x6c, 0x24, 0xf4, 0x45, 0xc8, 0x53, - 0x9d, 0xb9, 0x96, 0x9e, 0xd7, 0xf5, 0x13, 0x49, 0x1f, 0xe0, 0x68, 0x25, 0x10, 0x81, 0x48, 0xe3, - 0xc9, 0x3f, 0x88, 0xae, 0x07, 0x42, 0x04, 0x11, 0x23, 0x34, 0x0e, 0x09, 0xe5, 0x5c, 0x28, 0xaa, - 0x42, 0xc1, 0x87, 0x9a, 0x3b, 0x19, 0xa8, 0x31, 0xed, 0xd0, 0x36, 0x24, 0xd9, 0x2b, 0x08, 0x3f, - 0x4f, 0xd0, 0x9f, 0xe9, 0xa0, 0xcb, 0xf6, 0xbb, 0x4c, 0x2a, 0xfb, 0x05, 0xba, 0x36, 0x11, 0x95, - 0xb1, 0xe0, 0x92, 0xe1, 0x87, 0x68, 0x29, 0x15, 0xaf, 0x1a, 0x1b, 0xc6, 0xd6, 0x72, 0xc5, 0x72, - 0xa6, 0xdf, 0xd4, 0x49, 0x75, 0xd5, 0x85, 0xa3, 0x93, 0x7c, 0xce, 0x05, 0x8d, 0x7d, 0x1d, 0x8a, - 0x56, 0x69, 0x44, 0xb9, 0xcf, 0x86, 0x5e, 0x3d, 0xb4, 0x32, 0x19, 0x06, 0x33, 0x8a, 0x16, 0x93, - 0xde, 0x24, 0x5e, 0xe7, 0xb7, 0x96, 0x2b, 0x6b, 0x0e, 0x34, 0x24, 0xe9, 0xde, 0xc8, 0xe8, 0xb1, - 0x08, 0x79, 0xb5, 0x94, 0xd8, 0x7c, 0xf9, 0x9d, 0xdf, 0x0a, 0x42, 0xd5, 0xec, 0x7a, 0x09, 0x0f, - 0x74, 0x0f, 0x7e, 0x8a, 0xb2, 0xd1, 0x22, 0xaa, 0x17, 0x33, 0xa9, 0x05, 0xd2, 0x4d, 0x2b, 0xdb, - 0x26, 0x5a, 0xd5, 0xd6, 0x2f, 0x85, 0xa2, 0xd1, 0x7f, 0x58, 0x87, 0x06, 0x5a, 0x9b, 0x72, 0x08, - 0x70, 0x0c, 0x2d, 0xc4, 0x42, 0x44, 0xc0, 0xb6, 0x3e, 0x95, 0xad, 0xc6, 0x7c, 0x8d, 0xb7, 0x0b, - 0x78, 0x3b, 0x73, 0xe0, 0x81, 0x46, 0xba, 0xba, 0xbc, 0x9d, 0x47, 0xb7, 0x34, 0xc3, 0x23, 0xce, - 0xbb, 0x34, 0x0a, 0xdf, 0xb0, 0x86, 0xcb, 0x5e, 0xd1, 0x4e, 0x63, 0x34, 0xa8, 0xb7, 0xc8, 0xca, - 0x4a, 0x00, 0xd2, 0x3d, 0x74, 0x45, 0x2a, 0xda, 0x0a, 0x79, 0x50, 0xef, 0xa4, 0x47, 0x7a, 0x78, - 0x17, 0xab, 0xe5, 0x04, 0xeb, 0xd7, 0x49, 0xfe, 0x66, 0x0a, 0x21, 0x1b, 0x2d, 0x27, 0x14, 0xa4, - 0x4d, 0x55, 0xd3, 0x79, 0xca, 0x02, 0xea, 0xf7, 0x6a, 0xcc, 0xff, 0xfe, 0xb5, 0x88, 0xe0, 0x6a, - 0x35, 0xe6, 0xbb, 0x97, 0xa1, 0x12, 0x78, 0x54, 0xde, 0x2d, 0xa2, 0x45, 0x6d, 0x8f, 0xdf, 0x1b, - 0x68, 0x29, 0x1d, 0x3a, 0xde, 0xce, 0x5a, 0x8a, 0xd3, 0x7b, 0x66, 0xee, 0xcc, 0x95, 0x9b, 0xde, - 0xc4, 0xbe, 0x77, 0xf8, 0xe3, 0xef, 0xa7, 0x73, 0x1b, 0xd8, 0x22, 0x33, 0x17, 0x1b, 0x7f, 0x30, - 0xd0, 0x05, 0x98, 0x17, 0x9e, 0x6d, 0x30, 0x39, 0x72, 0xb3, 0x30, 0x5f, 0x32, 0xe0, 0x6c, 0x6a, - 0x9c, 0xdb, 0x38, 0x9f, 0x85, 0xe3, 0x01, 0xc3, 0x67, 0x03, 0x5d, 0x1a, 0x5f, 0x22, 0x5c, 0x9a, - 0xe9, 0x33, 0x65, 0x19, 0xcd, 0xf2, 0x19, 0x14, 0x80, 0x57, 0xd4, 0x78, 0x9b, 0xf8, 0x6e, 0x16, - 0x9e, 0x4a, 0x54, 0xf5, 0x21, 0xe4, 0x37, 0x03, 0x5d, 0x3d, 0xb5, 0x44, 0xf8, 0xfe, 0x4c, 0xdf, - 0xac, 0xad, 0x34, 0x1f, 0x9c, 0x55, 0x06, 0xcc, 0x15, 0xcd, 0x5c, 0xc0, 0xdb, 0x59, 0xcc, 0x74, - 0x24, 0x1d, 0x2e, 0x73, 0xf5, 0xc9, 0x51, 0xdf, 0x32, 0x8e, 0xfb, 0x96, 0xf1, 0xa7, 0x6f, 0x19, - 0x1f, 0x07, 0x56, 0xee, 0x78, 0x60, 0xe5, 0x7e, 0x0e, 0xac, 0xdc, 0x5e, 0x61, 0xec, 0x7d, 0x2b, - 0x05, 0x11, 0xf5, 0x24, 0x29, 0x05, 0x45, 0xbf, 0x49, 0x43, 0x4e, 0x5e, 0x8f, 0x15, 0xd7, 0x6f, - 0x9e, 0xb7, 0xa4, 0xbf, 0x87, 0xbb, 0xff, 0x02, 0x00, 0x00, 0xff, 0xff, 0xd7, 0xa6, 0xa4, 0x44, - 0xe1, 0x05, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - // Params queires the module params. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Balance queries the balance of all coins of x/community module. - Balance(ctx context.Context, in *QueryBalanceRequest, opts ...grpc.CallOption) (*QueryBalanceResponse, error) - // TotalBalance queries the balance of all coins, including x/distribution, - // x/community, and supplied balances. - TotalBalance(ctx context.Context, in *QueryTotalBalanceRequest, opts ...grpc.CallOption) (*QueryTotalBalanceResponse, error) - // AnnualizedRewards calculates and returns the current annualized reward percentages, - // like staking rewards, for the chain. - AnnualizedRewards(ctx context.Context, in *QueryAnnualizedRewardsRequest, opts ...grpc.CallOption) (*QueryAnnualizedRewardsResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { - out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, "/kava.community.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Balance(ctx context.Context, in *QueryBalanceRequest, opts ...grpc.CallOption) (*QueryBalanceResponse, error) { - out := new(QueryBalanceResponse) - err := c.cc.Invoke(ctx, "/kava.community.v1beta1.Query/Balance", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalBalance(ctx context.Context, in *QueryTotalBalanceRequest, opts ...grpc.CallOption) (*QueryTotalBalanceResponse, error) { - out := new(QueryTotalBalanceResponse) - err := c.cc.Invoke(ctx, "/kava.community.v1beta1.Query/TotalBalance", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) AnnualizedRewards(ctx context.Context, in *QueryAnnualizedRewardsRequest, opts ...grpc.CallOption) (*QueryAnnualizedRewardsResponse, error) { - out := new(QueryAnnualizedRewardsResponse) - err := c.cc.Invoke(ctx, "/kava.community.v1beta1.Query/AnnualizedRewards", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queires the module params. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Balance queries the balance of all coins of x/community module. - Balance(context.Context, *QueryBalanceRequest) (*QueryBalanceResponse, error) - // TotalBalance queries the balance of all coins, including x/distribution, - // x/community, and supplied balances. - TotalBalance(context.Context, *QueryTotalBalanceRequest) (*QueryTotalBalanceResponse, error) - // AnnualizedRewards calculates and returns the current annualized reward percentages, - // like staking rewards, for the chain. - AnnualizedRewards(context.Context, *QueryAnnualizedRewardsRequest) (*QueryAnnualizedRewardsResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") -} -func (*UnimplementedQueryServer) Balance(ctx context.Context, req *QueryBalanceRequest) (*QueryBalanceResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Balance not implemented") -} -func (*UnimplementedQueryServer) TotalBalance(ctx context.Context, req *QueryTotalBalanceRequest) (*QueryTotalBalanceResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalBalance not implemented") -} -func (*UnimplementedQueryServer) AnnualizedRewards(ctx context.Context, req *QueryAnnualizedRewardsRequest) (*QueryAnnualizedRewardsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method AnnualizedRewards not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryParamsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Params(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.community.v1beta1.Query/Params", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Balance_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryBalanceRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Balance(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.community.v1beta1.Query/Balance", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Balance(ctx, req.(*QueryBalanceRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalBalance_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalBalanceRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalBalance(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.community.v1beta1.Query/TotalBalance", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalBalance(ctx, req.(*QueryTotalBalanceRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_AnnualizedRewards_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAnnualizedRewardsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).AnnualizedRewards(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.community.v1beta1.Query/AnnualizedRewards", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).AnnualizedRewards(ctx, req.(*QueryAnnualizedRewardsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.community.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Balance", - Handler: _Query_Balance_Handler, - }, - { - MethodName: "TotalBalance", - Handler: _Query_TotalBalance_Handler, - }, - { - MethodName: "AnnualizedRewards", - Handler: _Query_AnnualizedRewards_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/community/v1beta1/query.proto", -} - -func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryBalanceRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryBalanceRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryBalanceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryBalanceResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryBalanceResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryBalanceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Coins) > 0 { - for iNdEx := len(m.Coins) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Coins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalBalanceRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryTotalBalanceRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalBalanceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryTotalBalanceResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryTotalBalanceResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalBalanceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Pool) > 0 { - for iNdEx := len(m.Pool) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Pool[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryAnnualizedRewardsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryAnnualizedRewardsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAnnualizedRewardsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryAnnualizedRewardsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryAnnualizedRewardsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAnnualizedRewardsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.StakingRewards.Size() - i -= size - if _, err := m.StakingRewards.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryParamsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryBalanceRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryBalanceResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Coins) > 0 { - for _, e := range m.Coins { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryTotalBalanceRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryTotalBalanceResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Pool) > 0 { - for _, e := range m.Pool { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryAnnualizedRewardsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryAnnualizedRewardsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.StakingRewards.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryBalanceRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryBalanceRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryBalanceRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryBalanceResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryBalanceResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryBalanceResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Coins", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Coins = append(m.Coins, types.Coin{}) - if err := m.Coins[len(m.Coins)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTotalBalanceRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTotalBalanceRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalBalanceRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTotalBalanceResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTotalBalanceResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalBalanceResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pool", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Pool = append(m.Pool, types.DecCoin{}) - if err := m.Pool[len(m.Pool)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryAnnualizedRewardsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryAnnualizedRewardsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAnnualizedRewardsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryAnnualizedRewardsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryAnnualizedRewardsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAnnualizedRewardsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field StakingRewards", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.StakingRewards.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/community/types/query.pb.gw.go b/x/community/types/query.pb.gw.go deleted file mode 100644 index 289b1988..00000000 --- a/x/community/types/query.pb.gw.go +++ /dev/null @@ -1,348 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/community/v1beta1/query.proto - -/* -Package types is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package types - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join - -func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Params(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Balance_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryBalanceRequest - var metadata runtime.ServerMetadata - - msg, err := client.Balance(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Balance_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryBalanceRequest - var metadata runtime.ServerMetadata - - msg, err := server.Balance(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_TotalBalance_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalBalanceRequest - var metadata runtime.ServerMetadata - - msg, err := client.TotalBalance(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TotalBalance_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalBalanceRequest - var metadata runtime.ServerMetadata - - msg, err := server.TotalBalance(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_AnnualizedRewards_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAnnualizedRewardsRequest - var metadata runtime.ServerMetadata - - msg, err := client.AnnualizedRewards(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_AnnualizedRewards_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAnnualizedRewardsRequest - var metadata runtime.ServerMetadata - - msg, err := server.AnnualizedRewards(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Balance_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Balance_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Balance_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalBalance_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_TotalBalance_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TotalBalance_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_AnnualizedRewards_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_AnnualizedRewards_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_AnnualizedRewards_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Balance_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Balance_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Balance_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalBalance_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_TotalBalance_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TotalBalance_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_AnnualizedRewards_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_AnnualizedRewards_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_AnnualizedRewards_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "community", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Balance_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "community", "v1beta1", "balance"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TotalBalance_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "community", "v1beta1", "total_balance"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_AnnualizedRewards_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "community", "v1beta1", "annualized_rewards"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Balance_0 = runtime.ForwardResponseMessage - - forward_Query_TotalBalance_0 = runtime.ForwardResponseMessage - - forward_Query_AnnualizedRewards_0 = runtime.ForwardResponseMessage -) diff --git a/x/community/types/staking.go b/x/community/types/staking.go deleted file mode 100644 index 4f37222d..00000000 --- a/x/community/types/staking.go +++ /dev/null @@ -1,51 +0,0 @@ -package types - -import ( - "errors" - "time" - - sdkmath "cosmossdk.io/math" -) - -var ( - // DefaultLastAccumulationTime is zero - DefaultLastAccumulationTime = time.Time{} - // DefaultLastTruncationError is zero - DefaultLastTruncationError = sdkmath.LegacyZeroDec() -) - -// NewStakingRewardsState returns a new staking rewards state object -func NewStakingRewardsState( - lastAccumulationTime time.Time, - lastTruncationError sdkmath.LegacyDec, -) StakingRewardsState { - return StakingRewardsState{ - LastAccumulationTime: lastAccumulationTime, - LastTruncationError: lastTruncationError, - } -} - -// DefaultStakingRewardsState returns default params -func DefaultStakingRewardsState() StakingRewardsState { - return NewStakingRewardsState( - DefaultLastAccumulationTime, - DefaultLastTruncationError, - ) -} - -// Validate checks the params are valid -func (p StakingRewardsState) Validate() error { - if err := validateDecNotNilNonNegative(p.LastTruncationError, "LastTruncationError"); err != nil { - return err - } - - if p.LastTruncationError.GTE(sdkmath.LegacyOneDec()) { - return errors.New("LastTruncationError should not be greater or equal to 1") - } - - if p.LastAccumulationTime.IsZero() && !p.LastTruncationError.IsZero() { - return errors.New("LastTruncationError should be zero if last accumulation time is zero") - } - - return nil -} diff --git a/x/community/types/staking.pb.go b/x/community/types/staking.pb.go deleted file mode 100644 index 2248bec5..00000000 --- a/x/community/types/staking.pb.go +++ /dev/null @@ -1,386 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/community/v1beta1/staking.proto - -package types - -import ( - cosmossdk_io_math "cosmossdk.io/math" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// StakingRewardsState represents the state of staking reward accumulation between blocks. -type StakingRewardsState struct { - // last_accumulation_time represents the last block time which rewards where calculated and distributed. - // This may be zero to signal accumulation should start on the next interval. - LastAccumulationTime time.Time `protobuf:"bytes,1,opt,name=last_accumulation_time,json=lastAccumulationTime,proto3,stdtime" json:"last_accumulation_time"` - // accumulated_truncation_error represents the sum of previous errors due to truncation on payout - // This value will always be on the interval [0, 1). - LastTruncationError cosmossdk_io_math.LegacyDec `protobuf:"bytes,2,opt,name=last_truncation_error,json=lastTruncationError,proto3,customtype=cosmossdk.io/math.LegacyDec" json:"last_truncation_error"` -} - -func (m *StakingRewardsState) Reset() { *m = StakingRewardsState{} } -func (m *StakingRewardsState) String() string { return proto.CompactTextString(m) } -func (*StakingRewardsState) ProtoMessage() {} -func (*StakingRewardsState) Descriptor() ([]byte, []int) { - return fileDescriptor_fce59dad9b680fa3, []int{0} -} -func (m *StakingRewardsState) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *StakingRewardsState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_StakingRewardsState.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *StakingRewardsState) XXX_Merge(src proto.Message) { - xxx_messageInfo_StakingRewardsState.Merge(m, src) -} -func (m *StakingRewardsState) XXX_Size() int { - return m.Size() -} -func (m *StakingRewardsState) XXX_DiscardUnknown() { - xxx_messageInfo_StakingRewardsState.DiscardUnknown(m) -} - -var xxx_messageInfo_StakingRewardsState proto.InternalMessageInfo - -func (m *StakingRewardsState) GetLastAccumulationTime() time.Time { - if m != nil { - return m.LastAccumulationTime - } - return time.Time{} -} - -func init() { - proto.RegisterType((*StakingRewardsState)(nil), "kava.community.v1beta1.StakingRewardsState") -} - -func init() { - proto.RegisterFile("kava/community/v1beta1/staking.proto", fileDescriptor_fce59dad9b680fa3) -} - -var fileDescriptor_fce59dad9b680fa3 = []byte{ - // 333 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0x91, 0x41, 0x4e, 0x02, 0x31, - 0x14, 0x86, 0xa7, 0x2e, 0x8c, 0x8e, 0x3b, 0x40, 0x82, 0x98, 0xcc, 0x10, 0xe3, 0x82, 0x85, 0xb4, - 0xa0, 0x27, 0x90, 0xa0, 0x2b, 0x57, 0xc0, 0x8a, 0x0d, 0x79, 0x53, 0x6a, 0x99, 0x30, 0x33, 0x25, - 0xd3, 0x37, 0x28, 0xb7, 0xe0, 0x30, 0x1e, 0x82, 0x25, 0x71, 0x45, 0x5c, 0xa0, 0x81, 0x8b, 0x98, - 0x4e, 0x81, 0xb0, 0xeb, 0x7b, 0xf9, 0xfe, 0xaf, 0xf9, 0x5b, 0xf7, 0x7e, 0x02, 0x33, 0x60, 0x5c, - 0xc5, 0x71, 0x96, 0x84, 0x38, 0x67, 0xb3, 0x56, 0x20, 0x10, 0x5a, 0x4c, 0x23, 0x4c, 0xc2, 0x44, - 0xd2, 0x69, 0xaa, 0x50, 0x15, 0xca, 0x86, 0xa2, 0x47, 0x8a, 0xee, 0xa9, 0xea, 0x0d, 0x57, 0x3a, - 0x56, 0x7a, 0x98, 0x53, 0xcc, 0x0e, 0x36, 0x52, 0x2d, 0x49, 0x25, 0x95, 0xdd, 0x9b, 0xd3, 0x7e, - 0xeb, 0x4b, 0xa5, 0x64, 0x24, 0x58, 0x3e, 0x05, 0xd9, 0x3b, 0xc3, 0x30, 0x16, 0x1a, 0x21, 0x9e, - 0x5a, 0xe0, 0x6e, 0x4d, 0xdc, 0x62, 0xcf, 0xde, 0xdd, 0x15, 0x1f, 0x90, 0x8e, 0x74, 0x0f, 0x01, - 0x45, 0x61, 0xe0, 0x96, 0x23, 0xd0, 0x38, 0x04, 0xce, 0xb3, 0x38, 0x8b, 0x00, 0x43, 0x95, 0x0c, - 0x4d, 0xb8, 0x42, 0x6a, 0xa4, 0x7e, 0xf5, 0x58, 0xa5, 0xd6, 0x4c, 0x0f, 0x66, 0xda, 0x3f, 0x98, - 0xdb, 0x17, 0xcb, 0x8d, 0xef, 0x2c, 0x7e, 0x7d, 0xd2, 0x2d, 0x19, 0xc7, 0xf3, 0x89, 0xc2, 0x40, - 0x05, 0xe1, 0x5e, 0xe7, 0x6e, 0x4c, 0xb3, 0x84, 0x5b, 0xb3, 0x48, 0x53, 0x95, 0x56, 0xce, 0x6a, - 0xa4, 0x7e, 0xd9, 0x6e, 0x99, 0xf8, 0xcf, 0xc6, 0xbf, 0xb5, 0xfd, 0xf4, 0x68, 0x42, 0x43, 0xc5, - 0x62, 0xc0, 0x31, 0x7d, 0x13, 0x12, 0xf8, 0xbc, 0x23, 0xf8, 0xf7, 0x57, 0xc3, 0xdd, 0xd7, 0xef, - 0x08, 0xde, 0x2d, 0x1a, 0x5f, 0xff, 0xa8, 0x7b, 0x31, 0xb6, 0xf6, 0xeb, 0x72, 0xeb, 0x91, 0xd5, - 0xd6, 0x23, 0x7f, 0x5b, 0x8f, 0x2c, 0x76, 0x9e, 0xb3, 0xda, 0x79, 0xce, 0x7a, 0xe7, 0x39, 0x83, - 0x07, 0x19, 0xe2, 0x38, 0x0b, 0xcc, 0x03, 0xb3, 0xa6, 0x8c, 0x20, 0xd0, 0xac, 0x29, 0x1b, 0x7c, - 0x0c, 0x61, 0xc2, 0x3e, 0x4f, 0x3e, 0x07, 0xe7, 0x53, 0xa1, 0x83, 0xf3, 0xbc, 0xe2, 0xd3, 0x7f, - 0x00, 0x00, 0x00, 0xff, 0xff, 0x05, 0xd5, 0x6c, 0x66, 0xbb, 0x01, 0x00, 0x00, -} - -func (m *StakingRewardsState) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *StakingRewardsState) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *StakingRewardsState) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.LastTruncationError.Size() - i -= size - if _, err := m.LastTruncationError.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintStaking(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - n1, err1 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.LastAccumulationTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.LastAccumulationTime):]) - if err1 != nil { - return 0, err1 - } - i -= n1 - i = encodeVarintStaking(dAtA, i, uint64(n1)) - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintStaking(dAtA []byte, offset int, v uint64) int { - offset -= sovStaking(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *StakingRewardsState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.LastAccumulationTime) - n += 1 + l + sovStaking(uint64(l)) - l = m.LastTruncationError.Size() - n += 1 + l + sovStaking(uint64(l)) - return n -} - -func sovStaking(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozStaking(x uint64) (n int) { - return sovStaking(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *StakingRewardsState) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStaking - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: StakingRewardsState: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: StakingRewardsState: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LastAccumulationTime", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStaking - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthStaking - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthStaking - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.LastAccumulationTime, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LastTruncationError", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStaking - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthStaking - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthStaking - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.LastTruncationError.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipStaking(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthStaking - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipStaking(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowStaking - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowStaking - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowStaking - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthStaking - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupStaking - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthStaking - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthStaking = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowStaking = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupStaking = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/community/types/staking_test.go b/x/community/types/staking_test.go deleted file mode 100644 index 1758b9e8..00000000 --- a/x/community/types/staking_test.go +++ /dev/null @@ -1,105 +0,0 @@ -package types_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - sdkmath "cosmossdk.io/math" - "github.com/0glabs/0g-chain/x/community/types" -) - -type stakingRewardsStateTestCase struct { - name string - stakingRewardsState types.StakingRewardsState - expectedErr string -} - -var stakingRewardsStateTestCases = []stakingRewardsStateTestCase{ - { - name: "default stakingRewardsState are valid", - stakingRewardsState: types.DefaultStakingRewardsState(), - expectedErr: "", - }, - { - name: "valid example state", - stakingRewardsState: types.StakingRewardsState{ - LastAccumulationTime: time.Now(), - LastTruncationError: newDecFromString("0.10000000000000000"), - }, - expectedErr: "", - }, - { - name: "last accumulation time can be zero", - stakingRewardsState: types.StakingRewardsState{ - LastAccumulationTime: time.Time{}, - LastTruncationError: sdkmath.LegacyZeroDec(), - }, - expectedErr: "", - }, - { - name: "nil last truncation error is invalid", - stakingRewardsState: types.StakingRewardsState{ - LastAccumulationTime: time.Now(), - LastTruncationError: sdkmath.LegacyDec{}, - }, - expectedErr: "LastTruncationError should not be nil", - }, - { - name: "negative last truncation error is invalid", - stakingRewardsState: types.StakingRewardsState{ - LastAccumulationTime: time.Now(), - LastTruncationError: newDecFromString("-0.10000000000000000"), - }, - expectedErr: "LastTruncationError should not be negative", - }, - { - name: "last truncation error equal to 1 is invalid", - stakingRewardsState: types.StakingRewardsState{ - LastAccumulationTime: time.Now(), - LastTruncationError: newDecFromString("1.00000000000000000"), - }, - expectedErr: "LastTruncationError should not be greater or equal to 1", - }, - { - name: "last truncation error greater than 1 is invalid", - stakingRewardsState: types.StakingRewardsState{ - LastAccumulationTime: time.Now(), - LastTruncationError: newDecFromString("1.00000000000000000"), - }, - expectedErr: "LastTruncationError should not be greater or equal to 1", - }, - { - name: "last truncation error can not be set if last accumulation time is zero", - stakingRewardsState: types.StakingRewardsState{ - LastAccumulationTime: time.Time{}, - LastTruncationError: newDecFromString("0.10000000000000000"), - }, - expectedErr: "LastTruncationError should be zero if last accumulation time is zero", - }, -} - -func TestStakingRewardsStateValidate(t *testing.T) { - for _, tc := range stakingRewardsStateTestCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.stakingRewardsState.Validate() - - if tc.expectedErr == "" { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), tc.expectedErr) - } - }) - } -} - -// newDecFromString returns a new sdkmath.Int from a string -func newDecFromString(str string) sdkmath.LegacyDec { - num, err := sdkmath.LegacyNewDecFromStr(str) - if err != nil { - panic(err) - } - return num -} diff --git a/x/community/types/tx.pb.go b/x/community/types/tx.pb.go deleted file mode 100644 index a84797be..00000000 --- a/x/community/types/tx.pb.go +++ /dev/null @@ -1,1065 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/community/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// MsgFundCommunityPool allows an account to directly fund the community module account. -type MsgFundCommunityPool struct { - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` - Depositor string `protobuf:"bytes,2,opt,name=depositor,proto3" json:"depositor,omitempty"` -} - -func (m *MsgFundCommunityPool) Reset() { *m = MsgFundCommunityPool{} } -func (m *MsgFundCommunityPool) String() string { return proto.CompactTextString(m) } -func (*MsgFundCommunityPool) ProtoMessage() {} -func (*MsgFundCommunityPool) Descriptor() ([]byte, []int) { - return fileDescriptor_e81067e0fbdaca18, []int{0} -} -func (m *MsgFundCommunityPool) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgFundCommunityPool) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgFundCommunityPool.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgFundCommunityPool) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgFundCommunityPool.Merge(m, src) -} -func (m *MsgFundCommunityPool) XXX_Size() int { - return m.Size() -} -func (m *MsgFundCommunityPool) XXX_DiscardUnknown() { - xxx_messageInfo_MsgFundCommunityPool.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgFundCommunityPool proto.InternalMessageInfo - -// MsgFundCommunityPoolResponse defines the Msg/FundCommunityPool response type. -type MsgFundCommunityPoolResponse struct { -} - -func (m *MsgFundCommunityPoolResponse) Reset() { *m = MsgFundCommunityPoolResponse{} } -func (m *MsgFundCommunityPoolResponse) String() string { return proto.CompactTextString(m) } -func (*MsgFundCommunityPoolResponse) ProtoMessage() {} -func (*MsgFundCommunityPoolResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_e81067e0fbdaca18, []int{1} -} -func (m *MsgFundCommunityPoolResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgFundCommunityPoolResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgFundCommunityPoolResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgFundCommunityPoolResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgFundCommunityPoolResponse.Merge(m, src) -} -func (m *MsgFundCommunityPoolResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgFundCommunityPoolResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgFundCommunityPoolResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgFundCommunityPoolResponse proto.InternalMessageInfo - -// MsgUpdateParams allows an account to update the community module parameters. -type MsgUpdateParams struct { - // authority is the address that controls the module (defaults to x/gov unless overwritten). - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` - // params defines the x/community parameters to update. - Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"` -} - -func (m *MsgUpdateParams) Reset() { *m = MsgUpdateParams{} } -func (m *MsgUpdateParams) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateParams) ProtoMessage() {} -func (*MsgUpdateParams) Descriptor() ([]byte, []int) { - return fileDescriptor_e81067e0fbdaca18, []int{2} -} -func (m *MsgUpdateParams) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgUpdateParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateParams.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgUpdateParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateParams.Merge(m, src) -} -func (m *MsgUpdateParams) XXX_Size() int { - return m.Size() -} -func (m *MsgUpdateParams) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateParams.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateParams proto.InternalMessageInfo - -// MsgUpdateParamsResponse defines the Msg/UpdateParams response type. -type MsgUpdateParamsResponse struct { -} - -func (m *MsgUpdateParamsResponse) Reset() { *m = MsgUpdateParamsResponse{} } -func (m *MsgUpdateParamsResponse) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateParamsResponse) ProtoMessage() {} -func (*MsgUpdateParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_e81067e0fbdaca18, []int{3} -} -func (m *MsgUpdateParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgUpdateParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateParamsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgUpdateParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateParamsResponse.Merge(m, src) -} -func (m *MsgUpdateParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgUpdateParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateParamsResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgFundCommunityPool)(nil), "kava.community.v1beta1.MsgFundCommunityPool") - proto.RegisterType((*MsgFundCommunityPoolResponse)(nil), "kava.community.v1beta1.MsgFundCommunityPoolResponse") - proto.RegisterType((*MsgUpdateParams)(nil), "kava.community.v1beta1.MsgUpdateParams") - proto.RegisterType((*MsgUpdateParamsResponse)(nil), "kava.community.v1beta1.MsgUpdateParamsResponse") -} - -func init() { proto.RegisterFile("kava/community/v1beta1/tx.proto", fileDescriptor_e81067e0fbdaca18) } - -var fileDescriptor_e81067e0fbdaca18 = []byte{ - // 452 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x92, 0xb1, 0x8e, 0xd3, 0x30, - 0x18, 0xc7, 0x63, 0xee, 0x54, 0xe9, 0x7c, 0x48, 0x88, 0xa8, 0x82, 0xb6, 0x42, 0xee, 0xa9, 0x0c, - 0x74, 0xb8, 0xc6, 0xbd, 0x82, 0x18, 0x10, 0x0b, 0x3d, 0x89, 0x01, 0xa9, 0xd2, 0x29, 0x88, 0x85, - 0x05, 0x39, 0x89, 0xe5, 0x58, 0x77, 0xf1, 0x17, 0xc5, 0xce, 0x71, 0x7d, 0x03, 0x16, 0x24, 0x1e, - 0x81, 0x11, 0x31, 0xb3, 0xf0, 0x06, 0x37, 0x9e, 0x98, 0x98, 0x00, 0xa5, 0x0b, 0x8f, 0x81, 0x92, - 0x38, 0xa5, 0x40, 0x0b, 0xdc, 0x94, 0xd8, 0xfe, 0xff, 0xfd, 0xff, 0x7d, 0x9f, 0x3f, 0xdc, 0x3f, - 0x66, 0xa7, 0x8c, 0x86, 0x90, 0x24, 0xb9, 0x92, 0x66, 0x4e, 0x4f, 0x0f, 0x02, 0x6e, 0xd8, 0x01, - 0x35, 0x67, 0x5e, 0x9a, 0x81, 0x01, 0xf7, 0x46, 0x29, 0xf0, 0x96, 0x02, 0xcf, 0x0a, 0x7a, 0x24, - 0x04, 0x9d, 0x80, 0xa6, 0x01, 0xd3, 0x7c, 0xe9, 0x0a, 0x41, 0xaa, 0xda, 0xd7, 0xeb, 0xd6, 0xe7, - 0x2f, 0xaa, 0x15, 0xad, 0x17, 0xf6, 0xa8, 0x2d, 0x40, 0x40, 0xbd, 0x5f, 0xfe, 0xd9, 0xdd, 0xdb, - 0x1b, 0x48, 0x52, 0x96, 0xb1, 0xc4, 0x5a, 0x07, 0x1f, 0x11, 0x6e, 0xcf, 0xb4, 0x78, 0x9c, 0xab, - 0xe8, 0xb0, 0x51, 0x1e, 0x01, 0x9c, 0xb8, 0x21, 0x6e, 0xb1, 0x04, 0x72, 0x65, 0x3a, 0x68, 0x6f, - 0x6b, 0xb8, 0x3b, 0xe9, 0x7a, 0x36, 0xb2, 0xe4, 0x6b, 0xa0, 0xbd, 0x43, 0x90, 0x6a, 0x3a, 0x3e, - 0xff, 0xd2, 0x77, 0xde, 0x7f, 0xed, 0x0f, 0x85, 0x34, 0x71, 0x1e, 0x94, 0xb5, 0x59, 0x3e, 0xfb, - 0x19, 0xe9, 0xe8, 0x98, 0x9a, 0x79, 0xca, 0x75, 0x65, 0xd0, 0xbe, 0xbd, 0xda, 0xbd, 0x8f, 0x77, - 0x22, 0x9e, 0x82, 0x96, 0x06, 0xb2, 0xce, 0x95, 0x3d, 0x34, 0xdc, 0x99, 0x76, 0x3e, 0x7d, 0x18, - 0xb5, 0x6d, 0xd4, 0xa3, 0x28, 0xca, 0xb8, 0xd6, 0x4f, 0x4d, 0x26, 0x95, 0xf0, 0x7f, 0x4a, 0x1f, - 0x6c, 0xbf, 0x7a, 0xdb, 0x77, 0x06, 0x04, 0xdf, 0x5a, 0x87, 0xee, 0x73, 0x9d, 0x82, 0xd2, 0x7c, - 0xf0, 0x1a, 0xe1, 0x6b, 0x33, 0x2d, 0x9e, 0xa5, 0x11, 0x33, 0xfc, 0xa8, 0xaa, 0xba, 0x4c, 0x64, - 0xb9, 0x89, 0x21, 0x93, 0x66, 0xde, 0x41, 0xff, 0x4a, 0x5c, 0x4a, 0xdd, 0x87, 0xb8, 0x55, 0xf7, - 0xad, 0xc2, 0xdc, 0x9d, 0x10, 0x6f, 0xfd, 0x33, 0x7a, 0x75, 0xce, 0x74, 0xbb, 0xec, 0x89, 0x6f, - 0x3d, 0x96, 0xb7, 0x8b, 0x6f, 0xfe, 0x86, 0xd3, 0xa0, 0x4e, 0xbe, 0x23, 0xbc, 0x35, 0xd3, 0xc2, - 0x7d, 0x89, 0xaf, 0xff, 0xf9, 0x14, 0xfb, 0x9b, 0xb2, 0xd6, 0x55, 0xdf, 0xbb, 0x77, 0x19, 0x75, - 0x03, 0xe0, 0xc6, 0xf8, 0xea, 0x2f, 0x7d, 0xba, 0xf3, 0x97, 0x5b, 0x56, 0x85, 0x3d, 0xfa, 0x9f, - 0xc2, 0x26, 0x69, 0xfa, 0xe4, 0x5d, 0x41, 0xd0, 0x79, 0x41, 0xd0, 0x45, 0x41, 0xd0, 0xb7, 0x82, - 0xa0, 0x37, 0x0b, 0xe2, 0x5c, 0x2c, 0x88, 0xf3, 0x79, 0x41, 0x9c, 0xe7, 0xfb, 0x2b, 0x33, 0x34, - 0x16, 0x27, 0x2c, 0xd0, 0x74, 0x2c, 0x46, 0x61, 0xcc, 0xa4, 0xa2, 0x67, 0x2b, 0xc3, 0x5c, 0x4d, - 0x53, 0xd0, 0xaa, 0x86, 0xf8, 0xee, 0x8f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x7c, 0x2f, 0x37, 0xf3, - 0x75, 0x03, 0x00, 0x00, -} - -func (this *MsgFundCommunityPool) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MsgFundCommunityPool) - if !ok { - that2, ok := that.(MsgFundCommunityPool) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if len(this.Amount) != len(that1.Amount) { - return false - } - for i := range this.Amount { - if !this.Amount[i].Equal(&that1.Amount[i]) { - return false - } - } - if this.Depositor != that1.Depositor { - return false - } - return true -} -func (this *MsgFundCommunityPoolResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MsgFundCommunityPoolResponse) - if !ok { - that2, ok := that.(MsgFundCommunityPoolResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - return true -} -func (this *MsgUpdateParams) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MsgUpdateParams) - if !ok { - that2, ok := that.(MsgUpdateParams) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Authority != that1.Authority { - return false - } - if !this.Params.Equal(&that1.Params) { - return false - } - return true -} -func (this *MsgUpdateParamsResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MsgUpdateParamsResponse) - if !ok { - that2, ok := that.(MsgUpdateParamsResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - return true -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - // FundCommunityPool defines a method to allow an account to directly fund the community module account. - FundCommunityPool(ctx context.Context, in *MsgFundCommunityPool, opts ...grpc.CallOption) (*MsgFundCommunityPoolResponse, error) - // UpdateParams defines a method to allow an account to update the community module parameters. - UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) FundCommunityPool(ctx context.Context, in *MsgFundCommunityPool, opts ...grpc.CallOption) (*MsgFundCommunityPoolResponse, error) { - out := new(MsgFundCommunityPoolResponse) - err := c.cc.Invoke(ctx, "/kava.community.v1beta1.Msg/FundCommunityPool", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) { - out := new(MsgUpdateParamsResponse) - err := c.cc.Invoke(ctx, "/kava.community.v1beta1.Msg/UpdateParams", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // FundCommunityPool defines a method to allow an account to directly fund the community module account. - FundCommunityPool(context.Context, *MsgFundCommunityPool) (*MsgFundCommunityPoolResponse, error) - // UpdateParams defines a method to allow an account to update the community module parameters. - UpdateParams(context.Context, *MsgUpdateParams) (*MsgUpdateParamsResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) FundCommunityPool(ctx context.Context, req *MsgFundCommunityPool) (*MsgFundCommunityPoolResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method FundCommunityPool not implemented") -} -func (*UnimplementedMsgServer) UpdateParams(ctx context.Context, req *MsgUpdateParams) (*MsgUpdateParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UpdateParams not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_FundCommunityPool_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgFundCommunityPool) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).FundCommunityPool(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.community.v1beta1.Msg/FundCommunityPool", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).FundCommunityPool(ctx, req.(*MsgFundCommunityPool)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_UpdateParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgUpdateParams) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).UpdateParams(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.community.v1beta1.Msg/UpdateParams", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).UpdateParams(ctx, req.(*MsgUpdateParams)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.community.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "FundCommunityPool", - Handler: _Msg_FundCommunityPool_Handler, - }, - { - MethodName: "UpdateParams", - Handler: _Msg_UpdateParams_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/community/v1beta1/tx.proto", -} - -func (m *MsgFundCommunityPool) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgFundCommunityPool) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgFundCommunityPool) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0x12 - } - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *MsgFundCommunityPoolResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgFundCommunityPoolResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgFundCommunityPoolResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgUpdateParams) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgUpdateParams) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateParams) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgUpdateParamsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgUpdateParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgFundCommunityPool) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgFundCommunityPoolResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgUpdateParams) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Authority) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Params.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgUpdateParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgFundCommunityPool) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgFundCommunityPool: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgFundCommunityPool: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgFundCommunityPoolResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgFundCommunityPoolResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgFundCommunityPoolResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgUpdateParams) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgUpdateParams: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateParams: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Authority = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgUpdateParamsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgUpdateParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/earn/client/cli/query.go b/x/earn/client/cli/query.go deleted file mode 100644 index fb514e62..00000000 --- a/x/earn/client/cli/query.go +++ /dev/null @@ -1,208 +0,0 @@ -package cli - -import ( - "context" - "fmt" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/0glabs/0g-chain/x/earn/types" -) - -// flags for cli queries -const ( - flagDenom = "denom" - flagOwner = "owner" - flagValueInStakedTokens = "value_in_staked_tokens" -) - -// GetQueryCmd returns the cli query commands for the earn module -func GetQueryCmd() *cobra.Command { - earnQueryCommand := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the earn module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - queryParamsCmd(), - queryVaultsCmd(), - queryVaultCmd(), - queryDepositsCmd(), - queryTotalSupplyCmd(), - } - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - earnQueryCommand.AddCommand(cmds...) - - return earnQueryCommand -} - -func queryParamsCmd() *cobra.Command { - return &cobra.Command{ - Use: "params", - Short: "get the earn module parameters", - Long: "Get the current earn module parameters.", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - req := types.NewQueryParamsRequest() - res, err := queryClient.Params(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - } -} - -func queryVaultsCmd() *cobra.Command { - return &cobra.Command{ - Use: "vaults", - Short: "get all earn vaults", - Long: "Get all earn module vaults.", - Args: cobra.NoArgs, - Example: fmt.Sprintf(`%[1]s q %[2]s vaults`, version.AppName, types.ModuleName), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - req := types.NewQueryVaultsRequest() - res, err := queryClient.Vaults(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -func queryVaultCmd() *cobra.Command { - return &cobra.Command{ - Use: "vault", - Short: "get a earn vault", - Long: "Get a specific earn module vault by denom.", - Args: cobra.ExactArgs(1), - Example: fmt.Sprintf(`%[1]s q %[2]s vault usdx`, version.AppName, types.ModuleName), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - req := types.NewQueryVaultRequest(args[0]) - res, err := queryClient.Vault(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} - -func queryDepositsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "deposits", - Short: "get earn vault deposits", - Long: "Get earn vault deposits for all or specific accounts and vaults.", - Args: cobra.NoArgs, - Example: fmt.Sprintf(`%[1]s q %[2]s deposits -%[1]s q %[2]s deposits --owner kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny --denom usdx -%[1]s q %[2]s deposits --denom usdx`, version.AppName, types.ModuleName), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - ownerBech, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - valueInStakedTokens, err := cmd.Flags().GetBool(flagValueInStakedTokens) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - req := types.NewQueryDepositsRequest( - ownerBech, - denom, - valueInStakedTokens, - pageReq, - ) - res, err := queryClient.Deposits(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddPaginationFlagsToCmd(cmd, "deposits") - - cmd.Flags().String(flagOwner, "", "(optional) filter for deposits by owner address") - cmd.Flags().String(flagDenom, "", "(optional) filter for deposits by vault denom") - cmd.Flags().Bool(flagValueInStakedTokens, false, "(optional) get underlying staked tokens for staking derivative vaults") - - return cmd -} - -func queryTotalSupplyCmd() *cobra.Command { - return &cobra.Command{ - Use: "total-supply", - Short: "get total supply across all savings strategy vaults", - Long: "Get the sum of all denoms locking into vaults that allow the savings strategy.", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.TotalSupply(context.Background(), &types.QueryTotalSupplyRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} diff --git a/x/earn/client/cli/tx.go b/x/earn/client/cli/tx.go deleted file mode 100644 index 038b9512..00000000 --- a/x/earn/client/cli/tx.go +++ /dev/null @@ -1,229 +0,0 @@ -package cli - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - "github.com/0glabs/0g-chain/x/earn/types" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - earnTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: fmt.Sprintf("%s transactions subcommands", types.ModuleName), - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - getCmdDeposit(), - getCmdWithdraw(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - earnTxCmd.AddCommand(cmds...) - - return earnTxCmd -} - -func getCmdDeposit() *cobra.Command { - return &cobra.Command{ - Use: "deposit [amount] [strategy]", - Short: "deposit coins to an earn vault", - Example: fmt.Sprintf( - `%s tx %s deposit 10000000ukava hard --from `, - version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - amount, err := sdk.ParseCoinNormalized(args[0]) - if err != nil { - return err - } - - strategy := types.NewStrategyTypeFromString(args[1]) - if !strategy.IsValid() { - return fmt.Errorf("invalid strategy type: %s", args[1]) - } - - signer := clientCtx.GetFromAddress() - msg := types.NewMsgDeposit(signer.String(), amount, strategy) - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} - -func getCmdWithdraw() *cobra.Command { - return &cobra.Command{ - Use: "withdraw [amount] [strategy]", - Short: "withdraw coins from an earn vault", - Example: fmt.Sprintf( - `%s tx %s withdraw 10000000ukava hard --from `, - version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - amount, err := sdk.ParseCoinNormalized(args[0]) - if err != nil { - return err - } - - strategy := types.NewStrategyTypeFromString(args[1]) - if !strategy.IsValid() { - return fmt.Errorf("invalid strategy type: %s", args[1]) - } - - fromAddr := clientCtx.GetFromAddress() - msg := types.NewMsgWithdraw(fromAddr.String(), amount, strategy) - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} - -// GetCmdSubmitCommunityPoolDepositProposal implements the command to submit a community-pool deposit proposal -func GetCmdSubmitCommunityPoolDepositProposal() *cobra.Command { - cmd := &cobra.Command{ - Use: "community-pool-deposit [proposal-file]", - Args: cobra.ExactArgs(1), - Short: "Submit a community pool deposit proposal", - Long: strings.TrimSpace( - fmt.Sprintf(`Submit a community pool deposit proposal along with an initial deposit. -The proposal details must be supplied via a JSON file. -Example: -$ %s tx gov submit-proposal community-pool-deposit --from= -Where proposal.json contains: -{ - "title": "Community Pool Deposit", - "description": "Deposit some KAVA from community pool!", - "amount": - { - "denom": "ukava", - "amount": "100000000000" - }, - "deposit": [ - { - "denom": "ukava", - "amount": "1000000000" - } - ] -} -`, - version.AppName, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - proposal, err := ParseCommunityPoolDepositProposalJSON(clientCtx.Codec, args[0]) - if err != nil { - return err - } - - from := clientCtx.GetFromAddress() - content := types.NewCommunityPoolDepositProposal(proposal.Title, proposal.Description, proposal.Amount) - msg, err := govv1beta1.NewMsgSubmitProposal(content, proposal.Deposit, from) - if err != nil { - return err - } - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - return cmd -} - -// GetCmdSubmitCommunityPoolWithdrawProposal implements the command to submit a community-pool withdraw proposal -func GetCmdSubmitCommunityPoolWithdrawProposal() *cobra.Command { - cmd := &cobra.Command{ - Use: "community-pool-withdraw [proposal-file]", - Args: cobra.ExactArgs(1), - Short: "Submit a community pool withdraw proposal", - Long: strings.TrimSpace( - fmt.Sprintf(`Submit a community pool withdraw proposal along with an initial deposit. -The proposal details must be supplied via a JSON file. -Example: -$ %s tx gov submit-proposal community-pool-withdraw --from= -Where proposal.json contains: -{ - "title": "Community Pool Withdraw", - "description": "Withdraw some KAVA from community pool!", - "amount": - { - "denom": "ukava", - "amount": "100000000000" - }, - "deposit": [ - { - "denom": "ukava", - "amount": "1000000000" - } - ] -} -`, - version.AppName, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - proposal, err := ParseCommunityPoolWithdrawProposalJSON(clientCtx.Codec, args[0]) - if err != nil { - return err - } - - from := clientCtx.GetFromAddress() - content := types.NewCommunityPoolWithdrawProposal(proposal.Title, proposal.Description, proposal.Amount) - msg, err := govv1beta1.NewMsgSubmitProposal(content, proposal.Deposit, from) - if err != nil { - return err - } - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - return cmd -} diff --git a/x/earn/client/cli/utils.go b/x/earn/client/cli/utils.go deleted file mode 100644 index 6e2ab52c..00000000 --- a/x/earn/client/cli/utils.go +++ /dev/null @@ -1,39 +0,0 @@ -package cli - -import ( - "os" - - "github.com/cosmos/cosmos-sdk/codec" - - "github.com/0glabs/0g-chain/x/earn/types" -) - -// ParseCommunityPoolDepositProposalJSON reads and parses a CommunityPoolDepositProposalJSON from a file. -func ParseCommunityPoolDepositProposalJSON(cdc codec.JSONCodec, proposalFile string) (types.CommunityPoolDepositProposalJSON, error) { - proposal := types.CommunityPoolDepositProposalJSON{} - contents, err := os.ReadFile(proposalFile) - if err != nil { - return proposal, err - } - - if err := cdc.UnmarshalJSON(contents, &proposal); err != nil { - return proposal, err - } - - return proposal, nil -} - -// ParseCommunityPoolWithdrawProposalJSON reads and parses a CommunityPoolWithdrawProposalJSON from a file. -func ParseCommunityPoolWithdrawProposalJSON(cdc codec.JSONCodec, proposalFile string) (types.CommunityPoolWithdrawProposalJSON, error) { - proposal := types.CommunityPoolWithdrawProposalJSON{} - contents, err := os.ReadFile(proposalFile) - if err != nil { - return proposal, err - } - - if err := cdc.UnmarshalJSON(contents, &proposal); err != nil { - return proposal, err - } - - return proposal, nil -} diff --git a/x/earn/client/proposal_handler.go b/x/earn/client/proposal_handler.go deleted file mode 100644 index adb0ab23..00000000 --- a/x/earn/client/proposal_handler.go +++ /dev/null @@ -1,13 +0,0 @@ -package client - -import ( - govclient "github.com/cosmos/cosmos-sdk/x/gov/client" - - "github.com/0glabs/0g-chain/x/earn/client/cli" -) - -// community-pool deposit/withdraw proposal handlers -var ( - DepositProposalHandler = govclient.NewProposalHandler(cli.GetCmdSubmitCommunityPoolDepositProposal) - WithdrawProposalHandler = govclient.NewProposalHandler(cli.GetCmdSubmitCommunityPoolWithdrawProposal) -) diff --git a/x/earn/genesis.go b/x/earn/genesis.go deleted file mode 100644 index e234586c..00000000 --- a/x/earn/genesis.go +++ /dev/null @@ -1,63 +0,0 @@ -package earn - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/earn/keeper" - "github.com/0glabs/0g-chain/x/earn/types" -) - -// InitGenesis initializes genesis state -func InitGenesis( - ctx sdk.Context, - k keeper.Keeper, - ak types.AccountKeeper, - gs types.GenesisState, -) { - if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) - } - - // Total of all vault share records, vault record total supply should equal this - vaultTotalShares := types.NewVaultShares() - - for _, vaultShareRecord := range gs.VaultShareRecords { - if err := vaultShareRecord.Validate(); err != nil { - panic(fmt.Sprintf("invalid vault share: %s", err)) - } - - vaultTotalShares = vaultTotalShares.Add(vaultShareRecord.Shares...) - - k.SetVaultShareRecord(ctx, vaultShareRecord) - } - - for _, vaultRecord := range gs.VaultRecords { - if err := vaultRecord.Validate(); err != nil { - panic(fmt.Sprintf("invalid vault record: %s", err)) - } - - if !vaultRecord.TotalShares.Amount.Equal(vaultTotalShares.AmountOf(vaultRecord.TotalShares.Denom)) { - panic(fmt.Sprintf( - "invalid vault record total supply for %s, got %s but sum of vault shares is %s", - vaultRecord.TotalShares.Denom, - vaultRecord.TotalShares.Amount, - vaultTotalShares.AmountOf(vaultRecord.TotalShares.Denom), - )) - } - - k.SetVaultRecord(ctx, vaultRecord) - } - - k.SetParams(ctx, gs.Params) -} - -// ExportGenesis returns a GenesisState for a given context and keeper -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { - params := k.GetParams(ctx) - vaultRecords := k.GetAllVaultRecords(ctx) - vaultShareRecords := k.GetAllVaultShareRecords(ctx) - - return types.NewGenesisState(params, vaultRecords, vaultShareRecords) -} diff --git a/x/earn/genesis_test.go b/x/earn/genesis_test.go deleted file mode 100644 index 6a54bcc2..00000000 --- a/x/earn/genesis_test.go +++ /dev/null @@ -1,178 +0,0 @@ -package earn_test - -import ( - "testing" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/earn" - "github.com/0glabs/0g-chain/x/earn/testutil" - "github.com/0glabs/0g-chain/x/earn/types" - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type genesisTestSuite struct { - testutil.Suite -} - -func (suite *genesisTestSuite) Test_InitGenesis_ValidationPanic() { - invalidState := types.NewGenesisState( - types.Params{ - AllowedVaults: types.AllowedVaults{ - types.NewAllowedVault( - "usdx", types.StrategyTypes{types.STRATEGY_TYPE_HARD}, - false, - nil, - ), - }, - }, - types.VaultRecords{ - { - TotalShares: types.VaultShare{ - Denom: "", Amount: sdk.NewDec(1), - }, - }, - }, - types.VaultShareRecords{}, - ) - - suite.Panics(func() { - earn.InitGenesis(suite.Ctx, suite.Keeper, suite.AccountKeeper, invalidState) - }, "expected init genesis to panic with invalid state") -} - -func (suite *genesisTestSuite) Test_InitAndExportGenesis() { - depositor_1, err := sdk.AccAddressFromBech32("kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea") - suite.Require().NoError(err) - depositor_2, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - suite.Require().NoError(err) - - // slices are sorted by key as stored in the data store, so init and export can be compared with equal - state := types.NewGenesisState( - types.Params{ - AllowedVaults: types.AllowedVaults{ - types.NewAllowedVault( - "usdx", - types.StrategyTypes{types.STRATEGY_TYPE_HARD}, - false, - nil, - ), - types.NewAllowedVault( - "ukava", - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - true, - []sdk.AccAddress{suite.AccountKeeper.GetModuleAddress("distribution")}, - ), - }, - }, - types.VaultRecords{ - types.VaultRecord{ - TotalShares: types.NewVaultShare("ukava", sdk.NewDec(3800000)), - }, - types.VaultRecord{ - TotalShares: types.NewVaultShare("usdx", sdk.NewDec(1000000)), - }, - }, - types.VaultShareRecords{ - types.VaultShareRecord{ - Depositor: depositor_1, - Shares: types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(500000)), - types.NewVaultShare("ukava", sdk.NewDec(1900000)), - ), - }, - types.VaultShareRecord{ - Depositor: depositor_2, - Shares: types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(500000)), - types.NewVaultShare("ukava", sdk.NewDec(1900000)), - ), - }, - }, - ) - - earn.InitGenesis(suite.Ctx, suite.Keeper, suite.AccountKeeper, state) - suite.Equal(state.Params, suite.Keeper.GetParams(suite.Ctx)) - - vaultRecord1, _ := suite.Keeper.GetVaultRecord(suite.Ctx, "ukava") - vaultRecord2, _ := suite.Keeper.GetVaultRecord(suite.Ctx, "usdx") - suite.Equal(state.VaultRecords[0], vaultRecord1) - suite.Equal(state.VaultRecords[1], vaultRecord2) - - shareRecord1, _ := suite.Keeper.GetVaultShareRecord(suite.Ctx, depositor_1) - shareRecord2, _ := suite.Keeper.GetVaultShareRecord(suite.Ctx, depositor_2) - - suite.Equal(state.VaultShareRecords[0], shareRecord1) - suite.Equal(state.VaultShareRecords[1], shareRecord2) - - exportedState := earn.ExportGenesis(suite.Ctx, suite.Keeper) - suite.Equal(state, exportedState) -} - -func (suite *genesisTestSuite) Test_Marshall() { - depositor_1, err := sdk.AccAddressFromBech32("kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea") - suite.Require().NoError(err) - depositor_2, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - suite.Require().NoError(err) - - // slices are sorted by key as stored in the data store, so init and export can be compared with equal - state := types.NewGenesisState( - types.Params{ - AllowedVaults: types.AllowedVaults{ - types.NewAllowedVault( - "usdx", - types.StrategyTypes{types.STRATEGY_TYPE_HARD}, - false, - nil, - ), - types.NewAllowedVault( - "ukava", - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - true, - []sdk.AccAddress{suite.AccountKeeper.GetModuleAddress("distribution")}, - ), - }, - }, - types.VaultRecords{ - types.VaultRecord{ - TotalShares: types.NewVaultShare("ukava", sdk.NewDec(3800000)), - }, - types.VaultRecord{ - TotalShares: types.NewVaultShare("usdx", sdk.NewDec(1000000)), - }, - }, - types.VaultShareRecords{ - types.VaultShareRecord{ - Depositor: depositor_1, - Shares: types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(500000)), - types.NewVaultShare("ukava", sdk.NewDec(1900000)), - ), - }, - types.VaultShareRecord{ - Depositor: depositor_2, - Shares: types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(500000)), - types.NewVaultShare("ukava", sdk.NewDec(1900000)), - ), - }, - }, - ) - - encodingCfg := app.MakeEncodingConfig() - cdc := encodingCfg.Marshaler - - bz, err := cdc.Marshal(&state) - suite.Require().NoError(err, "expected genesis state to marshal without error") - - var decodedState types.GenesisState - err = cdc.Unmarshal(bz, &decodedState) - suite.Require().NoError(err, "expected genesis state to unmarshal without error") - - suite.Equal(state, decodedState) -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(genesisTestSuite)) -} diff --git a/x/earn/handler.go b/x/earn/handler.go deleted file mode 100644 index 3596a2ed..00000000 --- a/x/earn/handler.go +++ /dev/null @@ -1,25 +0,0 @@ -package earn - -import ( - errorsmod "cosmossdk.io/errors" - 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/0glabs/0g-chain/x/earn/keeper" - "github.com/0glabs/0g-chain/x/earn/types" -) - -// NewCommunityPoolProposalHandler -func NewCommunityPoolProposalHandler(k keeper.Keeper) govv1beta1.Handler { - return func(ctx sdk.Context, content govv1beta1.Content) error { - switch c := content.(type) { - case *types.CommunityPoolDepositProposal: - return keeper.HandleCommunityPoolDepositProposal(ctx, k, c) - case *types.CommunityPoolWithdrawProposal: - return keeper.HandleCommunityPoolWithdrawProposal(ctx, k, c) - default: - return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized earn proposal content type: %T", c) - } - } -} diff --git a/x/earn/keeper/deposit.go b/x/earn/keeper/deposit.go deleted file mode 100644 index 8127e06f..00000000 --- a/x/earn/keeper/deposit.go +++ /dev/null @@ -1,127 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/earn/types" -) - -// Deposit adds the provided amount from a depositor to a vault. The vault is -// specified by the denom in the amount. -func (k *Keeper) Deposit( - ctx sdk.Context, - depositor sdk.AccAddress, - amount sdk.Coin, - depositStrategy types.StrategyType, -) error { - // Get AllowedVault, if not found (not a valid vault), return error - allowedVault, found := k.GetAllowedVault(ctx, amount.Denom) - if !found { - return types.ErrInvalidVaultDenom - } - - if amount.IsZero() { - return types.ErrInsufficientAmount - } - - // Check if deposit strategy is supported by vault - if !allowedVault.IsStrategyAllowed(depositStrategy) { - return types.ErrInvalidVaultStrategy - } - - // Check if account can deposit -- this checks if the vault is private - // and if so, if the depositor is in the AllowedDepositors list - if !allowedVault.IsAccountAllowed(depositor) { - return types.ErrAccountDepositNotAllowed - } - - // Check if VaultRecord exists, create if not exist - vaultRecord, found := k.GetVaultRecord(ctx, amount.Denom) - if !found { - // Create a new VaultRecord with 0 supply - vaultRecord = types.NewVaultRecord(amount.Denom, sdk.ZeroDec()) - } - - // Get the strategy for the vault - // NOTE: Currently always uses the first one, AllowedVaults are currently - // only valid with 1 and only 1 strategy so this is safe. - // If/When multiple strategies are supported and users can specify specific - // strategies, shares should be issued per-strategy instead of per-vault. - strategy, err := k.GetStrategy(allowedVault.Strategies[0]) - if err != nil { - return err - } - - // Transfer amount to module account - if err := k.bankKeeper.SendCoinsFromAccountToModule( - ctx, - depositor, - types.ModuleName, - sdk.NewCoins(amount), - ); err != nil { - return err - } - - // Get VaultShareRecord for account, create if account has no deposits. - // This can still be found if the account has deposits for other vaults. - vaultShareRecord, found := k.GetVaultShareRecord(ctx, depositor) - if !found { - // Create a new empty VaultShareRecord with 0 supply - vaultShareRecord = types.NewVaultShareRecord(depositor, types.NewVaultShares()) - } - - shares, err := k.ConvertToShares(ctx, amount) - if err != nil { - return fmt.Errorf("failed to convert assets to shares: %w", err) - } - - isNew := vaultShareRecord.Shares.AmountOf(amount.Denom).IsZero() - if !isNew { - // If deposits for this vault already exists, call hook with user's existing shares - k.BeforeVaultDepositModified(ctx, amount.Denom, depositor, vaultShareRecord.Shares.AmountOf(amount.Denom)) - } - - // Increment VaultRecord total shares and account shares - vaultRecord.TotalShares = vaultRecord.TotalShares.Add(shares) - vaultShareRecord.Shares = vaultShareRecord.Shares.Add(shares) - - // Update VaultRecord and VaultShareRecord - k.SetVaultRecord(ctx, vaultRecord) - k.SetVaultShareRecord(ctx, vaultShareRecord) - - if isNew { - // If first deposit in this vault - k.AfterVaultDepositCreated(ctx, amount.Denom, depositor, shares.Amount) - } - - // Deposit to the strategy - if err := strategy.Deposit(ctx, amount); err != nil { - return err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeVaultDeposit, - sdk.NewAttribute(types.AttributeKeyVaultDenom, amount.Denom), - sdk.NewAttribute(types.AttributeKeyDepositor, depositor.String()), - sdk.NewAttribute(types.AttributeKeyShares, shares.Amount.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, amount.Amount.String()), - ), - ) - - return nil -} - -// DepositFromModuleAccount adds the provided amount from a depositor module -// account to a vault. The vault is specified by the denom in the amount. -func (k *Keeper) DepositFromModuleAccount( - ctx sdk.Context, - from string, - wantAmount sdk.Coin, - withdrawStrategy types.StrategyType, -) error { - addr := k.accountKeeper.GetModuleAddress(from) - return k.Deposit(ctx, addr, wantAmount, withdrawStrategy) -} diff --git a/x/earn/keeper/deposit_test.go b/x/earn/keeper/deposit_test.go deleted file mode 100644 index 765c30f0..00000000 --- a/x/earn/keeper/deposit_test.go +++ /dev/null @@ -1,193 +0,0 @@ -package keeper_test - -import ( - "os" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/earn/testutil" - "github.com/0glabs/0g-chain/x/earn/types" - "github.com/stretchr/testify/suite" -) - -func TestMain(m *testing.M) { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - os.Exit(m.Run()) -} - -type depositTestSuite struct { - testutil.Suite -} - -func (suite *depositTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) -} - -func TestDepositTestSuite(t *testing.T) { - suite.Run(t, new(depositTestSuite)) -} - -func (suite *depositTestSuite) TestDeposit_Balances() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance.Sub(depositAmount)), // Account decreases by deposit - ) - - suite.VaultTotalValuesEqual(sdk.NewCoins(depositAmount)) - suite.VaultTotalSharesEqual(types.NewVaultShares( - types.NewVaultShare(depositAmount.Denom, sdk.NewDecFromInt(depositAmount.Amount)), - )) -} - -func (suite *depositTestSuite) TestDeposit_Exceed() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 1001) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, sdkerrors.ErrInsufficientFunds) - - // No changes in balances - - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance), - ) - - suite.ModuleAccountBalanceEqual( - sdk.NewCoins(), - ) -} - -func (suite *depositTestSuite) TestDeposit_Zero() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 0) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrInsufficientAmount) - - // No changes in balances - - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance), - ) - - suite.ModuleAccountBalanceEqual( - sdk.NewCoins(), - ) -} - -func (suite *depositTestSuite) TestDeposit_InvalidVault() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 1001) - - // Vault not created -- doesn't exist - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrInvalidVaultDenom) - - // No changes in balances - - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance), - ) - - suite.ModuleAccountBalanceEqual( - sdk.NewCoins(), - ) -} - -func (suite *depositTestSuite) TestDeposit_InvalidStrategy() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 1001) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrInvalidVaultStrategy) -} - -func (suite *depositTestSuite) TestDeposit_PrivateVault() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1) - - suite.CreateVault( - vaultDenom, - types.StrategyTypes{types.STRATEGY_TYPE_HARD}, - true, - []sdk.AccAddress{acc1.GetAddress()}, - ) - - err := suite.Keeper.Deposit(suite.Ctx, acc2.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrAccountDepositNotAllowed, "private vault should not allow deposits from non-allowed addresses") - - err = suite.Keeper.Deposit(suite.Ctx, acc1.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err, "private vault should allow deposits from allowed addresses") -} - -func (suite *depositTestSuite) TestDeposit_bKava() { - vaultDenom := "bkava" - coinDenom := testutil.TestBkavaDenoms[0] - - startBalance := sdk.NewInt64Coin(coinDenom, 1000) - depositAmount := sdk.NewInt64Coin(coinDenom, 100) - - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - // vault denom is only "bkava" which has it's own special handler - suite.CreateVault( - vaultDenom, - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - false, - []sdk.AccAddress{}, - ) - - err := suite.Keeper.Deposit(suite.Ctx, acc1.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError( - err, - "should be able to deposit bkava derivative denom in bkava vault", - ) -} diff --git a/x/earn/keeper/grpc_query.go b/x/earn/keeper/grpc_query.go deleted file mode 100644 index 8b96fd15..00000000 --- a/x/earn/keeper/grpc_query.go +++ /dev/null @@ -1,569 +0,0 @@ -package keeper - -import ( - "context" - "fmt" - "strings" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/earn/types" -) - -type queryServer struct { - keeper Keeper -} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(k Keeper) types.QueryServer { - return &queryServer{keeper: k} -} - -var _ types.QueryServer = queryServer{} - -// Params implements the gRPC service handler for querying x/earn parameters. -func (s queryServer) Params( - ctx context.Context, - req *types.QueryParamsRequest, -) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - params := s.keeper.GetParams(sdkCtx) - - return &types.QueryParamsResponse{Params: params}, nil -} - -// Vaults implements the gRPC service handler for querying x/earn vaults. -func (s queryServer) Vaults( - ctx context.Context, - req *types.QueryVaultsRequest, -) (*types.QueryVaultsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - allowedVaults := s.keeper.GetAllowedVaults(sdkCtx) - allowedVaultsMap := make(map[string]types.AllowedVault) - visitedMap := make(map[string]bool) - for _, av := range allowedVaults { - allowedVaultsMap[av.Denom] = av - visitedMap[av.Denom] = false - } - - vaults := []types.VaultResponse{} - - var vaultRecordsErr error - - // Iterate over vault records instead of AllowedVaults to get all bkava-* - // vaults - s.keeper.IterateVaultRecords(sdkCtx, func(record types.VaultRecord) bool { - // Check if bkava, use allowed vault - allowedVaultDenom := record.TotalShares.Denom - if strings.HasPrefix(record.TotalShares.Denom, bkavaPrefix) { - allowedVaultDenom = bkavaDenom - } - - allowedVault, found := allowedVaultsMap[allowedVaultDenom] - if !found { - vaultRecordsErr = fmt.Errorf("vault record not found for vault record denom %s", record.TotalShares.Denom) - return true - } - - totalValue, err := s.keeper.GetVaultTotalValue(sdkCtx, record.TotalShares.Denom) - if err != nil { - vaultRecordsErr = err - // Stop iterating if error - return true - } - - vaults = append(vaults, types.VaultResponse{ - Denom: record.TotalShares.Denom, - Strategies: allowedVault.Strategies, - IsPrivateVault: allowedVault.IsPrivateVault, - AllowedDepositors: addressSliceToStringSlice(allowedVault.AllowedDepositors), - TotalShares: record.TotalShares.Amount.String(), - TotalValue: totalValue.Amount, - }) - - // Mark this allowed vault as visited - visitedMap[allowedVaultDenom] = true - - return false - }) - - if vaultRecordsErr != nil { - return nil, vaultRecordsErr - } - - // Add the allowed vaults that have not been visited yet - // These are always empty vaults, as the vault would have been visited - // earlier if there are any deposits - for denom, visited := range visitedMap { - if visited { - continue - } - - allowedVault, found := allowedVaultsMap[denom] - if !found { - return nil, fmt.Errorf("vault record not found for vault record denom %s", denom) - } - - vaults = append(vaults, types.VaultResponse{ - Denom: denom, - Strategies: allowedVault.Strategies, - IsPrivateVault: allowedVault.IsPrivateVault, - AllowedDepositors: addressSliceToStringSlice(allowedVault.AllowedDepositors), - // No shares, no value - TotalShares: sdk.ZeroDec().String(), - TotalValue: sdk.ZeroInt(), - }) - } - - // Does not include vaults that have no deposits, only iterates over vault - // records which exists only for those with deposits. - return &types.QueryVaultsResponse{ - Vaults: vaults, - }, nil -} - -// Vaults implements the gRPC service handler for querying x/earn vaults. -func (s queryServer) Vault( - ctx context.Context, - req *types.QueryVaultRequest, -) (*types.QueryVaultResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - if req.Denom == "" { - return nil, status.Errorf(codes.InvalidArgument, "empty denom") - } - - // Only 1 vault - allowedVault, found := s.keeper.GetAllowedVault(sdkCtx, req.Denom) - if !found { - return nil, status.Errorf(codes.NotFound, "vault not found with specified denom") - } - - // Handle bkava separately to get total of **all** bkava vaults - if req.Denom == bkavaDenom { - return s.getAggregateBkavaVault(sdkCtx, allowedVault) - } - - // Must be req.Denom and not allowedVault.Denom to get full "bkava" denom - vaultRecord, found := s.keeper.GetVaultRecord(sdkCtx, req.Denom) - if !found { - // No supply yet, no error just set it to zero - vaultRecord.TotalShares = types.NewVaultShare(req.Denom, sdk.ZeroDec()) - } - - totalValue, err := s.keeper.GetVaultTotalValue(sdkCtx, req.Denom) - if err != nil { - return nil, err - } - - vault := types.VaultResponse{ - // VaultRecord denom instead of AllowedVault.Denom for full bkava denom - Denom: vaultRecord.TotalShares.Denom, - Strategies: allowedVault.Strategies, - IsPrivateVault: allowedVault.IsPrivateVault, - AllowedDepositors: addressSliceToStringSlice(allowedVault.AllowedDepositors), - TotalShares: vaultRecord.TotalShares.Amount.String(), - TotalValue: totalValue.Amount, - } - - return &types.QueryVaultResponse{ - Vault: vault, - }, nil -} - -// getAggregateBkavaVault returns a VaultResponse of the total of all bkava -// vaults. -func (s queryServer) getAggregateBkavaVault( - ctx sdk.Context, - allowedVault types.AllowedVault, -) (*types.QueryVaultResponse, error) { - allBkava := sdk.NewCoins() - - var iterErr error - s.keeper.IterateVaultRecords(ctx, func(record types.VaultRecord) (stop bool) { - // Skip non bkava vaults - if !strings.HasPrefix(record.TotalShares.Denom, bkavaPrefix) { - return false - } - - vaultValue, err := s.keeper.GetVaultTotalValue(ctx, record.TotalShares.Denom) - if err != nil { - iterErr = err - return false - } - - allBkava = allBkava.Add(vaultValue) - - return false - }) - - if iterErr != nil { - return nil, iterErr - } - - vaultValue, err := s.keeper.liquidKeeper.GetStakedTokensForDerivatives(ctx, allBkava) - if err != nil { - return nil, err - } - - return &types.QueryVaultResponse{ - Vault: types.VaultResponse{ - Denom: bkavaDenom, - Strategies: allowedVault.Strategies, - IsPrivateVault: allowedVault.IsPrivateVault, - AllowedDepositors: addressSliceToStringSlice(allowedVault.AllowedDepositors), - // Empty for shares, as adding up all shares is not useful information - TotalShares: "0", - TotalValue: vaultValue.Amount, - }, - }, nil -} - -// Deposits implements the gRPC service handler for querying x/earn deposits. -func (s queryServer) Deposits( - ctx context.Context, - req *types.QueryDepositsRequest, -) (*types.QueryDepositsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - if req.Depositor == "" { - return nil, status.Errorf(codes.InvalidArgument, "depositor is required") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - // bkava aggregate total - if req.Denom == bkavaDenom { - return s.getOneAccountBkavaVaultDeposit(sdkCtx, req) - } - - // specific vault - if req.Denom != "" { - return s.getOneAccountOneVaultDeposit(sdkCtx, req) - } - - // all vaults - return s.getOneAccountAllDeposits(sdkCtx, req) -} - -// TotalSupply implements the gRPC service handler for querying x/earn total supply (TVL) -func (s queryServer) TotalSupply( - ctx context.Context, - req *types.QueryTotalSupplyRequest, -) (*types.QueryTotalSupplyResponse, error) { - sdkCtx := sdk.UnwrapSDKContext(ctx) - totalSupply := sdk.NewCoins() - liquidStakedDerivatives := sdk.NewCoins() - - // allowed vaults param contains info on allowed strategies, but bkava is aggregated - allowedVaults := s.keeper.GetAllowedVaults(sdkCtx) - allowedVaultByDenom := make(map[string]types.AllowedVault) - for _, av := range allowedVaults { - allowedVaultByDenom[av.Denom] = av - } - - var vaultRecordErr error - // iterate actual records to properly enumerate all denoms - s.keeper.IterateVaultRecords(sdkCtx, func(vault types.VaultRecord) (stop bool) { - isLiquidStakingDenom := false - // find allowed vault to get parameters. handle translating bkava denoms to allowed vault denom - allowedVaultDenom := vault.TotalShares.Denom - if strings.HasPrefix(vault.TotalShares.Denom, bkavaPrefix) { - isLiquidStakingDenom = true - allowedVaultDenom = bkavaDenom - } - allowedVault, found := allowedVaultByDenom[allowedVaultDenom] - if !found { - vaultRecordErr = fmt.Errorf("vault record not found for vault record denom %s", vault.TotalShares.Denom) - return true - } - - // only consider savings strategy vaults when determining supply - if !allowedVault.IsStrategyAllowed(types.STRATEGY_TYPE_SAVINGS) { - return false - } - - // vault has savings strategy! determine total value of vault and add to sum - vaultSupply, err := s.keeper.GetVaultTotalValue(sdkCtx, vault.TotalShares.Denom) - if err != nil { - vaultRecordErr = err - return true - } - - // liquid staked tokens must be converted to their underlying value - // aggregate them here and then we can convert to underlying values all at once at the end - if isLiquidStakingDenom { - liquidStakedDerivatives = liquidStakedDerivatives.Add(vaultSupply) - } else { - totalSupply = totalSupply.Add(vaultSupply) - } - return false - }) - - // determine underlying value of bkava denoms - if len(liquidStakedDerivatives) > 0 { - underlyingValue, err := s.keeper.liquidKeeper.GetStakedTokensForDerivatives( - sdkCtx, - liquidStakedDerivatives, - ) - if err != nil { - return nil, err - } - totalSupply = totalSupply.Add(sdk.NewCoin(bkavaDenom, underlyingValue.Amount)) - } - - return &types.QueryTotalSupplyResponse{ - Height: sdkCtx.BlockHeight(), - Result: totalSupply, - }, vaultRecordErr -} - -// getOneAccountOneVaultDeposit returns deposits for a specific vault and a specific -// account -func (s queryServer) getOneAccountOneVaultDeposit( - ctx sdk.Context, - req *types.QueryDepositsRequest, -) (*types.QueryDepositsResponse, error) { - depositor, err := sdk.AccAddressFromBech32(req.Depositor) - if err != nil { - return nil, status.Error(codes.InvalidArgument, "Invalid address") - } - - shareRecord, found := s.keeper.GetVaultShareRecord(ctx, depositor) - if !found { - return &types.QueryDepositsResponse{ - Deposits: []types.DepositResponse{ - { - Depositor: depositor.String(), - // Zero shares and zero value for no deposits - Shares: types.NewVaultShares(types.NewVaultShare(req.Denom, sdk.ZeroDec())), - Value: sdk.NewCoins(sdk.NewCoin(req.Denom, sdk.ZeroInt())), - }, - }, - Pagination: nil, - }, nil - } - - // Only requesting the value of the specified denom - value, err := s.keeper.GetVaultAccountValue(ctx, req.Denom, depositor) - if err != nil { - return nil, status.Error(codes.NotFound, err.Error()) - } - - if req.ValueInStakedTokens { - // Get underlying ukava amount if denom is a derivative - if !s.keeper.liquidKeeper.IsDerivativeDenom(ctx, req.Denom) { - return nil, status.Errorf( - codes.InvalidArgument, - "denom %s is not a derivative, ValueInStakedTokens can only be used with liquid derivatives", - req.Denom, - ) - } - - ukavaValue, err := s.keeper.liquidKeeper.GetStakedTokensForDerivatives(ctx, sdk.NewCoins(value)) - if err != nil { - // This should "never" happen if IsDerivativeDenom is true - panic("Error getting ukava value for " + req.Denom) - } - - value = ukavaValue - } - - return &types.QueryDepositsResponse{ - Deposits: []types.DepositResponse{ - { - Depositor: depositor.String(), - // Only respond with requested denom shares - Shares: types.NewVaultShares( - types.NewVaultShare(req.Denom, shareRecord.Shares.AmountOf(req.Denom)), - ), - Value: sdk.NewCoins(value), - }, - }, - Pagination: nil, - }, nil -} - -// getOneAccountBkavaVaultDeposit returns deposits for the aggregated bkava vault -// and a specific account -func (s queryServer) getOneAccountBkavaVaultDeposit( - ctx sdk.Context, - req *types.QueryDepositsRequest, -) (*types.QueryDepositsResponse, error) { - depositor, err := sdk.AccAddressFromBech32(req.Depositor) - if err != nil { - return nil, status.Error(codes.InvalidArgument, "Invalid address") - } - - shareRecord, found := s.keeper.GetVaultShareRecord(ctx, depositor) - if !found { - return &types.QueryDepositsResponse{ - Deposits: []types.DepositResponse{ - { - Depositor: depositor.String(), - // Zero shares and zero value for no deposits - Shares: types.NewVaultShares(types.NewVaultShare(req.Denom, sdk.ZeroDec())), - Value: sdk.NewCoins(sdk.NewCoin(req.Denom, sdk.ZeroInt())), - }, - }, - Pagination: nil, - }, nil - } - - // Get all account deposit values to add up bkava - totalAccountValue, err := getAccountTotalValue(ctx, s.keeper, depositor, shareRecord.Shares) - if err != nil { - return nil, err - } - - // Remove non-bkava coins, GetStakedTokensForDerivatives expects only bkava - totalBkavaValue := sdk.NewCoins() - for _, coin := range totalAccountValue { - if s.keeper.liquidKeeper.IsDerivativeDenom(ctx, coin.Denom) { - totalBkavaValue = totalBkavaValue.Add(coin) - } - } - - // Use account value with only the aggregate bkava converted to underlying staked tokens - stakedValue, err := s.keeper.liquidKeeper.GetStakedTokensForDerivatives(ctx, totalBkavaValue) - if err != nil { - return nil, err - } - - return &types.QueryDepositsResponse{ - Deposits: []types.DepositResponse{ - { - Depositor: depositor.String(), - // Only respond with requested denom shares - Shares: types.NewVaultShares( - types.NewVaultShare(req.Denom, shareRecord.Shares.AmountOf(req.Denom)), - ), - Value: sdk.NewCoins(stakedValue), - }, - }, - Pagination: nil, - }, nil -} - -// getOneAccountAllDeposits returns deposits for all vaults for a specific account -func (s queryServer) getOneAccountAllDeposits( - ctx sdk.Context, - req *types.QueryDepositsRequest, -) (*types.QueryDepositsResponse, error) { - depositor, err := sdk.AccAddressFromBech32(req.Depositor) - if err != nil { - return nil, status.Error(codes.InvalidArgument, "Invalid address") - } - - deposits := []types.DepositResponse{} - - accountShare, found := s.keeper.GetVaultShareRecord(ctx, depositor) - if !found { - return &types.QueryDepositsResponse{ - Deposits: []types.DepositResponse{}, - Pagination: nil, - }, nil - } - - value, err := getAccountTotalValue(ctx, s.keeper, depositor, accountShare.Shares) - if err != nil { - return nil, status.Error(codes.InvalidArgument, err.Error()) - } - - if req.ValueInStakedTokens { - // Plain slice to not sum ukava amounts together. This is not a valid - // sdk.Coin due to multiple coins of the same denom, but we need them to - // be separate in the response to not be an aggregate amount. - var valueInStakedTokens []sdk.Coin - - for _, coin := range value { - // Skip non-bkava coins - if !s.keeper.liquidKeeper.IsDerivativeDenom(ctx, coin.Denom) { - continue - } - - // Derivative coins are converted to underlying staked tokens - ukavaValue, err := s.keeper.liquidKeeper.GetStakedTokensForDerivatives(ctx, sdk.NewCoins(coin)) - if err != nil { - // This should "never" happen if IsDerivativeDenom is true - panic("Error getting ukava value for " + coin.Denom) - } - valueInStakedTokens = append(valueInStakedTokens, ukavaValue) - } - - var filteredShares types.VaultShares - for _, share := range accountShare.Shares { - // Remove non-bkava coins from shares as they are used to - // determine which value is mapped to which denom - // These should be in the same order as valueInStakedTokens - if !s.keeper.liquidKeeper.IsDerivativeDenom(ctx, share.Denom) { - continue - } - - filteredShares = append(filteredShares, share) - } - - value = valueInStakedTokens - accountShare.Shares = filteredShares - } - - deposits = append(deposits, types.DepositResponse{ - Depositor: depositor.String(), - Shares: accountShare.Shares, - Value: value, - }) - - return &types.QueryDepositsResponse{ - Deposits: deposits, - Pagination: nil, - }, nil -} - -// getAccountTotalValue returns the total value for all vaults for a specific -// account based on their shares. -func getAccountTotalValue( - ctx sdk.Context, - keeper Keeper, - account sdk.AccAddress, - shares types.VaultShares, -) (sdk.Coins, error) { - value := sdk.NewCoins() - - for _, share := range shares { - accValue, err := keeper.GetVaultAccountValue(ctx, share.Denom, account) - if err != nil { - return nil, err - } - - value = value.Add(sdk.NewCoin(share.Denom, accValue.Amount)) - } - - return value, nil -} - -func addressSliceToStringSlice(addresses []sdk.AccAddress) []string { - var strings []string - for _, address := range addresses { - strings = append(strings, address.String()) - } - - return strings -} diff --git a/x/earn/keeper/grpc_query_test.go b/x/earn/keeper/grpc_query_test.go deleted file mode 100644 index 466af2f4..00000000 --- a/x/earn/keeper/grpc_query_test.go +++ /dev/null @@ -1,905 +0,0 @@ -package keeper_test - -import ( - "context" - "fmt" - "testing" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/earn/keeper" - "github.com/0glabs/0g-chain/x/earn/testutil" - "github.com/0glabs/0g-chain/x/earn/types" - liquidtypes "github.com/0glabs/0g-chain/x/liquid/types" -) - -type grpcQueryTestSuite struct { - testutil.Suite - - queryClient types.QueryClient -} - -func (suite *grpcQueryTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) - - queryHelper := baseapp.NewQueryServerTestHelper(suite.Ctx, suite.App.InterfaceRegistry()) - types.RegisterQueryServer(queryHelper, keeper.NewQueryServerImpl(suite.Keeper)) - - suite.queryClient = types.NewQueryClient(queryHelper) -} - -func TestGrpcQueryTestSuite(t *testing.T) { - suite.Run(t, new(grpcQueryTestSuite)) -} - -func (suite *grpcQueryTestSuite) TestQueryParams() { - vaultDenom := "usdx" - - res, err := suite.queryClient.Params(context.Background(), types.NewQueryParamsRequest()) - suite.Require().NoError(err) - // ElementsMatch instead of Equal because AllowedVaults{} != AllowedVaults(nil) - suite.Require().ElementsMatch(types.DefaultParams().AllowedVaults, res.Params.AllowedVaults) - - // Add vault to params - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Query again for added vault - res, err = suite.queryClient.Params(context.Background(), types.NewQueryParamsRequest()) - suite.Require().NoError(err) - suite.Require().Equal( - types.AllowedVaults{ - types.NewAllowedVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil), - }, - res.Params.AllowedVaults, - ) -} - -func (suite *grpcQueryTestSuite) TestVaults_ZeroSupply() { - // Add vaults - suite.CreateVault("usdx", types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault("busd", types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - suite.Run("single", func() { - res, err := suite.queryClient.Vault(context.Background(), types.NewQueryVaultRequest("usdx")) - suite.Require().NoError(err) - suite.Require().Equal( - types.VaultResponse{ - Denom: "usdx", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: nil, - TotalShares: sdk.NewDec(0).String(), - TotalValue: sdkmath.NewInt(0), - }, - res.Vault, - ) - }) - - suite.Run("all", func() { - res, err := suite.queryClient.Vaults(context.Background(), types.NewQueryVaultsRequest()) - suite.Require().NoError(err) - suite.Require().ElementsMatch([]types.VaultResponse{ - { - Denom: "usdx", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: nil, - TotalShares: sdk.ZeroDec().String(), - TotalValue: sdk.ZeroInt(), - }, - { - Denom: "busd", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: nil, - TotalShares: sdk.ZeroDec().String(), - TotalValue: sdk.ZeroInt(), - }, - }, - res.Vaults, - ) - }) -} - -func (suite *grpcQueryTestSuite) TestVaults_WithSupply() { - vaultDenom := "usdx" - vault2Denom := testutil.TestBkavaDenoms[0] - - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - deposit2Amount := sdk.NewInt64Coin(vault2Denom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault("bkava", types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins( - sdk.NewInt64Coin(vaultDenom, 1000), - sdk.NewInt64Coin(vault2Denom, 1000), - ), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - err = suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), deposit2Amount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - res, err := suite.queryClient.Vaults(context.Background(), types.NewQueryVaultsRequest()) - suite.Require().NoError(err) - suite.Require().Len(res.Vaults, 2) - suite.Require().ElementsMatch( - []types.VaultResponse{ - { - Denom: vaultDenom, - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: nil, - TotalShares: sdk.NewDecFromInt(depositAmount.Amount).String(), - TotalValue: depositAmount.Amount, - }, - { - Denom: vault2Denom, - Strategies: []types.StrategyType{types.STRATEGY_TYPE_SAVINGS}, - IsPrivateVault: false, - AllowedDepositors: nil, - TotalShares: sdk.NewDecFromInt(deposit2Amount.Amount).String(), - TotalValue: deposit2Amount.Amount, - }, - }, - res.Vaults, - ) -} - -func (suite *grpcQueryTestSuite) TestVaults_MixedSupply() { - vaultDenom := "usdx" - vault2Denom := "busd" - vault3Denom := testutil.TestBkavaDenoms[0] - - depositAmount := sdk.NewInt64Coin(vault3Denom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault(vault2Denom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault("bkava", types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins( - sdk.NewInt64Coin(vaultDenom, 1000), - sdk.NewInt64Coin(vault2Denom, 1000), - sdk.NewInt64Coin(vault3Denom, 1000), - ), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - res, err := suite.queryClient.Vaults(context.Background(), types.NewQueryVaultsRequest()) - suite.Require().NoError(err) - suite.Require().Len(res.Vaults, 3) - suite.Require().ElementsMatch( - []types.VaultResponse{ - { - Denom: vaultDenom, - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: nil, - TotalShares: sdk.ZeroDec().String(), - TotalValue: sdk.ZeroInt(), - }, - { - Denom: vault2Denom, - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: nil, - TotalShares: sdk.ZeroDec().String(), - TotalValue: sdk.ZeroInt(), - }, - { - Denom: vault3Denom, - Strategies: []types.StrategyType{types.STRATEGY_TYPE_SAVINGS}, - IsPrivateVault: false, - AllowedDepositors: nil, - TotalShares: sdk.NewDecFromInt(depositAmount.Amount).String(), - TotalValue: depositAmount.Amount, - }, - }, - res.Vaults, - ) -} - -func (suite *grpcQueryTestSuite) TestVault_NotFound() { - _, err := suite.queryClient.Vault(context.Background(), types.NewQueryVaultRequest("usdx")) - suite.Require().Error(err) - suite.Require().ErrorIs(err, status.Errorf(codes.NotFound, "vault not found with specified denom")) -} - -func (suite *grpcQueryTestSuite) TestDeposits() { - // Validator setup for bkava - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr1, valAccAddr2, delegator := addrs[0], addrs[1], addrs[2] - valAddr1 := sdk.ValAddress(valAccAddr1) - valAddr2 := sdk.ValAddress(valAccAddr2) - - vault1Denom := "usdx" - vault2Denom := "busd" - vault3Denom := fmt.Sprintf("bkava-%s", valAddr1.String()) - vault4Denom := fmt.Sprintf("bkava-%s", valAddr2.String()) - - initialUkavaBalance := sdkmath.NewInt(1e9) - startBalance := sdk.NewCoins( - sdk.NewCoin("ukava", initialUkavaBalance), - sdk.NewInt64Coin(vault1Denom, 1000), - sdk.NewInt64Coin(vault2Denom, 1000), - // Bkava isn't actually minted via x/liquid - sdk.NewInt64Coin(vault3Denom, 1000), - sdk.NewInt64Coin(vault4Denom, 1000), - ) - - delegateAmount := sdkmath.NewInt(100e6) - - suite.App.FundAccount(suite.Ctx, valAccAddr1, startBalance) - suite.App.FundAccount(suite.Ctx, valAccAddr2, startBalance) - suite.App.FundAccount(suite.Ctx, delegator, startBalance) - - suite.CreateNewUnbondedValidator(valAddr1, initialUkavaBalance) - suite.CreateNewUnbondedValidator(valAddr2, initialUkavaBalance) - suite.CreateDelegation(valAddr1, delegator, delegateAmount) - suite.CreateDelegation(valAddr2, delegator, delegateAmount) - - staking.EndBlocker(suite.Ctx, suite.App.GetStakingKeeper()) - - savingsParams := suite.SavingsKeeper.GetParams(suite.Ctx) - savingsParams.SupportedDenoms = append(savingsParams.SupportedDenoms, "bkava") - suite.SavingsKeeper.SetParams(suite.Ctx, savingsParams) - - // Add vaults - suite.CreateVault(vault1Denom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault(vault2Denom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault("bkava", types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - deposit1Amount := sdk.NewInt64Coin(vault1Denom, 100) - deposit2Amount := sdk.NewInt64Coin(vault2Denom, 200) - deposit3Amount := sdk.NewInt64Coin(vault3Denom, 200) - deposit4Amount := sdk.NewInt64Coin(vault4Denom, 300) - - // Accounts - acc1 := suite.CreateAccount(startBalance, 0).GetAddress() - acc2 := delegator - - // Deposit into each vault from each account - 4 total deposits - // Acc 1: usdx + busd - // Acc 2: usdx + bkava-1 + bkava-2 - err := suite.Keeper.Deposit(suite.Ctx, acc1, deposit1Amount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - err = suite.Keeper.Deposit(suite.Ctx, acc1, deposit2Amount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - err = suite.Keeper.Deposit(suite.Ctx, acc2, deposit1Amount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - err = suite.Keeper.Deposit(suite.Ctx, acc2, deposit3Amount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - err = suite.Keeper.Deposit(suite.Ctx, acc2, deposit4Amount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - suite.Run("specific vault", func() { - // Query all deposits for account 1 - res, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(acc1.String(), vault1Denom, false, nil), - ) - suite.Require().NoError(err) - suite.Require().Len(res.Deposits, 1) - suite.Require().ElementsMatchf( - []types.DepositResponse{ - { - Depositor: acc1.String(), - // Only includes specified deposit shares - Shares: types.NewVaultShares( - types.NewVaultShare(deposit1Amount.Denom, sdk.NewDecFromInt(deposit1Amount.Amount)), - ), - // Only the specified vault denom value - Value: sdk.NewCoins(deposit1Amount), - }, - }, - res.Deposits, - "deposits should match, got %v", - res.Deposits, - ) - }) - - suite.Run("specific bkava vault", func() { - res, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(acc2.String(), vault3Denom, false, nil), - ) - suite.Require().NoError(err) - suite.Require().Len(res.Deposits, 1) - suite.Require().ElementsMatchf( - []types.DepositResponse{ - { - Depositor: acc2.String(), - // Only includes specified deposit shares - Shares: types.NewVaultShares( - types.NewVaultShare(deposit3Amount.Denom, sdk.NewDecFromInt(deposit3Amount.Amount)), - ), - // Only the specified vault denom value - Value: sdk.NewCoins(deposit3Amount), - }, - }, - res.Deposits, - "deposits should match, got %v", - res.Deposits, - ) - }) - - suite.Run("specific bkava vault in staked tokens", func() { - res, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(acc2.String(), vault3Denom, true, nil), - ) - suite.Require().NoError(err) - suite.Require().Len(res.Deposits, 1) - suite.Require().Equal( - types.DepositResponse{ - Depositor: acc2.String(), - // Only includes specified deposit shares - Shares: types.NewVaultShares( - types.NewVaultShare(deposit3Amount.Denom, sdk.NewDecFromInt(deposit3Amount.Amount)), - ), - // Only the specified vault denom value - Value: sdk.NewCoins( - sdk.NewCoin("ukava", deposit3Amount.Amount), - ), - }, - res.Deposits[0], - ) - }) - - suite.Run("invalid vault", func() { - _, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(acc1.String(), "notavaliddenom", false, nil), - ) - suite.Require().Error(err) - suite.Require().ErrorIs(err, status.Errorf(codes.NotFound, "vault for notavaliddenom not found")) - }) - - suite.Run("all vaults", func() { - // Query all deposits for account 1 - res, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(acc1.String(), "", false, nil), - ) - suite.Require().NoError(err) - suite.Require().Len(res.Deposits, 1) - suite.Require().ElementsMatch( - []types.DepositResponse{ - { - Depositor: acc1.String(), - Shares: types.NewVaultShares( - types.NewVaultShare(deposit1Amount.Denom, sdk.NewDecFromInt(deposit1Amount.Amount)), - types.NewVaultShare(deposit2Amount.Denom, sdk.NewDecFromInt(deposit2Amount.Amount)), - ), - Value: sdk.NewCoins(deposit1Amount, deposit2Amount), - }, - }, - res.Deposits, - ) - }) - - suite.Run("all vaults value in staked tokens", func() { - // Query all deposits for account 1 with value in staked tokens - res, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(acc2.String(), "", true, nil), - ) - suite.Require().NoError(err) - suite.Require().Len(res.Deposits, 1) - suite.Require().Equal( - types.DepositResponse{ - Depositor: acc2.String(), - Shares: types.VaultShares{ - // Does not include non-bkava vaults - types.NewVaultShare(deposit4Amount.Denom, sdk.NewDecFromInt(deposit4Amount.Amount)), - types.NewVaultShare(deposit3Amount.Denom, sdk.NewDecFromInt(deposit3Amount.Amount)), - }, - Value: sdk.Coins{ - // Does not include non-bkava vaults - sdk.NewCoin("ukava", deposit4Amount.Amount), - sdk.NewCoin("ukava", deposit3Amount.Amount), - }, - }, - res.Deposits[0], - ) - for i := range res.Deposits[0].Shares { - suite.Equal( - res.Deposits[0].Shares[i].Amount, - sdk.NewDecFromInt(res.Deposits[0].Value[i].Amount), - "order of deposit value should match shares", - ) - } - }) -} - -func (suite *grpcQueryTestSuite) TestDeposits_NoDeposits() { - vault1Denom := "usdx" - vault2Denom := "busd" - - // Add vaults - suite.CreateVault(vault1Denom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault(vault2Denom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault("bkava", types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - // Accounts - acc1 := suite.CreateAccount(sdk.NewCoins(), 0).GetAddress() - - suite.Run("specific vault", func() { - // Query all deposits for account 1 - res, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(acc1.String(), vault1Denom, false, nil), - ) - suite.Require().NoError(err) - suite.Require().Len(res.Deposits, 1) - suite.Require().ElementsMatchf( - []types.DepositResponse{ - { - Depositor: acc1.String(), - // Zero shares and zero value - Shares: nil, - Value: nil, - }, - }, - res.Deposits, - "deposits should match, got %v", - res.Deposits, - ) - }) - - suite.Run("all vaults", func() { - // Query all deposits for account 1 - res, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(acc1.String(), "", false, nil), - ) - suite.Require().NoError(err) - suite.Require().Empty(res.Deposits) - }) -} - -func (suite *grpcQueryTestSuite) TestDeposits_NoDepositor() { - _, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest("", "usdx", false, nil), - ) - suite.Require().Error(err) - suite.Require().ErrorIs(err, status.Error(codes.InvalidArgument, "depositor is required")) -} - -func (suite *grpcQueryTestSuite) TestDeposits_InvalidAddress() { - _, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest("asdf", "usdx", false, nil), - ) - suite.Require().Error(err) - suite.Require().ErrorIs(err, status.Error(codes.InvalidArgument, "Invalid address")) - - _, err = suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest("asdf", "", false, nil), - ) - suite.Require().Error(err) - suite.Require().ErrorIs(err, status.Error(codes.InvalidArgument, "Invalid address")) -} - -func (suite *grpcQueryTestSuite) TestDeposits_bKava() { - // vault denom is only "bkava" which has it's own special handler - suite.CreateVault( - "bkava", - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - false, - []sdk.AccAddress{}, - ) - - suite.CreateVault( - "ukava", - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - false, - []sdk.AccAddress{}, - ) - - address1, derivatives1, _ := suite.createAccountWithDerivatives(testutil.TestBkavaDenoms[0], sdkmath.NewInt(1e9)) - address2, derivatives2, _ := suite.createAccountWithDerivatives(testutil.TestBkavaDenoms[1], sdkmath.NewInt(1e9)) - - err := suite.App.FundAccount(suite.Ctx, address1, sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e9)))) - suite.Require().NoError(err) - - // Slash the last validator to reduce the value of it's derivatives to test bkava to underlying token conversion. - // First call end block to bond validator to enable slashing. - staking.EndBlocker(suite.Ctx, suite.App.GetStakingKeeper()) - err = suite.slashValidator(sdk.ValAddress(address2), sdk.MustNewDecFromStr("0.5")) - suite.Require().NoError(err) - - suite.Run("no deposits", func() { - // Query all deposits for account 1 - res, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(address1.String(), "bkava", false, nil), - ) - suite.Require().NoError(err) - suite.Require().Len(res.Deposits, 1) - suite.Require().ElementsMatchf( - []types.DepositResponse{ - { - Depositor: address1.String(), - // Zero shares for "bkava" aggregate - Shares: nil, - // Only the specified vault denom value - Value: nil, - }, - }, - res.Deposits, - "deposits should match, got %v", - res.Deposits, - ) - }) - - err = suite.Keeper.Deposit(suite.Ctx, address1, derivatives1, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - err = suite.BankKeeper.SendCoins(suite.Ctx, address2, address1, sdk.NewCoins(derivatives2)) - suite.Require().NoError(err) - err = suite.Keeper.Deposit(suite.Ctx, address1, derivatives2, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - err = suite.Keeper.Deposit(suite.Ctx, address1, sdk.NewInt64Coin("ukava", 1e6), types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - suite.Run("multiple deposits", func() { - // Query all deposits for account 1 - res, err := suite.queryClient.Deposits( - context.Background(), - types.NewQueryDepositsRequest(address1.String(), "bkava", false, nil), - ) - suite.Require().NoError(err) - suite.Require().Len(res.Deposits, 1) - // first validator isn't slashed, so bkava units equal to underlying staked tokens - // last validator slashed 50% so derivatives are worth half - // Excludes non-bkava deposits - expectedValue := derivatives1.Amount.Add(derivatives2.Amount.QuoRaw(2)) - suite.Require().ElementsMatchf( - []types.DepositResponse{ - { - Depositor: address1.String(), - // Zero shares for "bkava" aggregate - Shares: nil, - // Value returned in units of staked token - Value: sdk.NewCoins( - sdk.NewCoin(suite.bondDenom(), expectedValue), - ), - }, - }, - res.Deposits, - "deposits should match, got %v", - res.Deposits, - ) - }) -} - -func (suite *grpcQueryTestSuite) TestVault_bKava_Single() { - vaultDenom := "bkava" - coinDenom := testutil.TestBkavaDenoms[0] - - startBalance := sdk.NewInt64Coin(coinDenom, 1000) - depositAmount := sdk.NewInt64Coin(coinDenom, 100) - - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - // vault denom is only "bkava" which has it's own special handler - suite.CreateVault( - vaultDenom, - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - false, - []sdk.AccAddress{}, - ) - - err := suite.Keeper.Deposit(suite.Ctx, acc1.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError( - err, - "should be able to deposit bkava derivative denom in bkava vault", - ) - - res, err := suite.queryClient.Vault( - context.Background(), - types.NewQueryVaultRequest(coinDenom), - ) - suite.Require().NoError(err) - suite.Require().Equal( - types.VaultResponse{ - Denom: coinDenom, - Strategies: types.StrategyTypes{ - types.STRATEGY_TYPE_SAVINGS, - }, - IsPrivateVault: false, - AllowedDepositors: []string(nil), - TotalShares: "100.000000000000000000", - TotalValue: sdkmath.NewInt(100), - }, - res.Vault, - ) -} - -func (suite *grpcQueryTestSuite) TestVault_bKava_Aggregate() { - vaultDenom := "bkava" - - address1, derivatives1, _ := suite.createAccountWithDerivatives(testutil.TestBkavaDenoms[0], sdkmath.NewInt(1e9)) - address2, derivatives2, _ := suite.createAccountWithDerivatives(testutil.TestBkavaDenoms[1], sdkmath.NewInt(1e9)) - address3, derivatives3, _ := suite.createAccountWithDerivatives(testutil.TestBkavaDenoms[2], sdkmath.NewInt(1e9)) - // Slash the last validator to reduce the value of it's derivatives to test bkava to underlying token conversion. - // First call end block to bond validator to enable slashing. - staking.EndBlocker(suite.Ctx, suite.App.GetStakingKeeper()) - err := suite.slashValidator(sdk.ValAddress(address3), sdk.MustNewDecFromStr("0.5")) - suite.Require().NoError(err) - - // vault denom is only "bkava" which has it's own special handler - suite.CreateVault( - vaultDenom, - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - false, - []sdk.AccAddress{}, - ) - - err = suite.Keeper.Deposit(suite.Ctx, address1, derivatives1, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - err = suite.Keeper.Deposit(suite.Ctx, address2, derivatives2, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - err = suite.Keeper.Deposit(suite.Ctx, address3, derivatives3, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Query "bkava" to get aggregate amount - res, err := suite.queryClient.Vault( - context.Background(), - types.NewQueryVaultRequest(vaultDenom), - ) - suite.Require().NoError(err) - // first two validators are not slashed, so bkava units equal to underlying staked tokens - expectedValue := derivatives1.Amount.Add(derivatives2.Amount) - // last validator slashed 50% so derivatives are worth half - expectedValue = expectedValue.Add(derivatives2.Amount.QuoRaw(2)) - suite.Require().Equal( - types.VaultResponse{ - Denom: vaultDenom, - Strategies: types.StrategyTypes{ - types.STRATEGY_TYPE_SAVINGS, - }, - IsPrivateVault: false, - AllowedDepositors: []string(nil), - // No shares for aggregate - TotalShares: "0", - TotalValue: expectedValue, - }, - res.Vault, - ) -} - -func (suite *grpcQueryTestSuite) TestTotalSupply() { - deposit := func(addr sdk.AccAddress, denom string, amount int64) { - err := suite.Keeper.Deposit( - suite.Ctx, - addr, - sdk.NewInt64Coin(denom, amount), - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - } - testCases := []struct { - name string - setup func() - expectedSupply sdk.Coins - }{ - { - name: "no vaults mean no supply", - setup: func() {}, - expectedSupply: nil, - }, - { - name: "no savings vaults mean no supply", - setup: func() { - suite.CreateVault("usdx", types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault("busd", types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - }, - expectedSupply: nil, - }, - { - name: "empty savings vaults mean no supply", - setup: func() { - suite.CreateVault("usdx", types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - suite.CreateVault("busd", types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - }, - expectedSupply: nil, - }, - { - name: "calculates supply of savings vaults", - setup: func() { - vault1Denom := "usdx" - vault2Denom := "busd" - suite.CreateVault(vault1Denom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - suite.CreateVault(vault2Denom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - acc1 := suite.CreateAccount(sdk.NewCoins( - sdk.NewInt64Coin(vault1Denom, 1e6), - sdk.NewInt64Coin(vault2Denom, 1e6), - ), 0) - deposit(acc1.GetAddress(), vault1Denom, 1e5) - deposit(acc1.GetAddress(), vault2Denom, 1e5) - acc2 := suite.CreateAccount(sdk.NewCoins( - sdk.NewInt64Coin(vault1Denom, 1e6), - sdk.NewInt64Coin(vault2Denom, 1e6), - ), 0) - deposit(acc2.GetAddress(), vault1Denom, 2e5) - deposit(acc2.GetAddress(), vault2Denom, 2e5) - }, - expectedSupply: sdk.NewCoins( - sdk.NewInt64Coin("usdx", 3e5), - sdk.NewInt64Coin("busd", 3e5), - ), - }, - { - name: "calculates supply of savings vaults, even when private", - setup: func() { - vault1Denom := "ukava" - vault2Denom := "busd" - - acc1 := suite.CreateAccount(sdk.NewCoins( - sdk.NewInt64Coin(vault1Denom, 1e6), - sdk.NewInt64Coin(vault2Denom, 1e6), - ), 0) - acc2 := suite.CreateAccount(sdk.NewCoins( - sdk.NewInt64Coin(vault1Denom, 1e6), - sdk.NewInt64Coin(vault2Denom, 1e6), - ), 0) - - suite.CreateVault( - vault1Denom, - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - true, // private! - []sdk.AccAddress{acc1.GetAddress()}, // only acc1 can deposit. - ) - suite.CreateVault("busd", - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - false, - nil, - ) - - deposit(acc1.GetAddress(), vault1Denom, 1e5) - deposit(acc1.GetAddress(), vault2Denom, 1e5) - deposit(acc2.GetAddress(), vault2Denom, 2e5) - }, - expectedSupply: sdk.NewCoins( - sdk.NewInt64Coin("ukava", 1e5), - sdk.NewInt64Coin("busd", 3e5), - ), - }, - { - name: "aggregates supply of bkava vaults accounting for slashing", - setup: func() { - address1, derivatives1, _ := suite.createAccountWithDerivatives(testutil.TestBkavaDenoms[0], sdkmath.NewInt(1e9)) - address2, derivatives2, _ := suite.createAccountWithDerivatives(testutil.TestBkavaDenoms[1], sdkmath.NewInt(1e9)) - - // bond validators - staking.EndBlocker(suite.Ctx, suite.App.GetStakingKeeper()) - // slash val2 - its shares are now 80% as valuable! - err := suite.slashValidator(sdk.ValAddress(address2), sdk.MustNewDecFromStr("0.2")) - suite.Require().NoError(err) - - // create "bkava" vault. it holds all bkava denoms - suite.CreateVault("bkava", types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, []sdk.AccAddress{}) - - // deposit bkava - deposit(address1, testutil.TestBkavaDenoms[0], derivatives1.Amount.Int64()) - deposit(address2, testutil.TestBkavaDenoms[1], derivatives2.Amount.Int64()) - }, - expectedSupply: sdk.NewCoins( - sdk.NewCoin( - "bkava", - sdkmath.NewIntFromUint64(1e9). // derivative 1 - Add(sdkmath.NewInt(1e9).MulRaw(80).QuoRaw(100))), // derivative 2: original value * 80% - ), - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - tc.setup() - res, err := suite.queryClient.TotalSupply( - sdk.WrapSDKContext(suite.Ctx), - &types.QueryTotalSupplyRequest{}, - ) - suite.Require().NoError(err) - suite.Require().Equal(tc.expectedSupply, res.Result) - }) - } -} - -// createUnbondedValidator creates an unbonded validator with the given amount of self-delegation. -func (suite *grpcQueryTestSuite) createUnbondedValidator(address sdk.ValAddress, selfDelegation sdk.Coin, minSelfDelegation sdkmath.Int) error { - msg, err := stakingtypes.NewMsgCreateValidator( - address, - ed25519.GenPrivKey().PubKey(), - selfDelegation, - stakingtypes.Description{}, - stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - minSelfDelegation, - ) - if err != nil { - return err - } - - msgServer := stakingkeeper.NewMsgServerImpl(suite.App.GetStakingKeeper()) - _, err = msgServer.CreateValidator(sdk.WrapSDKContext(suite.Ctx), msg) - return err -} - -// createAccountWithDerivatives creates an account with the given amount and denom of derivative token. -// Internally, it creates a validator account and mints derivatives from the validator's self delegation. -func (suite *grpcQueryTestSuite) createAccountWithDerivatives(denom string, amount sdkmath.Int) (sdk.AccAddress, sdk.Coin, sdk.Coins) { - valAddress, err := liquidtypes.ParseLiquidStakingTokenDenom(denom) - suite.Require().NoError(err) - address := sdk.AccAddress(valAddress) - - remainingSelfDelegation := sdkmath.NewInt(1e6) - selfDelegation := sdk.NewCoin( - suite.bondDenom(), - amount.Add(remainingSelfDelegation), - ) - - suite.NewAccountFromAddr(address, sdk.NewCoins(selfDelegation)) - - err = suite.createUnbondedValidator(valAddress, selfDelegation, remainingSelfDelegation) - suite.Require().NoError(err) - - toConvert := sdk.NewCoin(suite.bondDenom(), amount) - derivatives, err := suite.App.GetLiquidKeeper().MintDerivative(suite.Ctx, - address, - valAddress, - toConvert, - ) - suite.Require().NoError(err) - - fullBalance := suite.BankKeeper.GetAllBalances(suite.Ctx, address) - - return address, derivatives, fullBalance -} - -// slashValidator slashes the validator with the given address by the given percentage. -func (suite *grpcQueryTestSuite) slashValidator(address sdk.ValAddress, slashFraction sdk.Dec) error { - stakingKeeper := suite.App.GetStakingKeeper() - - validator, found := stakingKeeper.GetValidator(suite.Ctx, address) - suite.Require().True(found) - consAddr, err := validator.GetConsAddr() - suite.Require().NoError(err) - - // Assume infraction was at current height. Note unbonding delegations and redelegations are only slashed if created after - // the infraction height so none will be slashed. - infractionHeight := suite.Ctx.BlockHeight() - - power := stakingKeeper.TokensToConsensusPower(suite.Ctx, validator.GetTokens()) - - stakingKeeper.Slash(suite.Ctx, consAddr, infractionHeight, power, slashFraction) - return nil -} - -// bondDenom fetches the staking denom from the staking module. -func (suite *grpcQueryTestSuite) bondDenom() string { - return suite.App.GetStakingKeeper().BondDenom(suite.Ctx) -} diff --git a/x/earn/keeper/hooks.go b/x/earn/keeper/hooks.go deleted file mode 100644 index d693b91c..00000000 --- a/x/earn/keeper/hooks.go +++ /dev/null @@ -1,34 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/earn/types" -) - -// Implements EarnHooks interface -var _ types.EarnHooks = Keeper{} - -// AfterVaultDepositCreated - call hook if registered -func (k Keeper) AfterVaultDepositCreated( - ctx sdk.Context, - vaultDenom string, - depositor sdk.AccAddress, - sharesOwned sdk.Dec, -) { - if k.hooks != nil { - k.hooks.AfterVaultDepositCreated(ctx, vaultDenom, depositor, sharesOwned) - } -} - -// BeforeVaultDepositModified - call hook if registered -func (k Keeper) BeforeVaultDepositModified( - ctx sdk.Context, - vaultDenom string, - depositor sdk.AccAddress, - sharesOwned sdk.Dec, -) { - if k.hooks != nil { - k.hooks.BeforeVaultDepositModified(ctx, vaultDenom, depositor, sharesOwned) - } -} diff --git a/x/earn/keeper/hooks_test.go b/x/earn/keeper/hooks_test.go deleted file mode 100644 index 63ff718a..00000000 --- a/x/earn/keeper/hooks_test.go +++ /dev/null @@ -1,539 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/0glabs/0g-chain/x/earn/testutil" - "github.com/0glabs/0g-chain/x/earn/types" - "github.com/0glabs/0g-chain/x/earn/types/mocks" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/suite" -) - -type hookTestSuite struct { - testutil.Suite -} - -func (suite *hookTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) -} - -func TestHookTestSuite(t *testing.T) { - suite.Run(t, new(hookTestSuite)) -} - -func (suite *hookTestSuite) TestHooks_DepositAndWithdraw() { - suite.Keeper.ClearHooks() - earnHooks := mocks.NewEarnHooks(suite.T()) - suite.Keeper.SetHooks(earnHooks) - - vault1Denom := "usdx" - vault2Denom := "ukava" - acc1deposit1Amount := sdk.NewInt64Coin(vault1Denom, 100) - acc1deposit2Amount := sdk.NewInt64Coin(vault2Denom, 200) - - acc2deposit1Amount := sdk.NewInt64Coin(vault1Denom, 200) - acc2deposit2Amount := sdk.NewInt64Coin(vault2Denom, 300) - - suite.CreateVault(vault1Denom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault(vault2Denom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins( - sdk.NewInt64Coin(vault1Denom, 1000), - sdk.NewInt64Coin(vault2Denom, 1000), - ), 0) - - acc2 := suite.CreateAccount(sdk.NewCoins( - sdk.NewInt64Coin(vault1Denom, 1000), - sdk.NewInt64Coin(vault2Denom, 1000), - ), 1) - - // first deposit creates vault - calls AfterVaultDepositCreated with initial shares - // shares are 1:1 - earnHooks.On( - "AfterVaultDepositCreated", - suite.Ctx, - acc1deposit1Amount.Denom, - acc.GetAddress(), - sdk.NewDecFromInt(acc1deposit1Amount.Amount), - ).Once() - err := suite.Keeper.Deposit( - suite.Ctx, - acc.GetAddress(), - acc1deposit1Amount, - types.STRATEGY_TYPE_HARD, - ) - suite.Require().NoError(err) - - // second deposit adds to vault - calls BeforeVaultDepositModified - // shares given are the initial shares, not new the shares added to the vault - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc1deposit1Amount.Denom, - acc.GetAddress(), - sdk.NewDecFromInt(acc1deposit1Amount.Amount), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc.GetAddress(), - acc1deposit1Amount, - types.STRATEGY_TYPE_HARD, - ) - suite.Require().NoError(err) - - // get the shares from the store from the last deposit - shareRecord, found := suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc.GetAddress(), - ) - suite.Require().True(found) - - // third deposit adds to vault - calls BeforeVaultDepositModified - // shares given are the shares added in previous deposit, not the shares added to the vault now - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc1deposit1Amount.Denom, - acc.GetAddress(), - shareRecord.AmountOf(acc1deposit1Amount.Denom), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc.GetAddress(), - acc1deposit1Amount, - types.STRATEGY_TYPE_HARD, - ) - suite.Require().NoError(err) - - // new deposit denom into vault creates the deposit and calls AfterVaultDepositCreated - earnHooks.On( - "AfterVaultDepositCreated", - suite.Ctx, - acc1deposit2Amount.Denom, - acc.GetAddress(), - sdk.NewDecFromInt(acc1deposit2Amount.Amount), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc.GetAddress(), - acc1deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // second deposit into vault calls BeforeVaultDepositModified with initial shares given - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc1deposit2Amount.Denom, - acc.GetAddress(), - sdk.NewDecFromInt(acc1deposit2Amount.Amount), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc.GetAddress(), - acc1deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // get the shares from the store from the last deposit - shareRecord, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc.GetAddress(), - ) - suite.Require().True(found) - - // third deposit into vault calls BeforeVaultDepositModified with shares from last deposit - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc1deposit2Amount.Denom, - acc.GetAddress(), - shareRecord.AmountOf(acc1deposit2Amount.Denom), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc.GetAddress(), - acc1deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // ------------------------------------------------------------ - // Second account deposits - - // first deposit by user - calls AfterVaultDepositCreated with user's shares - // not total shares - earnHooks.On( - "AfterVaultDepositCreated", - suite.Ctx, - acc2deposit1Amount.Denom, - acc2.GetAddress(), - sdk.NewDecFromInt(acc2deposit1Amount.Amount), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc2.GetAddress(), - acc2deposit1Amount, - types.STRATEGY_TYPE_HARD, - ) - suite.Require().NoError(err) - - // second deposit adds to vault - calls BeforeVaultDepositModified - // shares given are the initial shares, not new the shares added to the vault - // and not the total vault shares - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc2deposit1Amount.Denom, - acc2.GetAddress(), - sdk.NewDecFromInt(acc2deposit1Amount.Amount), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc2.GetAddress(), - acc2deposit1Amount, - types.STRATEGY_TYPE_HARD, - ) - suite.Require().NoError(err) - - // get the shares from the store from the last deposit - shareRecord2, found := suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc2.GetAddress(), - ) - suite.Require().True(found) - - // third deposit adds to vault - calls BeforeVaultDepositModified - // shares given are the shares added in previous deposit, not the shares added to the vault now - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc2deposit1Amount.Denom, - acc2.GetAddress(), - shareRecord2.AmountOf(acc2deposit1Amount.Denom), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc2.GetAddress(), - acc2deposit1Amount, - types.STRATEGY_TYPE_HARD, - ) - suite.Require().NoError(err) - - // new deposit denom into vault creates the deposit and calls AfterVaultDepositCreated - earnHooks.On( - "AfterVaultDepositCreated", - suite.Ctx, - acc2deposit2Amount.Denom, - acc2.GetAddress(), - sdk.NewDecFromInt(acc2deposit2Amount.Amount), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc2.GetAddress(), - acc2deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // second deposit into vault calls BeforeVaultDepositModified with initial shares given - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc2deposit2Amount.Denom, - acc2.GetAddress(), - sdk.NewDecFromInt(acc2deposit2Amount.Amount), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc2.GetAddress(), - acc2deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // get the shares from the store from the last deposit - shareRecord2, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc2.GetAddress(), - ) - suite.Require().True(found) - - // third deposit into vault calls BeforeVaultDepositModified with shares from last deposit - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc2deposit2Amount.Denom, - acc2.GetAddress(), - shareRecord2.AmountOf(acc2deposit2Amount.Denom), - ).Once() - err = suite.Keeper.Deposit( - suite.Ctx, - acc2.GetAddress(), - acc2deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // ------------------------------------------------------------ - // test hooks with a full withdraw of all shares deposit 1 denom - shareRecord, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc.GetAddress(), - ) - suite.Require().True(found) - - // all shares given to BeforeVaultDepositModified - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc1deposit1Amount.Denom, - acc.GetAddress(), - shareRecord.AmountOf(acc1deposit1Amount.Denom), - ).Once() - _, err = suite.Keeper.Withdraw( - suite.Ctx, - acc.GetAddress(), - // 3 deposits, multiply original deposit amount by 3 - sdk.NewCoin(acc1deposit1Amount.Denom, acc1deposit1Amount.Amount.MulRaw(3)), - types.STRATEGY_TYPE_HARD, - ) - suite.Require().NoError(err) - - // test hooks on partial withdraw - shareRecord, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc.GetAddress(), - ) - suite.Require().True(found) - - // all shares given to before deposit modified even with partial withdraw - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc1deposit2Amount.Denom, - acc.GetAddress(), - shareRecord.AmountOf(acc1deposit2Amount.Denom), - ).Once() - _, err = suite.Keeper.Withdraw( - suite.Ctx, - acc.GetAddress(), - acc1deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // test hooks on second partial withdraw - shareRecord, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc.GetAddress(), - ) - suite.Require().True(found) - - // all shares given to before deposit modified even with partial withdraw - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc1deposit2Amount.Denom, - acc.GetAddress(), - shareRecord.AmountOf(acc1deposit2Amount.Denom), - ).Once() - _, err = suite.Keeper.Withdraw( - suite.Ctx, - acc.GetAddress(), - acc1deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // test hooks withdraw all remaining shares - shareRecord, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc.GetAddress(), - ) - suite.Require().True(found) - - // all shares given to before deposit modified even with partial withdraw - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc1deposit2Amount.Denom, - acc.GetAddress(), - shareRecord.AmountOf(acc1deposit2Amount.Denom), - ).Once() - _, err = suite.Keeper.Withdraw( - suite.Ctx, - acc.GetAddress(), - acc1deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // ------------------------------------------------------------ - // withdraw from acc2 - shareRecord, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc2.GetAddress(), - ) - suite.Require().True(found) - - // all shares given to BeforeVaultDepositModified - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc2deposit1Amount.Denom, - acc2.GetAddress(), - shareRecord.AmountOf(acc2deposit1Amount.Denom), - ).Once() - _, err = suite.Keeper.Withdraw( - suite.Ctx, - acc2.GetAddress(), - // 3 deposits, multiply original deposit amount by 3 - sdk.NewCoin(acc2deposit1Amount.Denom, acc2deposit1Amount.Amount.MulRaw(3)), - types.STRATEGY_TYPE_HARD, - ) - suite.Require().NoError(err) - - // test hooks on partial withdraw - shareRecord2, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc2.GetAddress(), - ) - suite.Require().True(found) - - // all shares given to before deposit modified even with partial withdraw - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc2deposit2Amount.Denom, - acc2.GetAddress(), - shareRecord2.AmountOf(acc2deposit2Amount.Denom), - ).Once() - _, err = suite.Keeper.Withdraw( - suite.Ctx, - acc2.GetAddress(), - acc2deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // test hooks on second partial withdraw - shareRecord2, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc2.GetAddress(), - ) - suite.Require().True(found) - - // all shares given to before deposit modified even with partial withdraw - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc2deposit2Amount.Denom, - acc2.GetAddress(), - shareRecord2.AmountOf(acc2deposit2Amount.Denom), - ).Once() - _, err = suite.Keeper.Withdraw( - suite.Ctx, - acc2.GetAddress(), - acc2deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) - - // test hooks withdraw all remaining shares - shareRecord2, found = suite.Keeper.GetVaultAccountShares( - suite.Ctx, - acc2.GetAddress(), - ) - suite.Require().True(found) - - // all shares given to before deposit modified even with partial withdraw - earnHooks.On( - "BeforeVaultDepositModified", - suite.Ctx, - acc2deposit2Amount.Denom, - acc2.GetAddress(), - shareRecord2.AmountOf(acc2deposit2Amount.Denom), - ).Once() - _, err = suite.Keeper.Withdraw( - suite.Ctx, - acc2.GetAddress(), - acc2deposit2Amount, - types.STRATEGY_TYPE_SAVINGS, - ) - suite.Require().NoError(err) -} - -func (suite *hookTestSuite) TestHooks_NoPanicsOnNilHooks() { - suite.Keeper.ClearHooks() - - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - withdrawAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - // AfterVaultDepositModified should not panic if no hooks are registered - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // BeforeVaultDepositModified should not panic if no hooks are registered - err = suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // BeforeVaultDepositModified should not panic if no hooks are registered - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), withdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) -} - -func (suite *hookTestSuite) TestHooks_HookOrdering() { - suite.Keeper.ClearHooks() - earnHooks := &mocks.EarnHooks{} - suite.Keeper.SetHooks(earnHooks) - - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - earnHooks.On("AfterVaultDepositCreated", suite.Ctx, depositAmount.Denom, acc.GetAddress(), sdk.NewDecFromInt(depositAmount.Amount)). - Run(func(args mock.Arguments) { - shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc.GetAddress()) - suite.Require().True(found, "expected after hook to be called after shares are updated") - suite.Require().Equal(sdk.NewDecFromInt(depositAmount.Amount), shares.AmountOf(depositAmount.Denom)) - }) - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - earnHooks.On("BeforeVaultDepositModified", suite.Ctx, depositAmount.Denom, acc.GetAddress(), sdk.NewDecFromInt(depositAmount.Amount)). - Run(func(args mock.Arguments) { - shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc.GetAddress()) - suite.Require().True(found, "expected after hook to be called after shares are updated") - suite.Require().Equal(sdk.NewDecFromInt(depositAmount.Amount), shares.AmountOf(depositAmount.Denom)) - }) - err = suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - existingShares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc.GetAddress()) - suite.Require().True(found) - earnHooks.On("BeforeVaultDepositModified", suite.Ctx, depositAmount.Denom, acc.GetAddress(), existingShares.AmountOf(depositAmount.Denom)). - Run(func(args mock.Arguments) { - shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc.GetAddress()) - suite.Require().True(found, "expected after hook to be called after shares are updated") - suite.Require().Equal(sdk.NewDecFromInt(depositAmount.Amount.MulRaw(2)), shares.AmountOf(depositAmount.Denom)) - }) - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) -} diff --git a/x/earn/keeper/invariants.go b/x/earn/keeper/invariants.go deleted file mode 100644 index 5f94d7f8..00000000 --- a/x/earn/keeper/invariants.go +++ /dev/null @@ -1,115 +0,0 @@ -package keeper - -import ( - "github.com/0glabs/0g-chain/x/earn/types" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// RegisterInvariants registers the swap module invariants -func RegisterInvariants(ir sdk.InvariantRegistry, k Keeper) { - ir.RegisterRoute(types.ModuleName, "vault-records", VaultRecordsInvariant(k)) - ir.RegisterRoute(types.ModuleName, "share-records", ShareRecordsInvariant(k)) - ir.RegisterRoute(types.ModuleName, "vault-shares", VaultSharesInvariant(k)) -} - -// AllInvariants runs all invariants of the swap module -func AllInvariants(k Keeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - if res, stop := VaultRecordsInvariant(k)(ctx); stop { - return res, stop - } - - if res, stop := ShareRecordsInvariant(k)(ctx); stop { - return res, stop - } - - res, stop := VaultSharesInvariant(k)(ctx) - return res, stop - } -} - -// VaultRecordsInvariant iterates all vault records and asserts that they are valid -func VaultRecordsInvariant(k Keeper) sdk.Invariant { - broken := false - message := sdk.FormatInvariant(types.ModuleName, "validate vault records broken", "vault record invalid") - - return func(ctx sdk.Context) (string, bool) { - k.IterateVaultRecords(ctx, func(record types.VaultRecord) bool { - if err := record.Validate(); err != nil { - broken = true - return true - } - return false - }) - - return message, broken - } -} - -// ShareRecordsInvariant iterates all share records and asserts that they are valid -func ShareRecordsInvariant(k Keeper) sdk.Invariant { - broken := false - message := sdk.FormatInvariant(types.ModuleName, "validate share records broken", "share record invalid") - - return func(ctx sdk.Context) (string, bool) { - k.IterateVaultShareRecords(ctx, func(record types.VaultShareRecord) bool { - if err := record.Validate(); err != nil { - broken = true - return true - } - return false - }) - - return message, broken - } -} - -type vaultShares struct { - totalShares types.VaultShare - totalSharesOwned types.VaultShare -} - -// VaultSharesInvariant iterates all vaults and shares and ensures the total vault shares match the sum of depositor shares -func VaultSharesInvariant(k Keeper) sdk.Invariant { - broken := false - message := sdk.FormatInvariant(types.ModuleName, "vault shares broken", "vault shares do not match depositor shares") - - return func(ctx sdk.Context) (string, bool) { - totalShares := make(map[string]vaultShares) - - k.IterateVaultRecords(ctx, func(record types.VaultRecord) bool { - totalShares[record.TotalShares.Denom] = vaultShares{ - totalShares: record.TotalShares, - totalSharesOwned: types.NewVaultShare(record.TotalShares.Denom, sdk.ZeroDec()), - } - - return false - }) - - k.IterateVaultShareRecords(ctx, func(sr types.VaultShareRecord) bool { - for _, share := range sr.Shares { - if shares, found := totalShares[share.Denom]; found { - shares.totalSharesOwned = shares.totalSharesOwned.Add(share) - totalShares[share.Denom] = shares - } else { - totalShares[share.Denom] = vaultShares{ - totalShares: types.NewVaultShare(share.Denom, sdk.ZeroDec()), - totalSharesOwned: share, - } - } - } - - return false - }) - - for _, share := range totalShares { - if !share.totalShares.Amount.Equal(share.totalSharesOwned.Amount) { - broken = true - break - } - } - - return message, broken - } -} diff --git a/x/earn/keeper/invariants_test.go b/x/earn/keeper/invariants_test.go deleted file mode 100644 index 12f9687d..00000000 --- a/x/earn/keeper/invariants_test.go +++ /dev/null @@ -1,182 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/earn/keeper" - "github.com/0glabs/0g-chain/x/earn/testutil" - "github.com/0glabs/0g-chain/x/earn/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" -) - -type invariantTestSuite struct { - testutil.Suite - - invariants map[string]map[string]sdk.Invariant - addrs []sdk.AccAddress -} - -func TestInvariantTestSuite(t *testing.T) { - suite.Run(t, new(invariantTestSuite)) -} - -func (suite *invariantTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.invariants = make(map[string]map[string]sdk.Invariant) - keeper.RegisterInvariants(suite, suite.Keeper) - - _, addrs := app.GeneratePrivKeyAddressPairs(4) - suite.addrs = addrs -} - -func (suite *invariantTestSuite) SetupValidState() { - suite.Keeper.SetVaultRecord(suite.Ctx, types.NewVaultRecord( - "usdx", - sdk.MustNewDecFromStr("100"), - )) - suite.Keeper.SetVaultRecord(suite.Ctx, types.NewVaultRecord( - "ukava", - sdk.MustNewDecFromStr("250.123456"), - )) - - vaultShare1 := types.NewVaultShareRecord( - suite.addrs[0], - types.NewVaultShares( - types.NewVaultShare("usdx", sdk.MustNewDecFromStr("50")), - types.NewVaultShare("ukava", sdk.MustNewDecFromStr("105.123")), - ), - ) - vaultShare2 := types.NewVaultShareRecord( - suite.addrs[1], - types.NewVaultShares( - types.NewVaultShare("usdx", sdk.MustNewDecFromStr("50")), - types.NewVaultShare("ukava", sdk.MustNewDecFromStr("145.000456")), - ), - ) - - suite.Require().NoError(vaultShare1.Validate()) - suite.Require().NoError(vaultShare2.Validate()) - - suite.Keeper.SetVaultShareRecord(suite.Ctx, vaultShare1) - suite.Keeper.SetVaultShareRecord(suite.Ctx, vaultShare2) -} - -func (suite *invariantTestSuite) RegisterRoute(moduleName string, route string, invariant sdk.Invariant) { - _, exists := suite.invariants[moduleName] - - if !exists { - suite.invariants[moduleName] = make(map[string]sdk.Invariant) - } - - suite.invariants[moduleName][route] = invariant -} - -func (suite *invariantTestSuite) runInvariant(route string, invariant func(k keeper.Keeper) sdk.Invariant) (string, bool) { - ctx := suite.Ctx - registeredInvariant := suite.invariants[types.ModuleName][route] - suite.Require().NotNil(registeredInvariant) - - // direct call - dMessage, dBroken := invariant(suite.Keeper)(ctx) - // registered call - rMessage, rBroken := registeredInvariant(ctx) - // all call - aMessage, aBroken := keeper.AllInvariants(suite.Keeper)(ctx) - - // require matching values for direct call and registered call - suite.Require().Equal(dMessage, rMessage, "expected registered invariant message to match") - suite.Require().Equal(dBroken, rBroken, "expected registered invariant broken to match") - // require matching values for direct call and all invariants call if broken - suite.Require().Equalf(dBroken, aBroken, "expected all invariant broken to match, direct %v != all %v", dBroken, aBroken) - if dBroken { - suite.Require().Equal(dMessage, aMessage, "expected all invariant message to match") - } - - // return message, broken - return dMessage, dBroken -} - -func (suite *invariantTestSuite) TestVaultRecordsInvariant() { - // default state is valid - message, broken := suite.runInvariant("vault-records", keeper.VaultRecordsInvariant) - suite.Equal("earn: validate vault records broken invariant\nvault record invalid\n", message) - suite.Equal(false, broken) - - suite.SetupValidState() - message, broken = suite.runInvariant("vault-records", keeper.VaultRecordsInvariant) - suite.Equal("earn: validate vault records broken invariant\nvault record invalid\n", message) - suite.Equal(false, broken) - - // broken with invalid vault record - suite.Keeper.SetVaultRecord(suite.Ctx, types.VaultRecord{ - TotalShares: types.VaultShare{ - Denom: "invalid denom", - Amount: sdk.MustNewDecFromStr("101"), - }, - }) - message, broken = suite.runInvariant("vault-records", keeper.VaultRecordsInvariant) - suite.Equal("earn: validate vault records broken invariant\nvault record invalid\n", message) - suite.Equal(true, broken) -} - -func (suite *invariantTestSuite) TestShareRecordsInvariant() { - message, broken := suite.runInvariant("share-records", keeper.ShareRecordsInvariant) - suite.Equal("earn: validate share records broken invariant\nshare record invalid\n", message) - suite.Equal(false, broken) - - suite.SetupValidState() - message, broken = suite.runInvariant("share-records", keeper.ShareRecordsInvariant) - suite.Equal("earn: validate share records broken invariant\nshare record invalid\n", message) - suite.Equal(false, broken) - - // broken with invalid share record - suite.Keeper.SetVaultShareRecord(suite.Ctx, types.NewVaultShareRecord( - suite.addrs[0], - // Directly create vaultshares instead of NewVaultShares() to avoid sanitization - types.VaultShares{ - types.NewVaultShare("ukava", sdk.MustNewDecFromStr("50")), - types.NewVaultShare("ukava", sdk.MustNewDecFromStr("105.123")), - }, - )) - message, broken = suite.runInvariant("share-records", keeper.ShareRecordsInvariant) - suite.Equal("earn: validate share records broken invariant\nshare record invalid\n", message) - suite.Equal(true, broken) -} - -func (suite *invariantTestSuite) TestVaultSharesInvariant() { - message, broken := suite.runInvariant("vault-shares", keeper.VaultSharesInvariant) - suite.Equal("earn: vault shares broken invariant\nvault shares do not match depositor shares\n", message) - suite.Equal(false, broken) - - suite.SetupValidState() - message, broken = suite.runInvariant("vault-shares", keeper.VaultSharesInvariant) - suite.Equal("earn: vault shares broken invariant\nvault shares do not match depositor shares\n", message) - suite.Equal(false, broken) - - // broken when total shares are greater than depositor shares - suite.Keeper.SetVaultRecord(suite.Ctx, types.NewVaultRecord( - "usdx", - sdk.MustNewDecFromStr("101"), - )) - message, broken = suite.runInvariant("vault-shares", keeper.VaultSharesInvariant) - suite.Equal("earn: vault shares broken invariant\nvault shares do not match depositor shares\n", message) - suite.Equal(true, broken) - - // broken when total shares are less than the depositor shares - suite.Keeper.SetVaultRecord(suite.Ctx, types.NewVaultRecord( - "usdx", - sdk.MustNewDecFromStr("99.999"), - )) - message, broken = suite.runInvariant("vault-shares", keeper.VaultSharesInvariant) - suite.Equal("earn: vault shares broken invariant\nvault shares do not match depositor shares\n", message) - suite.Equal(true, broken) - - // broken when vault record is missing - suite.Keeper.DeleteVaultRecord(suite.Ctx, "usdx") - message, broken = suite.runInvariant("vault-shares", keeper.VaultSharesInvariant) - suite.Equal("earn: vault shares broken invariant\nvault shares do not match depositor shares\n", message) - suite.Equal(true, broken) -} diff --git a/x/earn/keeper/keeper.go b/x/earn/keeper/keeper.go deleted file mode 100644 index b61619c5..00000000 --- a/x/earn/keeper/keeper.go +++ /dev/null @@ -1,70 +0,0 @@ -package keeper - -import ( - "github.com/0glabs/0g-chain/x/earn/types" - "github.com/cosmos/cosmos-sdk/codec" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -// Keeper keeper for the earn module -type Keeper struct { - key storetypes.StoreKey - cdc codec.Codec - paramSubspace paramtypes.Subspace - hooks types.EarnHooks - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - liquidKeeper types.LiquidKeeper - - // Keepers used for strategies - hardKeeper types.HardKeeper - savingsKeeper types.SavingsKeeper - - // Keeper for community pool transfers - distKeeper types.DistributionKeeper -} - -// NewKeeper creates a new keeper -func NewKeeper( - cdc codec.Codec, - key storetypes.StoreKey, - paramstore paramtypes.Subspace, - accountKeeper types.AccountKeeper, - bankKeeper types.BankKeeper, - liquidKeeper types.LiquidKeeper, - hardKeeper types.HardKeeper, - savingsKeeper types.SavingsKeeper, - distKeeper types.DistributionKeeper, -) Keeper { - if !paramstore.HasKeyTable() { - paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) - } - - return Keeper{ - key: key, - cdc: cdc, - paramSubspace: paramstore, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - liquidKeeper: liquidKeeper, - hardKeeper: hardKeeper, - savingsKeeper: savingsKeeper, - distKeeper: distKeeper, - } -} - -// SetHooks adds hooks to the keeper. -func (k *Keeper) SetHooks(sh types.EarnHooks) *Keeper { - if k.hooks != nil { - panic("cannot set earn hooks twice") - } - k.hooks = sh - return k -} - -// ClearHooks clears the hooks on the keeper -func (k *Keeper) ClearHooks() { - k.hooks = nil -} diff --git a/x/earn/keeper/msg_server.go b/x/earn/keeper/msg_server.go deleted file mode 100644 index a9e4d1da..00000000 --- a/x/earn/keeper/msg_server.go +++ /dev/null @@ -1,70 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/earn/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the earn MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -// Deposit handles MsgDeposit messages -func (m msgServer) Deposit(goCtx context.Context, msg *types.MsgDeposit) (*types.MsgDepositResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - - if err := m.keeper.Deposit(ctx, depositor, msg.Amount, msg.Strategy); err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.String()), - ), - ) - - return &types.MsgDepositResponse{}, nil -} - -// Withdraw handles MsgWithdraw messages -func (m msgServer) Withdraw(goCtx context.Context, msg *types.MsgWithdraw) (*types.MsgWithdrawResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - from, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - return nil, err - } - - _, err = m.keeper.Withdraw(ctx, from, msg.Amount, msg.Strategy) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, from.String()), - ), - ) - - return &types.MsgWithdrawResponse{}, nil -} diff --git a/x/earn/keeper/msg_server_test.go b/x/earn/keeper/msg_server_test.go deleted file mode 100644 index 2a7f4a1f..00000000 --- a/x/earn/keeper/msg_server_test.go +++ /dev/null @@ -1,139 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - - "github.com/0glabs/0g-chain/x/earn/keeper" - "github.com/0glabs/0g-chain/x/earn/testutil" - "github.com/0glabs/0g-chain/x/earn/types" - "github.com/cometbft/cometbft/crypto" - "github.com/stretchr/testify/suite" -) - -var moduleAccAddress = sdk.AccAddress(crypto.AddressHash([]byte(types.ModuleAccountName))) - -type msgServerTestSuite struct { - testutil.Suite - - msgServer types.MsgServer -} - -func (suite *msgServerTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) - - suite.msgServer = keeper.NewMsgServerImpl(suite.Keeper) -} - -func TestMsgServerTestSuite(t *testing.T) { - suite.Run(t, new(msgServerTestSuite)) -} - -func (suite *msgServerTestSuite) TestDeposit() { - vaultDenom := "usdx" - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - msg := types.NewMsgDeposit(acc.GetAddress().String(), depositAmount, types.STRATEGY_TYPE_HARD) - _, err := suite.msgServer.Deposit(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance.Sub(depositAmount)), - ) - - // Bank: Send deposit Account -> Module account - suite.EventsContains( - suite.GetEvents(), - sdk.NewEvent( - banktypes.EventTypeTransfer, - sdk.NewAttribute(banktypes.AttributeKeyRecipient, moduleAccAddress.String()), - sdk.NewAttribute(banktypes.AttributeKeySender, acc.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, depositAmount.String()), - ), - ) - - // Keeper Deposit() - suite.EventsContains( - suite.GetEvents(), - sdk.NewEvent( - types.EventTypeVaultDeposit, - sdk.NewAttribute(types.AttributeKeyVaultDenom, depositAmount.Denom), - sdk.NewAttribute(types.AttributeKeyDepositor, acc.GetAddress().String()), - // Shares 1:1 to amount - sdk.NewAttribute(types.AttributeKeyShares, sdk.NewDecFromInt(depositAmount.Amount).String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, depositAmount.Amount.String()), - ), - ) - - // Msg server module - suite.EventsContains( - suite.GetEvents(), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, acc.GetAddress().String()), - ), - ) -} - -func (suite *msgServerTestSuite) TestWithdraw() { - vaultDenom := "usdx" - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - msgDeposit := types.NewMsgDeposit(acc.GetAddress().String(), depositAmount, types.STRATEGY_TYPE_HARD) - _, err := suite.msgServer.Deposit(sdk.WrapSDKContext(suite.Ctx), msgDeposit) - suite.Require().NoError(err) - - // Withdraw all - msgWithdraw := types.NewMsgWithdraw(acc.GetAddress().String(), depositAmount, types.STRATEGY_TYPE_HARD) - _, err = suite.msgServer.Withdraw(sdk.WrapSDKContext(suite.Ctx), msgWithdraw) - suite.Require().NoError(err) - - // Bank: Send deposit Account -> Module account - suite.EventsContains( - suite.GetEvents(), - sdk.NewEvent( - banktypes.EventTypeTransfer, - // Direction opposite from Deposit() - sdk.NewAttribute(banktypes.AttributeKeyRecipient, acc.GetAddress().String()), - sdk.NewAttribute(banktypes.AttributeKeySender, moduleAccAddress.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, depositAmount.String()), - ), - ) - - // Keeper Withdraw() - suite.EventsContains( - suite.GetEvents(), - sdk.NewEvent( - types.EventTypeVaultWithdraw, - sdk.NewAttribute(types.AttributeKeyVaultDenom, depositAmount.Denom), - sdk.NewAttribute(types.AttributeKeyOwner, acc.GetAddress().String()), - sdk.NewAttribute(types.AttributeKeyShares, sdk.NewDecFromInt(depositAmount.Amount).String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, depositAmount.Amount.String()), - ), - ) - - // Msg server module - suite.EventsContains( - suite.GetEvents(), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, acc.GetAddress().String()), - ), - ) -} diff --git a/x/earn/keeper/params.go b/x/earn/keeper/params.go deleted file mode 100644 index 6223b9d4..00000000 --- a/x/earn/keeper/params.go +++ /dev/null @@ -1,62 +0,0 @@ -package keeper - -import ( - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/earn/types" -) - -const ( - bkavaDenom = "bkava" - bkavaPrefix = bkavaDenom + "-" -) - -// GetParams returns the params from the store -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - var p types.Params - k.paramSubspace.GetParamSet(ctx, &p) - - return p -} - -// SetParams sets params on the store -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSubspace.SetParamSet(ctx, ¶ms) -} - -// GetAllowedVaults returns the list of allowed vaults from the module params. -func (k Keeper) GetAllowedVaults(ctx sdk.Context) types.AllowedVaults { - return k.GetParams(ctx).AllowedVaults -} - -// getAllowedVaultRaw returns a single vault from the module params specified -// by the denom. -func (k Keeper) getAllowedVaultRaw( - ctx sdk.Context, - vaultDenom string, -) (types.AllowedVault, bool) { - for _, allowedVault := range k.GetAllowedVaults(ctx) { - if allowedVault.Denom == vaultDenom { - return allowedVault, true - } - } - - return types.AllowedVault{}, false -} - -// GetAllowedVault returns the AllowedVault that corresponds to the -// given denom. If the denom starts with "bkava-" where it will return the -// "bkava" AllowedVault. Otherwise, it will return the exact match for the -// corresponding AllowedVault denom. -func (k *Keeper) GetAllowedVault( - ctx sdk.Context, - vaultDenom string, -) (types.AllowedVault, bool) { - if strings.HasPrefix(vaultDenom, bkavaPrefix) { - return k.getAllowedVaultRaw(ctx, bkavaDenom) - } - - return k.getAllowedVaultRaw(ctx, vaultDenom) -} diff --git a/x/earn/keeper/proposal_handler.go b/x/earn/keeper/proposal_handler.go deleted file mode 100644 index 82986ae5..00000000 --- a/x/earn/keeper/proposal_handler.go +++ /dev/null @@ -1,49 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/earn/types" - kavadisttypes "github.com/0glabs/0g-chain/x/kavadist/types" -) - -// HandleCommunityPoolDepositProposal is a handler for executing a passed community pool deposit proposal -func HandleCommunityPoolDepositProposal(ctx sdk.Context, k Keeper, p *types.CommunityPoolDepositProposal) error { - fundAcc := k.accountKeeper.GetModuleAccount(ctx, kavadisttypes.FundModuleAccount) - if err := k.distKeeper.DistributeFromFeePool(ctx, sdk.NewCoins(p.Amount), fundAcc.GetAddress()); err != nil { - return err - } - - err := k.DepositFromModuleAccount(ctx, kavadisttypes.FundModuleAccount, p.Amount, types.STRATEGY_TYPE_SAVINGS) - if err != nil { - return err - } - - return nil - -} - -// HandleCommunityPoolWithdrawProposal is a handler for executing a passed community pool withdraw proposal. -func HandleCommunityPoolWithdrawProposal(ctx sdk.Context, k Keeper, p *types.CommunityPoolWithdrawProposal) error { - // Withdraw to fund module account - withdrawAmount, err := k.WithdrawFromModuleAccount(ctx, kavadisttypes.FundModuleAccount, p.Amount, types.STRATEGY_TYPE_SAVINGS) - if err != nil { - return err - } - - // Move funds to the community pool manually - err = k.bankKeeper.SendCoinsFromModuleToModule( - ctx, - kavadisttypes.FundModuleAccount, - k.distKeeper.GetDistributionAccount(ctx).GetName(), - sdk.NewCoins(withdrawAmount), - ) - if err != nil { - return err - } - feePool := k.distKeeper.GetFeePool(ctx) - newCommunityPool := feePool.CommunityPool.Add(sdk.NewDecCoinFromCoin(withdrawAmount)) - feePool.CommunityPool = newCommunityPool - k.distKeeper.SetFeePool(ctx, feePool) - return nil -} diff --git a/x/earn/keeper/proposal_handler_test.go b/x/earn/keeper/proposal_handler_test.go deleted file mode 100644 index f213e0dc..00000000 --- a/x/earn/keeper/proposal_handler_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - "github.com/0glabs/0g-chain/x/earn/keeper" - "github.com/0glabs/0g-chain/x/earn/testutil" - "github.com/0glabs/0g-chain/x/earn/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" -) - -type proposalTestSuite struct { - testutil.Suite -} - -func (suite *proposalTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) -} - -func TestProposalTestSuite(t *testing.T) { - suite.Run(t, new(proposalTestSuite)) -} - -func (suite *proposalTestSuite) TestCommunityDepositProposal() { - distKeeper := suite.App.GetDistrKeeper() - ctx := suite.Ctx - macc := distKeeper.GetDistributionAccount(ctx) - fundAmount := sdk.NewCoins(sdk.NewInt64Coin("ukava", 100000000)) - depositAmount := sdk.NewCoin("ukava", sdkmath.NewInt(10000000)) - suite.Require().NoError(suite.App.FundModuleAccount(ctx, macc.GetName(), fundAmount)) - feePool := distKeeper.GetFeePool(ctx) - feePool.CommunityPool = sdk.NewDecCoinsFromCoins(fundAmount...) - distKeeper.SetFeePool(ctx, feePool) - suite.CreateVault("ukava", types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - prop := types.NewCommunityPoolDepositProposal("test title", - "desc", depositAmount) - err := keeper.HandleCommunityPoolDepositProposal(ctx, suite.Keeper, prop) - suite.Require().NoError(err) - - balance := suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) - suite.Require().Equal(fundAmount.Sub(depositAmount), balance) - feePool = distKeeper.GetFeePool(ctx) - communityPoolBalance, change := feePool.CommunityPool.TruncateDecimal() - suite.Require().Equal(fundAmount.Sub(depositAmount), communityPoolBalance) - suite.Require().True(change.Empty()) -} - -func (suite *proposalTestSuite) TestCommunityWithdrawProposal() { - distKeeper := suite.App.GetDistrKeeper() - ctx := suite.Ctx - macc := distKeeper.GetDistributionAccount(ctx) - fundAmount := sdk.NewCoins(sdk.NewInt64Coin("ukava", 100000000)) - depositAmount := sdk.NewCoin("ukava", sdkmath.NewInt(10000000)) - suite.Require().NoError(suite.App.FundModuleAccount(ctx, macc.GetName(), fundAmount)) - feePool := distKeeper.GetFeePool(ctx) - feePool.CommunityPool = sdk.NewDecCoinsFromCoins(fundAmount...) - distKeeper.SetFeePool(ctx, feePool) - // TODO update to STRATEGY_TYPE_SAVINGS once implemented - suite.CreateVault("ukava", types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - deposit := types.NewCommunityPoolDepositProposal("test title", - "desc", depositAmount) - err := keeper.HandleCommunityPoolDepositProposal(ctx, suite.Keeper, deposit) - suite.Require().NoError(err) - - balance := suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) - suite.Require().Equal(fundAmount.Sub(depositAmount), balance) - - withdraw := types.NewCommunityPoolWithdrawProposal("test title", - "desc", depositAmount) - err = keeper.HandleCommunityPoolWithdrawProposal(ctx, suite.Keeper, withdraw) - suite.Require().NoError(err) - balance = suite.BankKeeper.GetAllBalances(ctx, macc.GetAddress()) - suite.Require().Equal(fundAmount, balance) - feePool = distKeeper.GetFeePool(ctx) - communityPoolBalance, change := feePool.CommunityPool.TruncateDecimal() - suite.Require().Equal(fundAmount, communityPoolBalance) - suite.Require().True(change.Empty()) -} diff --git a/x/earn/keeper/strategy.go b/x/earn/keeper/strategy.go deleted file mode 100644 index 96d26a71..00000000 --- a/x/earn/keeper/strategy.go +++ /dev/null @@ -1,40 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/0glabs/0g-chain/x/earn/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// Strategy is the interface that must be implemented by a strategy. -type Strategy interface { - // GetStrategyType returns the strategy type - GetStrategyType() types.StrategyType - - // GetEstimatedTotalAssets returns the estimated total assets of the - // strategy with the specified denom. This is the value if the strategy were - // to liquidate all assets. - // - // **Note:** This may not reflect the true value as it may become outdated - // from market changes. - GetEstimatedTotalAssets(ctx sdk.Context, denom string) (sdk.Coin, error) - - // Deposit the specified amount of coins into this strategy. - Deposit(ctx sdk.Context, amount sdk.Coin) error - - // Withdraw the specified amount of coins from this strategy. - Withdraw(ctx sdk.Context, amount sdk.Coin) error -} - -// GetStrategy returns the strategy for the given strategy type. -func (k *Keeper) GetStrategy(strategyType types.StrategyType) (Strategy, error) { - switch strategyType { - case types.STRATEGY_TYPE_HARD: - return (*HardStrategy)(k), nil - case types.STRATEGY_TYPE_SAVINGS: - return (*SavingsStrategy)(k), nil - default: - return nil, fmt.Errorf("unknown strategy type: %s", strategyType) - } -} diff --git a/x/earn/keeper/strategy_hard.go b/x/earn/keeper/strategy_hard.go deleted file mode 100644 index 12759ba4..00000000 --- a/x/earn/keeper/strategy_hard.go +++ /dev/null @@ -1,49 +0,0 @@ -package keeper - -import ( - "github.com/0glabs/0g-chain/x/earn/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// HardStrategy defines the strategy that deposits assets to Hard -type HardStrategy Keeper - -var _ Strategy = (*HardStrategy)(nil) - -// GetStrategyType returns the strategy type -func (s *HardStrategy) GetStrategyType() types.StrategyType { - return types.STRATEGY_TYPE_HARD -} - -// GetEstimatedTotalAssets returns the current value of all assets deposited -// in hard. -func (s *HardStrategy) GetEstimatedTotalAssets(ctx sdk.Context, denom string) (sdk.Coin, error) { - macc := s.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - deposit, found := s.hardKeeper.GetSyncedDeposit(ctx, macc.GetAddress()) - if !found { - // Return 0 if no deposit exists for module account - return sdk.NewCoin(denom, sdk.ZeroInt()), nil - } - - // Only return the deposit for the vault denom. - for _, coin := range deposit.Amount { - if coin.Denom == denom { - return coin, nil - } - } - - // Return 0 if no deposit exists for the vault denom - return sdk.NewCoin(denom, sdk.ZeroInt()), nil -} - -// Deposit deposits the specified amount of coins into hard. -func (s *HardStrategy) Deposit(ctx sdk.Context, amount sdk.Coin) error { - macc := s.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - return s.hardKeeper.Deposit(ctx, macc.GetAddress(), sdk.NewCoins(amount)) -} - -// Withdraw withdraws the specified amount of coins from hard. -func (s *HardStrategy) Withdraw(ctx sdk.Context, amount sdk.Coin) error { - macc := s.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - return s.hardKeeper.Withdraw(ctx, macc.GetAddress(), sdk.NewCoins(amount)) -} diff --git a/x/earn/keeper/strategy_hard_test.go b/x/earn/keeper/strategy_hard_test.go deleted file mode 100644 index 31eca7cb..00000000 --- a/x/earn/keeper/strategy_hard_test.go +++ /dev/null @@ -1,497 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/earn/testutil" - "github.com/0glabs/0g-chain/x/earn/types" - - "github.com/stretchr/testify/suite" -) - -type strategyHardTestSuite struct { - testutil.Suite -} - -func (suite *strategyHardTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) -} - -func TestStrategyLendTestSuite(t *testing.T) { - suite.Run(t, new(strategyHardTestSuite)) -} - -func (suite *strategyHardTestSuite) TestGetStrategyType() { - strategy, err := suite.Keeper.GetStrategy(types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - suite.Equal(types.STRATEGY_TYPE_HARD, strategy.GetStrategyType()) -} - -func (suite *strategyHardTestSuite) TestDeposit_SingleAcc() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - suite.HardDepositAmountEqual(sdk.NewCoins(depositAmount)) - suite.VaultTotalValuesEqual(sdk.NewCoins(depositAmount)) - suite.VaultTotalSharesEqual(types.NewVaultShares( - types.NewVaultShare(depositAmount.Denom, sdk.NewDecFromInt(depositAmount.Amount)), - )) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenom) - suite.Require().NoError(err) - - suite.Equal(depositAmount, totalValue) -} - -func (suite *strategyHardTestSuite) TestDeposit_SingleAcc_MultipleDeposits() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Second deposit - err = suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - expectedVaultBalance := depositAmount.Add(depositAmount) - suite.HardDepositAmountEqual(sdk.NewCoins(expectedVaultBalance)) - suite.VaultTotalValuesEqual(sdk.NewCoins(expectedVaultBalance)) - suite.VaultTotalSharesEqual(types.NewVaultShares( - types.NewVaultShare(expectedVaultBalance.Denom, sdk.NewDecFromInt(expectedVaultBalance.Amount)), - )) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenom) - suite.Require().NoError(err) - - suite.Equal(depositAmount.Add(depositAmount), totalValue) -} - -func (suite *strategyHardTestSuite) TestDeposit_MultipleAcc_MultipleDeposits() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - expectedTotalValue := sdk.NewCoin(vaultDenom, depositAmount.Amount.MulRaw(4)) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - // 2 deposits each account - for i := 0; i < 2; i++ { - // Deposit from acc1 - err := suite.Keeper.Deposit(suite.Ctx, acc1.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Deposit from acc2 - err = suite.Keeper.Deposit(suite.Ctx, acc2.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - } - - suite.HardDepositAmountEqual(sdk.NewCoins(expectedTotalValue)) - suite.VaultTotalValuesEqual(sdk.NewCoins(expectedTotalValue)) - suite.VaultTotalSharesEqual(types.NewVaultShares( - types.NewVaultShare(expectedTotalValue.Denom, sdk.NewDecFromInt(expectedTotalValue.Amount)), - )) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenom) - suite.Require().NoError(err) - - suite.Equal(expectedTotalValue, totalValue) -} - -func (suite *strategyHardTestSuite) TestGetVaultTotalValue_Empty() { - vaultDenom := "usdx" - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenom) - suite.Require().NoError(err) - - suite.Equal(sdk.NewCoin(vaultDenom, sdk.ZeroInt()), totalValue) -} - -func (suite *strategyHardTestSuite) TestGetVaultTotalValue_NoDenomDeposit() { - // 2 Vaults usdx, busd - // 1st vault has deposits - // 2nd vault has no deposits - vaultDenom := "usdx" - vaultDenomBusd := "busd" - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - suite.CreateVault(vaultDenomBusd, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - // Deposit vault1 - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Query vault total, hard deposit exists for account, but amount in busd does not - // Vault2 does not have any value, only returns amount for the correct denom - // if a hard deposit already exists - totalValueBusd, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenomBusd) - suite.Require().NoError(err) - - suite.Equal(sdk.NewCoin(vaultDenomBusd, sdk.ZeroInt()), totalValueBusd) -} - -// ---------------------------------------------------------------------------- -// Withdraw - -func (suite *strategyHardTestSuite) TestWithdraw() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - suite.HardDepositAmountEqual(sdk.NewCoins(depositAmount)) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenom) - suite.Require().NoError(err) - suite.Equal(depositAmount, totalValue) - - // Withdraw - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - suite.HardDepositAmountEqual(sdk.NewCoins()) - suite.VaultTotalValuesEqual(sdk.NewCoins()) - suite.VaultTotalSharesEqual(types.NewVaultShares()) - - totalValue, err = suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenom) - suite.Require().NoError(err) - suite.Equal(sdk.NewInt64Coin(vaultDenom, 0), totalValue) - - // Withdraw again - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrVaultRecordNotFound, "vault should be deleted when no more supply") -} - -func (suite *strategyHardTestSuite) TestWithdraw_OnlyWithdrawOwnSupply() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Deposits from 2 accounts - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - err := suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Withdraw - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Withdraw again - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs( - err, - types.ErrVaultShareRecordNotFound, - "should only be able to withdraw the account's own supply", - ) -} - -func (suite *strategyHardTestSuite) TestWithdraw_WithAccumulatedHard() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Deposits accounts - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - - err := suite.Keeper.Deposit(suite.Ctx, acc, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Deposit from acc2 so the vault doesn't get deleted when withdrawing - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Direct hard deposit from module account to increase vault value - err = suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 20))) - suite.Require().NoError(err) - - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.HardKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 20))) - suite.Require().NoError(err) - - // Query account value - accValue, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc) - suite.Require().NoError(err) - suite.Equal(depositAmount.AddAmount(sdkmath.NewInt(10)), accValue) - - // Withdraw 100, 10 remaining - _, err = suite.Keeper.Withdraw(suite.Ctx, acc, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Withdraw 100 again -- too much - _, err = suite.Keeper.Withdraw(suite.Ctx, acc, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs( - err, - types.ErrInsufficientValue, - "cannot withdraw more than account value", - ) - - // Half of remaining 10, 5 remaining - _, err = suite.Keeper.Withdraw(suite.Ctx, acc, sdk.NewCoin(vaultDenom, sdkmath.NewInt(5)), types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Withdraw all - _, err = suite.Keeper.Withdraw(suite.Ctx, acc, sdk.NewCoin(vaultDenom, sdkmath.NewInt(5)), types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - accValue, err = suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc) - suite.Require().Errorf( - err, - "account should be deleted when all shares withdrawn but has %s value still", - accValue, - ) - suite.Require().Equal("account vault share record for usdx not found", err.Error()) -} - -func (suite *strategyHardTestSuite) TestAccountShares() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 1000))) - suite.Require().NoError(err) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Deposit from account1 - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - - // 1. acc1 deposit 100 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - acc1Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100), acc1Shares.AmountOf(vaultDenom), "initial deposit 1:1 shares") - - // 2. Direct hard deposit from module account to increase vault value - // Total value: 100 -> 110 - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.HardKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 10))) - suite.Require().NoError(err) - - // 2. acc2 deposit 100 - // share price is 10% more expensive now - // hard 110 -> 210 - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // 100 * 100 / 210 = 47.619047619 shares - // 2.1 price * 47.619047619 = 99.9999999999 - acc2Value, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc2) - suite.Require().NoError(err) - suite.Equal( - sdkmath.NewInt(99), - acc2Value.Amount, - "value 1 less than deposit amount with different share price, decimals truncated", - ) - - acc2Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc2) - suite.Require().True(found) - // 100 * 100 / 110 = 190.909090909090909091 - // QuoInt64() truncates - expectedAcc2Shares := sdk.NewDec(100).MulInt64(100).QuoInt64(110) - suite.Equal(expectedAcc2Shares, acc2Shares.AmountOf(vaultDenom)) - - vaultTotalShares, found := suite.Keeper.GetVaultTotalShares(suite.Ctx, vaultDenom) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100).Add(expectedAcc2Shares), vaultTotalShares.Amount) - - // Hard deposit again from module account to triple original value - // 210 -> 300 - err = suite.HardKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 90))) - suite.Require().NoError(err) - - // Deposit again from acc1 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - acc1Shares, found = suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - // totalShares = 100 + 90 = 190 - // totalValue = 100 + 10 + 100 + 90 = 300 - // sharesIssued = assetAmount * (shareCount / totalTokens) - // sharedIssued = 100 * 190 / 300 = 63.3 = 63 - // total shares = 100 + 63 = 163 - suite.Equal( - sdk.NewDec(100).Add(sdk.NewDec(100).Mul(vaultTotalShares.Amount).Quo(sdk.NewDec(300))), - acc1Shares.AmountOf(vaultDenom), - "shares should consist of 100 of 1x share price and 63 of 3x share price", - ) -} - -func (suite *strategyHardTestSuite) TestWithdraw_AccumulatedAmount() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 1000))) - suite.Require().NoError(err) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Deposit from account1 - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - - // 1. acc1 deposit 100 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // acc2 deposit 100, just to make sure other deposits do not affect acc1 - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - acc1Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100), acc1Shares.AmountOf(vaultDenom), "initial deposit 1:1 shares") - - // 2. Direct hard deposit from module account to increase vault value - // Total value: 200 -> 220, 110 each account - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.HardKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 20))) - suite.Require().NoError(err) - - // 3. Withdraw all from acc1 - including accumulated amount - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, depositAmount.AddAmount(sdkmath.NewInt(10)), types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - _, found = suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().False(found, "should have withdrawn entire shares") -} - -func (suite *strategyHardTestSuite) TestWithdraw_AccumulatedTruncated() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 1000))) - suite.Require().NoError(err) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Deposit from account1 - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - - // 1. acc1 deposit 100 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // acc2 deposit 100, just to make sure other deposits do not affect acc1 - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - acc1Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100), acc1Shares.AmountOf(vaultDenom), "initial deposit 1:1 shares") - - // 2. Direct hard deposit from module account to increase vault value - // Total value: 200 -> 211, 105.5 each account - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.HardKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 11))) - suite.Require().NoError(err) - - accBal, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc1) - suite.Require().NoError(err) - suite.Equal(depositAmount.AddAmount(sdkmath.NewInt(5)), accBal, "acc1 should have 105 usdx") - - // 3. Withdraw all from acc1 - including accumulated amount - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, depositAmount.AddAmount(sdkmath.NewInt(5)), types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - acc1Shares, found = suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().Falsef(found, "should have withdrawn entire shares but has %s", acc1Shares) - - _, err = suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc1) - suite.Require().Error(err) -} - -func (suite *strategyHardTestSuite) TestWithdraw_ExpensiveShares() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 2000))) - suite.Require().NoError(err) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Deposit from account1 - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - - // 1. acc1 deposit 100 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - acc1Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100), acc1Shares.AmountOf(vaultDenom), "initial deposit 1:1 shares") - - // 2. Direct hard deposit from module account to increase vault value - // Total value: 100 -> 2000, shares now 10usdx each - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.HardKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 1900))) - suite.Require().NoError(err) - - accBal, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc1) - suite.Require().NoError(err) - suite.Equal(sdkmath.NewInt(2000), accBal.Amount, "acc1 should have 2000 usdx") - - // 3. Withdraw all from acc1 - including accumulated amount - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, sdk.NewInt64Coin(vaultDenom, 2000), types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - acc1Shares, found = suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().Falsef(found, "should have withdrawn entire shares but has %s", acc1Shares) - - _, err = suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc1) - suite.Require().Error(err) -} diff --git a/x/earn/keeper/strategy_savings.go b/x/earn/keeper/strategy_savings.go deleted file mode 100644 index aa15c0d3..00000000 --- a/x/earn/keeper/strategy_savings.go +++ /dev/null @@ -1,49 +0,0 @@ -package keeper - -import ( - "github.com/0glabs/0g-chain/x/earn/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// SavingsStrategy defines the strategy that deposits assets to x/savings -type SavingsStrategy Keeper - -var _ Strategy = (*SavingsStrategy)(nil) - -// GetStrategyType returns the strategy type -func (s *SavingsStrategy) GetStrategyType() types.StrategyType { - return types.STRATEGY_TYPE_SAVINGS -} - -// GetEstimatedTotalAssets returns the current value of all assets deposited -// in savings. -func (s *SavingsStrategy) GetEstimatedTotalAssets(ctx sdk.Context, denom string) (sdk.Coin, error) { - macc := s.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - deposit, found := s.savingsKeeper.GetDeposit(ctx, macc.GetAddress()) - if !found { - // Return 0 if no deposit exists for module account - return sdk.NewCoin(denom, sdk.ZeroInt()), nil - } - - // Only return the deposit for the vault denom. - for _, coin := range deposit.Amount { - if coin.Denom == denom { - return coin, nil - } - } - - // Return 0 if no deposit exists for the vault denom - return sdk.NewCoin(denom, sdk.ZeroInt()), nil -} - -// Deposit deposits the specified amount of coins into savings. -func (s *SavingsStrategy) Deposit(ctx sdk.Context, amount sdk.Coin) error { - macc := s.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - return s.savingsKeeper.Deposit(ctx, macc.GetAddress(), sdk.NewCoins(amount)) -} - -// Withdraw withdraws the specified amount of coins from savings. -func (s *SavingsStrategy) Withdraw(ctx sdk.Context, amount sdk.Coin) error { - macc := s.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - return s.savingsKeeper.Withdraw(ctx, macc.GetAddress(), sdk.NewCoins(amount)) -} diff --git a/x/earn/keeper/strategy_savings_test.go b/x/earn/keeper/strategy_savings_test.go deleted file mode 100644 index 827b90f2..00000000 --- a/x/earn/keeper/strategy_savings_test.go +++ /dev/null @@ -1,487 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/earn/testutil" - "github.com/0glabs/0g-chain/x/earn/types" - - "github.com/stretchr/testify/suite" -) - -const savingsVaultDenom = "ukava" - -type strategySavingsTestSuite struct { - testutil.Suite -} - -func (suite *strategySavingsTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) -} - -func TestStrategySavingsTestSuite(t *testing.T) { - suite.Run(t, new(strategySavingsTestSuite)) -} - -func (suite *strategySavingsTestSuite) TestGetStrategyType() { - strategy, err := suite.Keeper.GetStrategy(types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - suite.Equal(types.STRATEGY_TYPE_SAVINGS, strategy.GetStrategyType()) -} - -func (suite *strategySavingsTestSuite) TestDeposit_SingleAcc() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - suite.SavingsDepositAmountEqual(sdk.NewCoins(depositAmount)) - suite.VaultTotalValuesEqual(sdk.NewCoins(depositAmount)) - suite.VaultTotalSharesEqual(types.NewVaultShares( - types.NewVaultShare(depositAmount.Denom, sdk.NewDecFromInt(depositAmount.Amount)), - )) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, savingsVaultDenom) - suite.Require().NoError(err) - - suite.Equal(depositAmount, totalValue) -} - -func (suite *strategySavingsTestSuite) TestDeposit_SingleAcc_MultipleDeposits() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Second deposit - err = suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - expectedVaultBalance := depositAmount.Add(depositAmount) - suite.SavingsDepositAmountEqual(sdk.NewCoins(expectedVaultBalance)) - suite.VaultTotalValuesEqual(sdk.NewCoins(expectedVaultBalance)) - suite.VaultTotalSharesEqual(types.NewVaultShares( - types.NewVaultShare(expectedVaultBalance.Denom, sdk.NewDecFromInt(expectedVaultBalance.Amount)), - )) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, savingsVaultDenom) - suite.Require().NoError(err) - - suite.Equal(depositAmount.Add(depositAmount), totalValue) -} - -func (suite *strategySavingsTestSuite) TestDeposit_MultipleAcc_MultipleDeposits() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - - expectedTotalValue := sdk.NewCoin(savingsVaultDenom, depositAmount.Amount.MulRaw(4)) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - // 2 deposits each account - for i := 0; i < 2; i++ { - // Deposit from acc1 - err := suite.Keeper.Deposit(suite.Ctx, acc1.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Deposit from acc2 - err = suite.Keeper.Deposit(suite.Ctx, acc2.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - } - - suite.SavingsDepositAmountEqual(sdk.NewCoins(expectedTotalValue)) - suite.VaultTotalValuesEqual(sdk.NewCoins(expectedTotalValue)) - suite.VaultTotalSharesEqual(types.NewVaultShares( - types.NewVaultShare(expectedTotalValue.Denom, sdk.NewDecFromInt(expectedTotalValue.Amount)), - )) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, savingsVaultDenom) - suite.Require().NoError(err) - - suite.Equal(expectedTotalValue, totalValue) -} - -func (suite *strategySavingsTestSuite) TestGetVaultTotalValue_Empty() { - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, savingsVaultDenom) - suite.Require().NoError(err) - - suite.Equal(sdk.NewCoin(savingsVaultDenom, sdk.ZeroInt()), totalValue) -} - -func (suite *strategySavingsTestSuite) TestGetVaultTotalValue_NoDenomDeposit() { - // 2 Vaults usdx, busd - // 1st vault has deposits - // 2nd vault has no deposits - - vaultDenomBusd := "busd" - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - suite.CreateVault(vaultDenomBusd, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - // Deposit vault1 - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Query vault total, savings deposit exists for account, but amount in busd does not - // Vault2 does not have any value, only returns amount for the correct denom - // if a savings deposit already exists - totalValueBusd, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenomBusd) - suite.Require().NoError(err) - - suite.Equal(sdk.NewCoin(vaultDenomBusd, sdk.ZeroInt()), totalValueBusd) -} - -// ---------------------------------------------------------------------------- -// Withdraw - -func (suite *strategySavingsTestSuite) TestWithdraw() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - suite.SavingsDepositAmountEqual(sdk.NewCoins(depositAmount)) - - // Query vault total - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, savingsVaultDenom) - suite.Require().NoError(err) - suite.Equal(depositAmount, totalValue) - - // Withdraw - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - suite.SavingsDepositAmountEqual(sdk.NewCoins()) - suite.VaultTotalValuesEqual(sdk.NewCoins()) - suite.VaultTotalSharesEqual(types.NewVaultShares()) - - totalValue, err = suite.Keeper.GetVaultTotalValue(suite.Ctx, savingsVaultDenom) - suite.Require().NoError(err) - suite.Equal(sdk.NewInt64Coin(savingsVaultDenom, 0), totalValue) - - // Withdraw again - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrVaultRecordNotFound, "vault should be deleted when no more supply") -} - -func (suite *strategySavingsTestSuite) TestWithdraw_OnlyWithdrawOwnSupply() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - // Deposits from 2 accounts - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - err := suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Withdraw - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Withdraw again - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().Error(err) - suite.Require().ErrorIs( - err, - types.ErrVaultShareRecordNotFound, - "should only be able to withdraw the account's own supply", - ) -} - -func (suite *strategySavingsTestSuite) TestWithdraw_WithAccumulatedSavings() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - // Deposits accounts - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - - err := suite.Keeper.Deposit(suite.Ctx, acc, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Deposit from acc2 so the vault doesn't get deleted when withdrawing - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Direct savings deposit from module account to increase vault value - err = suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 20))) - suite.Require().NoError(err) - - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.SavingsKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 20))) - suite.Require().NoError(err) - - // Query account value - accValue, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, savingsVaultDenom, acc) - suite.Require().NoError(err) - suite.Equal(depositAmount.AddAmount(sdkmath.NewInt(10)), accValue) - - // Withdraw 100, 10 remaining - _, err = suite.Keeper.Withdraw(suite.Ctx, acc, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Withdraw 100 again -- too much - _, err = suite.Keeper.Withdraw(suite.Ctx, acc, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().Error(err) - suite.Require().ErrorIs( - err, - types.ErrInsufficientValue, - "cannot withdraw more than account value", - ) - - // Half of remaining 10, 5 remaining - _, err = suite.Keeper.Withdraw(suite.Ctx, acc, sdk.NewCoin(savingsVaultDenom, sdkmath.NewInt(5)), types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // Withdraw all - _, err = suite.Keeper.Withdraw(suite.Ctx, acc, sdk.NewCoin(savingsVaultDenom, sdkmath.NewInt(5)), types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - accValue, err = suite.Keeper.GetVaultAccountValue(suite.Ctx, savingsVaultDenom, acc) - suite.Require().Errorf( - err, - "account should be deleted when all shares withdrawn but has %s value still", - accValue, - ) - suite.Require().Equal("account vault share record for ukava not found", err.Error()) -} - -func (suite *strategySavingsTestSuite) TestAccountShares() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 1000))) - suite.Require().NoError(err) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - // Deposit from account1 - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - - // 1. acc1 deposit 100 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - acc1Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100), acc1Shares.AmountOf(savingsVaultDenom), "initial deposit 1:1 shares") - - // 2. Direct savings deposit from module account to increase vault value - // Total value: 100 -> 110 - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.SavingsKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 10))) - suite.Require().NoError(err) - - // 2. acc2 deposit 100 - // share price is 10% more expensive now - // savings 110 -> 210 - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // 100 * 100 / 210 = 47.619047619 shares - // 2.1 price * 47.619047619 = 99.9999999999 - acc2Value, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, savingsVaultDenom, acc2) - suite.Require().NoError(err) - suite.Equal( - sdkmath.NewInt(99), - acc2Value.Amount, - "value 1 less than deposit amount with different share price, decimals truncated", - ) - - acc2Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc2) - suite.Require().True(found) - // 100 * 100 / 110 = 90.909090909090909091 - // QuoInt64() truncates - expectedAcc2Shares := sdk.NewDec(100).MulInt64(100).QuoInt64(110) - suite.Equal(expectedAcc2Shares, acc2Shares.AmountOf(savingsVaultDenom)) - - vaultTotalShares, found := suite.Keeper.GetVaultTotalShares(suite.Ctx, savingsVaultDenom) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100).Add(expectedAcc2Shares), vaultTotalShares.Amount) - - // Savings deposit again from module account to triple original value - // 210 -> 300 - err = suite.SavingsKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 90))) - suite.Require().NoError(err) - - // Deposit again from acc1 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - acc1Shares, found = suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - // totalShares = 100 + 90 = 190 - // totalValue = 100 + 10 + 100 + 90 = 300 - // sharesIssued = assetAmount * (shareCount / totalTokens) - // sharedIssued = 100 * 190 / 300 = 63.3 = 63 - // total shares = 100 + 63 = 163 - suite.Equal( - sdk.NewDec(100).Add(sdk.NewDec(100).Mul(vaultTotalShares.Amount).Quo(sdk.NewDec(300))), - acc1Shares.AmountOf(savingsVaultDenom), - "shares should consist of 100 of 1x share price and 63 of 3x share price", - ) -} - -func (suite *strategySavingsTestSuite) TestWithdraw_AccumulatedAmount() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 1000))) - suite.Require().NoError(err) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - // Deposit from account1 - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - - // 1. acc1 deposit 100 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // acc2 deposit 100, just to make sure other deposits do not affect acc1 - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - acc1Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100), acc1Shares.AmountOf(savingsVaultDenom), "initial deposit 1:1 shares") - - // 2. Direct savings deposit from module account to increase vault value - // Total value: 200 -> 220, 110 each account - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.SavingsKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 20))) - suite.Require().NoError(err) - - // 3. Withdraw all from acc1 - including accumulated amount - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, depositAmount.AddAmount(sdkmath.NewInt(10)), types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - _, found = suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().False(found, "should have withdrawn entire shares") -} - -func (suite *strategySavingsTestSuite) TestWithdraw_AccumulatedTruncated() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 1000))) - suite.Require().NoError(err) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - // Deposit from account1 - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1).GetAddress() - - // 1. acc1 deposit 100 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // acc2 deposit 100, just to make sure other deposits do not affect acc1 - err = suite.Keeper.Deposit(suite.Ctx, acc2, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - acc1Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100), acc1Shares.AmountOf(savingsVaultDenom), "initial deposit 1:1 shares") - - // 2. Direct savings deposit from module account to increase vault value - // Total value: 200 -> 211, 105.5 each account - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.SavingsKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 11))) - suite.Require().NoError(err) - - accBal, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, savingsVaultDenom, acc1) - suite.Require().NoError(err) - suite.Equal(depositAmount.AddAmount(sdkmath.NewInt(5)), accBal, "acc1 should have 105 usdx") - - // 3. Withdraw all from acc1 - including accumulated amount - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, depositAmount.AddAmount(sdkmath.NewInt(5)), types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - acc1Shares, found = suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().Falsef(found, "should have withdrawn entire shares but has %s", acc1Shares) - - _, err = suite.Keeper.GetVaultAccountValue(suite.Ctx, savingsVaultDenom, acc1) - suite.Require().Error(err) -} - -func (suite *strategySavingsTestSuite) TestWithdraw_ExpensiveShares() { - startBalance := sdk.NewInt64Coin(savingsVaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(savingsVaultDenom, 100) - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 2000))) - suite.Require().NoError(err) - - suite.CreateVault(savingsVaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, false, nil) - - // Deposit from account1 - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0).GetAddress() - - // 1. acc1 deposit 100 - err = suite.Keeper.Deposit(suite.Ctx, acc1, depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - acc1Shares, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().True(found) - suite.Equal(sdk.NewDec(100), acc1Shares.AmountOf(savingsVaultDenom), "initial deposit 1:1 shares") - - // 2. Direct savings deposit from module account to increase vault value - // Total value: 100 -> 2000, shares now 10usdx each - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - err = suite.SavingsKeeper.Deposit(suite.Ctx, macc.GetAddress(), sdk.NewCoins(sdk.NewInt64Coin(savingsVaultDenom, 1900))) - suite.Require().NoError(err) - - accBal, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, savingsVaultDenom, acc1) - suite.Require().NoError(err) - suite.Equal(sdkmath.NewInt(2000), accBal.Amount, "acc1 should have 2000 usdx") - - // 3. Withdraw all from acc1 - including accumulated amount - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1, sdk.NewInt64Coin(savingsVaultDenom, 2000), types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - acc1Shares, found = suite.Keeper.GetVaultAccountShares(suite.Ctx, acc1) - suite.Require().Falsef(found, "should have withdrawn entire shares but has %s", acc1Shares) - - _, err = suite.Keeper.GetVaultAccountValue(suite.Ctx, savingsVaultDenom, acc1) - suite.Require().Error(err) -} diff --git a/x/earn/keeper/vault.go b/x/earn/keeper/vault.go deleted file mode 100644 index e524acb4..00000000 --- a/x/earn/keeper/vault.go +++ /dev/null @@ -1,73 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/0glabs/0g-chain/x/earn/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// GetVaultTotalShares returns the total shares of a vault. -func (k *Keeper) GetVaultTotalShares( - ctx sdk.Context, - denom string, -) (types.VaultShare, bool) { - vault, found := k.GetVaultRecord(ctx, denom) - if !found { - return types.VaultShare{}, false - } - - return vault.TotalShares, true -} - -// GetVaultTotalValue returns the total value of a vault, i.e. the realizable -// total value if the vault were to liquidate its entire strategies. -// -// **Note:** This does not include the tokens held in bank by the module -// account. If it were to be included, also note that the module account is -// unblocked and can receive funds from bank sends. -func (k *Keeper) GetVaultTotalValue( - ctx sdk.Context, - denom string, -) (sdk.Coin, error) { - allowedVault, found := k.GetAllowedVault(ctx, denom) - if !found { - return sdk.Coin{}, types.ErrVaultRecordNotFound - } - - strategy, err := k.GetStrategy(allowedVault.Strategies[0]) - if err != nil { - return sdk.Coin{}, types.ErrInvalidVaultStrategy - } - - // Denom can be different from allowedVault.Denom for bkava - return strategy.GetEstimatedTotalAssets(ctx, denom) -} - -// GetVaultAccountShares returns the shares for a single address for all vaults. -func (k *Keeper) GetVaultAccountShares( - ctx sdk.Context, - acc sdk.AccAddress, -) (types.VaultShares, bool) { - vaultShareRecord, found := k.GetVaultShareRecord(ctx, acc) - if !found { - return nil, false - } - - return vaultShareRecord.Shares, true -} - -// GetVaultAccountValue returns the value of a single address within a vault -// if the account were to withdraw their entire balance. -func (k *Keeper) GetVaultAccountValue( - ctx sdk.Context, - denom string, - acc sdk.AccAddress, -) (sdk.Coin, error) { - accShares, found := k.GetVaultAccountShares(ctx, acc) - if !found { - return sdk.Coin{}, fmt.Errorf("account vault share record for %s not found", denom) - } - - return k.ConvertToAssets(ctx, accShares.GetShare(denom)) -} diff --git a/x/earn/keeper/vault_record.go b/x/earn/keeper/vault_record.go deleted file mode 100644 index 13f96d96..00000000 --- a/x/earn/keeper/vault_record.go +++ /dev/null @@ -1,85 +0,0 @@ -package keeper - -import ( - "github.com/0glabs/0g-chain/x/earn/types" - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// ---------------------------------------------------------------------------- -// VaultRecord -- vault total shares - -// GetVaultRecord returns the vault record for a given denom. -func (k *Keeper) GetVaultRecord( - ctx sdk.Context, - vaultDenom string, -) (types.VaultRecord, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.VaultRecordKeyPrefix) - - bz := store.Get(types.VaultKey(vaultDenom)) - if bz == nil { - return types.VaultRecord{}, false - } - - var record types.VaultRecord - k.cdc.MustUnmarshal(bz, &record) - - return record, true -} - -// UpdateVaultRecord updates the vault record in state for a given denom. This -// deletes it if the supply is zero and updates the state if supply is non-zero. -func (k *Keeper) UpdateVaultRecord( - ctx sdk.Context, - vaultRecord types.VaultRecord, -) { - if vaultRecord.TotalShares.Amount.IsZero() { - k.DeleteVaultRecord(ctx, vaultRecord.TotalShares.Denom) - } else { - k.SetVaultRecord(ctx, vaultRecord) - } -} - -// DeleteVaultRecord deletes the vault record for a given denom. -func (k *Keeper) DeleteVaultRecord(ctx sdk.Context, vaultDenom string) { - store := prefix.NewStore(ctx.KVStore(k.key), types.VaultRecordKeyPrefix) - store.Delete(types.VaultKey(vaultDenom)) -} - -// SetVaultRecord sets the vault record for a given denom. -func (k *Keeper) SetVaultRecord(ctx sdk.Context, record types.VaultRecord) { - store := prefix.NewStore(ctx.KVStore(k.key), types.VaultRecordKeyPrefix) - bz := k.cdc.MustMarshal(&record) - store.Set(types.VaultKey(record.TotalShares.Denom), bz) -} - -// IterateVaultRecords iterates over all vault objects in the store and performs -// a callback function. -func (k Keeper) IterateVaultRecords( - ctx sdk.Context, - cb func(record types.VaultRecord) (stop bool), -) { - store := prefix.NewStore(ctx.KVStore(k.key), types.VaultRecordKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - var record types.VaultRecord - k.cdc.MustUnmarshal(iterator.Value(), &record) - if cb(record) { - break - } - } -} - -// GetAllVaultRecords returns all vault records from the store. -func (k Keeper) GetAllVaultRecords(ctx sdk.Context) types.VaultRecords { - var records types.VaultRecords - - k.IterateVaultRecords(ctx, func(record types.VaultRecord) bool { - records = append(records, record) - return false - }) - - return records -} diff --git a/x/earn/keeper/vault_share.go b/x/earn/keeper/vault_share.go deleted file mode 100644 index 2fe10ff8..00000000 --- a/x/earn/keeper/vault_share.go +++ /dev/null @@ -1,82 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/0glabs/0g-chain/x/earn/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// ConvertToShares converts a given amount of tokens to shares. -func (k *Keeper) ConvertToShares(ctx sdk.Context, assets sdk.Coin) (types.VaultShare, error) { - totalShares, found := k.GetVaultTotalShares(ctx, assets.Denom) - if !found { - // No shares issued yet, so shares are issued 1:1 - return types.NewVaultShare(assets.Denom, sdk.NewDecFromInt(assets.Amount)), nil - } - - totalValue, err := k.GetVaultTotalValue(ctx, assets.Denom) - if err != nil { - return types.VaultShare{}, err - } - - if totalValue.Amount.IsZero() { - return types.VaultShare{}, fmt.Errorf("total value of vault is zero") - } - - // sharePrice = totalValue / totalShares - // issuedShares = assets / sharePrice - // issuedShares = assets / (totalValue / totalShares) - // = assets * (totalShares / totalValue) - // = (assets * totalShares) / totalValue - // - // Multiply by reciprocal of sharePrice to avoid two divisions and limit - // rounding to one time. Per-share price is also not used as there is a loss - // of precision. - - // Division is done at the last step as there is a slight amount that is - // rounded down. - // For example: - // 100 * 100 / 105 == 10000 / 105 == 95.238095238095238095 - // 100 * (100 / 105) == 100 * 0.952380952380952380 == 95.238095238095238000 - // rounded down and truncated ^ loss of precision ^ - issuedShares := sdk.NewDecFromInt(assets.Amount).Mul(totalShares.Amount).QuoTruncate(sdk.NewDecFromInt(totalValue.Amount)) - - if issuedShares.IsZero() { - return types.VaultShare{}, fmt.Errorf("share count is zero") - } - - return types.NewVaultShare(assets.Denom, issuedShares), nil -} - -// ConvertToAssets converts a given amount of shares to tokens. -func (k *Keeper) ConvertToAssets(ctx sdk.Context, share types.VaultShare) (sdk.Coin, error) { - totalVaultShares, found := k.GetVaultTotalShares(ctx, share.Denom) - if !found { - return sdk.Coin{}, fmt.Errorf("vault for %s not found", share.Denom) - } - - totalValue, err := k.GetVaultTotalValue(ctx, share.Denom) - if err != nil { - return sdk.Coin{}, err - } - - // percentOwnership := accShares / totalVaultShares - // accValue := totalValue * percentOwnership - // accValue := totalValue * accShares / totalVaultShares - // Division must be last to avoid rounding errors and properly truncate. - value := sdk.NewDecFromInt(totalValue.Amount).Mul(share.Amount).QuoTruncate(totalVaultShares.Amount) - - return sdk.NewCoin(share.Denom, value.TruncateInt()), nil -} - -// ShareIsDust returns true if the share value is less than 1 coin -func (k *Keeper) ShareIsDust(ctx sdk.Context, share types.VaultShare) (bool, error) { - coin, err := k.ConvertToAssets(ctx, share) - if err != nil { - return false, err - } - - // Truncated int, becomes zero if < 1 - return coin.IsZero(), nil -} diff --git a/x/earn/keeper/vault_share_record.go b/x/earn/keeper/vault_share_record.go deleted file mode 100644 index daa2293f..00000000 --- a/x/earn/keeper/vault_share_record.go +++ /dev/null @@ -1,93 +0,0 @@ -package keeper - -import ( - "github.com/0glabs/0g-chain/x/earn/types" - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// ---------------------------------------------------------------------------- -// VaultShareRecords -- user shares per vault - -// GetVaultShareRecord returns the vault share record for a given denom and -// account. -func (k *Keeper) GetVaultShareRecord( - ctx sdk.Context, - acc sdk.AccAddress, -) (types.VaultShareRecord, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.VaultShareRecordKeyPrefix) - - bz := store.Get(types.DepositorVaultSharesKey(acc)) - if bz == nil { - return types.VaultShareRecord{}, false - } - - var record types.VaultShareRecord - k.cdc.MustUnmarshal(bz, &record) - - return record, true -} - -// UpdateVaultShareRecord updates the vault share record in state for a given -// denom and account. This deletes it if the supply is zero and updates the -// state if supply is non-zero. -func (k *Keeper) UpdateVaultShareRecord( - ctx sdk.Context, - record types.VaultShareRecord, -) { - if record.Shares.IsZero() { - k.DeleteVaultShareRecord(ctx, record.Depositor) - } else { - k.SetVaultShareRecord(ctx, record) - } -} - -// DeleteVaultShareRecord deletes the vault share record for a given account. -func (k *Keeper) DeleteVaultShareRecord( - ctx sdk.Context, - acc sdk.AccAddress, -) { - store := prefix.NewStore(ctx.KVStore(k.key), types.VaultShareRecordKeyPrefix) - store.Delete(types.DepositorVaultSharesKey(acc)) -} - -// SetVaultShareRecord sets the vault share record for a given account. -func (k *Keeper) SetVaultShareRecord( - ctx sdk.Context, - record types.VaultShareRecord, -) { - store := prefix.NewStore(ctx.KVStore(k.key), types.VaultShareRecordKeyPrefix) - bz := k.cdc.MustMarshal(&record) - store.Set(types.DepositorVaultSharesKey(record.Depositor), bz) -} - -// IterateVaultShareRecords iterates over all vault share objects in the store -// and performs a callback function. -func (k Keeper) IterateVaultShareRecords( - ctx sdk.Context, - cb func(record types.VaultShareRecord) (stop bool), -) { - store := prefix.NewStore(ctx.KVStore(k.key), types.VaultShareRecordKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - var record types.VaultShareRecord - k.cdc.MustUnmarshal(iterator.Value(), &record) - if cb(record) { - break - } - } -} - -// GetAllVaultShareRecords returns all vault share records from the store. -func (k Keeper) GetAllVaultShareRecords(ctx sdk.Context) types.VaultShareRecords { - var records types.VaultShareRecords - - k.IterateVaultShareRecords(ctx, func(record types.VaultShareRecord) bool { - records = append(records, record) - return false - }) - - return records -} diff --git a/x/earn/keeper/vault_share_record_test.go b/x/earn/keeper/vault_share_record_test.go deleted file mode 100644 index c57d530e..00000000 --- a/x/earn/keeper/vault_share_record_test.go +++ /dev/null @@ -1,90 +0,0 @@ -package keeper_test - -import ( - "github.com/0glabs/0g-chain/x/earn/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// ---------------------------------------------------------------------------- -// State methods - -func (suite *vaultTestSuite) TestGetVaultRecord() { - record := types.NewVaultRecord("usdx", sdk.ZeroDec()) - - _, found := suite.Keeper.GetVaultRecord(suite.Ctx, record.TotalShares.Denom) - suite.Require().False(found) - - suite.Keeper.SetVaultRecord(suite.Ctx, record) - - stateRecord, found := suite.Keeper.GetVaultRecord(suite.Ctx, record.TotalShares.Denom) - suite.Require().True(found) - suite.Require().Equal(record, stateRecord) -} - -func (suite *vaultTestSuite) TestUpdateVaultRecord() { - record := types.NewVaultRecord("usdx", sdk.ZeroDec()) - - record.TotalShares = types.NewVaultShare("usdx", sdk.NewDec(100)) - - // Update vault - suite.Keeper.UpdateVaultRecord(suite.Ctx, record) - - stateRecord, found := suite.Keeper.GetVaultRecord(suite.Ctx, record.TotalShares.Denom) - suite.Require().True(found, "vault record with supply should exist") - suite.Require().Equal(record, stateRecord) - - // Remove supply - record.TotalShares = types.NewVaultShare("usdx", sdk.NewDec(0)) - suite.Keeper.UpdateVaultRecord(suite.Ctx, record) - - _, found = suite.Keeper.GetVaultRecord(suite.Ctx, record.TotalShares.Denom) - suite.Require().False(found, "vault record with 0 supply should be deleted") -} - -func (suite *vaultTestSuite) TestGetVaultShareRecord() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - record := types.NewVaultShareRecord(acc.GetAddress(), types.NewVaultShares()) - - // Check share doesn't exist before deposit - - _, found := suite.Keeper.GetVaultShareRecord(suite.Ctx, acc.GetAddress()) - suite.Require().False(found, "vault share record should not exist before deposit") - - // Update share record - record.Shares = types.NewVaultShares( - types.NewVaultShare(vaultDenom, sdk.NewDec(100)), - ) - suite.Keeper.SetVaultShareRecord(suite.Ctx, record) - - // Check share exists and matches set value - stateRecord, found := suite.Keeper.GetVaultShareRecord(suite.Ctx, acc.GetAddress()) - suite.Require().True(found) - suite.Require().Equal(record, stateRecord) -} - -func (suite *vaultTestSuite) TestUpdateVaultShareRecord() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - record := types.NewVaultShareRecord(acc.GetAddress(), types.NewVaultShares( - types.NewVaultShare(vaultDenom, sdk.NewDec(100)), - )) - - // Update vault - suite.Keeper.UpdateVaultShareRecord(suite.Ctx, record) - - stateRecord, found := suite.Keeper.GetVaultShareRecord(suite.Ctx, acc.GetAddress()) - suite.Require().True(found, "vault share record with supply should exist") - suite.Require().Equal(record, stateRecord) - - // Remove supply - record.Shares = types.NewVaultShares() - suite.Keeper.UpdateVaultShareRecord(suite.Ctx, record) - - _, found = suite.Keeper.GetVaultShareRecord(suite.Ctx, acc.GetAddress()) - suite.Require().False(found, "vault share record with 0 supply should be deleted") -} diff --git a/x/earn/keeper/vault_share_test.go b/x/earn/keeper/vault_share_test.go deleted file mode 100644 index 9f8d8faa..00000000 --- a/x/earn/keeper/vault_share_test.go +++ /dev/null @@ -1,133 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/earn/testutil" - "github.com/0glabs/0g-chain/x/earn/types" -) - -type vaultShareTestSuite struct { - testutil.Suite -} - -func (suite *vaultShareTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) -} - -func TestVaultShareTestSuite(t *testing.T) { - suite.Run(t, new(vaultShareTestSuite)) -} - -func (suite *vaultShareTestSuite) TestConvertToShares() { - vaultDenom := "usdx" - - tests := []struct { - name string - beforeConvert func() - giveAmount sdk.Coin - wantShares types.VaultShare - }{ - { - name: "initial 1:1", - beforeConvert: func() {}, - giveAmount: sdk.NewCoin(vaultDenom, sdkmath.NewInt(100)), - wantShares: types.NewVaultShare(vaultDenom, sdk.NewDec(100)), - }, - { - name: "value doubled", - - beforeConvert: func() { - // set total shares set total value for hard - // value is double than shares - // shares is 2x price now - suite.addTotalShareAndValue(vaultDenom, sdk.NewDec(100), sdkmath.NewInt(200)) - }, - giveAmount: sdk.NewCoin(vaultDenom, sdkmath.NewInt(100)), - wantShares: types.NewVaultShare(vaultDenom, sdk.NewDec(50)), - }, - { - name: "truncate", - - beforeConvert: func() { - suite.addTotalShareAndValue(vaultDenom, sdk.NewDec(1000), sdkmath.NewInt(1001)) - }, - giveAmount: sdk.NewCoin(vaultDenom, sdkmath.NewInt(100)), - // 100 * 100 / 101 = 99.0099something - wantShares: types.NewVaultShare(vaultDenom, sdk.NewDec(100).MulInt64(1000).QuoInt64(1001)), - }, - } - - for _, tt := range tests { - suite.Run(tt.name, func() { - // Reset state - suite.Suite.SetupTest() - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - err := suite.App.FundModuleAccount( - suite.Ctx, - types.ModuleName, - sdk.NewCoins(sdk.NewInt64Coin(vaultDenom, 10000)), - ) - suite.Require().NoError(err) - - // Run any deposits or any other setup - tt.beforeConvert() - - issuedShares, err := suite.Keeper.ConvertToShares(suite.Ctx, tt.giveAmount) - suite.Require().NoError(err) - - suite.Equal(tt.wantShares, issuedShares) - }) - } -} - -func (suite *vaultShareTestSuite) addTotalShareAndValue( - vaultDenom string, - vaultShares sdk.Dec, - hardDeposit sdkmath.Int, -) { - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - - vaultRecord, found := suite.Keeper.GetVaultRecord(suite.Ctx, vaultDenom) - if !found { - vaultRecord = types.NewVaultRecord(vaultDenom, sdk.ZeroDec()) - } - - // Add to vault record - vaultRecord.TotalShares.Amount = vaultRecord.TotalShares.Amount.Add(vaultShares) - - // set total shares - suite.Keeper.UpdateVaultRecord( - suite.Ctx, - vaultRecord, - ) - // add value for hard -- this does not set - err := suite.HardKeeper.Deposit( - suite.Ctx, - macc.GetAddress(), - sdk.NewCoins(sdk.NewCoin(vaultDenom, hardDeposit)), - ) - suite.Require().NoError(err) -} - -func TestPrecisionMulQuoOrder(t *testing.T) { - assetAmount := sdk.NewDec(100) - totalShares := sdk.NewDec(100) - totalValue := sdk.NewDec(105) - - // issuedShares = assetAmount * (totalValue / totalShares) - // = (assetAmount * totalShares) / totalValue - mulFirst := assetAmount.Mul(totalShares).QuoTruncate(totalValue) - quoFirst := assetAmount.Mul(totalShares.QuoTruncate(totalValue)) - - assert.Equal(t, sdk.MustNewDecFromStr("95.238095238095238095"), mulFirst) - assert.Equal(t, sdk.MustNewDecFromStr("95.238095238095238000"), quoFirst) - - assert.NotEqual(t, mulFirst, quoFirst) -} diff --git a/x/earn/keeper/vault_test.go b/x/earn/keeper/vault_test.go deleted file mode 100644 index 32d9c120..00000000 --- a/x/earn/keeper/vault_test.go +++ /dev/null @@ -1,161 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/earn/testutil" - "github.com/0glabs/0g-chain/x/earn/types" - "github.com/stretchr/testify/suite" -) - -type vaultTestSuite struct { - testutil.Suite -} - -func (suite *vaultTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) -} - -func TestVaultTestSuite(t *testing.T) { - suite.Run(t, new(vaultTestSuite)) -} - -func (suite *vaultTestSuite) TestGetVaultTotalShares() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - vaultTotalShares, found := suite.Keeper.GetVaultTotalShares(suite.Ctx, vaultDenom) - suite.Require().True(found) - - suite.Equal(sdk.NewDecFromInt(depositAmount.Amount), vaultTotalShares.Amount) -} - -func (suite *vaultTestSuite) TestGetVaultTotalShares_NotFound() { - vaultDenom := "usdx" - - _, found := suite.Keeper.GetVaultTotalShares(suite.Ctx, vaultDenom) - suite.Require().False(found) -} - -func (suite *vaultTestSuite) TestGetVaultTotalValue() { - vaultDenom := "usdx" - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - totalValue, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenom) - suite.Require().NoError(err) - suite.Equal(sdkmath.NewInt(0), totalValue.Amount) -} - -func (suite *vaultTestSuite) TestGetVaultTotalValue_NotFound() { - vaultDenom := "usdx" - - _, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, vaultDenom) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrVaultRecordNotFound) -} - -func (suite *vaultTestSuite) TestInvalidVaultStrategy() { - vaultDenom := "usdx" - - suite.PanicsWithValue("value from ParamSetPair is invalid: invalid strategy 99999", func() { - suite.CreateVault(vaultDenom, types.StrategyTypes{99999}, false, nil) // not valid strategy type - }) -} - -func (suite *vaultTestSuite) TestGetVaultAccountSupplied() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - deposit1Amount := sdk.NewInt64Coin(vaultDenom, 100) - deposit2Amount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1) - - // Before deposit, account supplied is 0 - - _, found := suite.Keeper.GetVaultShareRecord(suite.Ctx, acc1.GetAddress()) - suite.Require().False(found) - - _, found = suite.Keeper.GetVaultShareRecord(suite.Ctx, acc2.GetAddress()) - suite.Require().False(found) - - // Deposits from both accounts - err := suite.Keeper.Deposit(suite.Ctx, acc1.GetAddress(), deposit1Amount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - err = suite.Keeper.Deposit(suite.Ctx, acc2.GetAddress(), deposit2Amount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Check balances - - vaultAcc1Supplied, found := suite.Keeper.GetVaultShareRecord(suite.Ctx, acc1.GetAddress()) - suite.Require().True(found) - - vaultAcc2Supplied, found := suite.Keeper.GetVaultShareRecord(suite.Ctx, acc2.GetAddress()) - suite.Require().True(found) - - // Account supply only includes the deposit from respective accounts - suite.Equal(sdk.NewDecFromInt(deposit1Amount.Amount), vaultAcc1Supplied.Shares.AmountOf(vaultDenom)) - suite.Equal(sdk.NewDecFromInt(deposit1Amount.Amount), vaultAcc2Supplied.Shares.AmountOf(vaultDenom)) -} - -func (suite *vaultTestSuite) TestGetVaultAccountValue() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - accValue, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc.GetAddress()) - suite.Require().NoError(err) - suite.Equal(depositAmount, accValue, "value should be same as deposit amount") -} - -func (suite *vaultTestSuite) TestGetVaultAccountValue_VaultNotFound() { - vaultDenom := "usdx" - acc := suite.CreateAccount(sdk.NewCoins(), 0) - - _, err := suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc.GetAddress()) - suite.Require().Error(err) - suite.Require().Equal("account vault share record for usdx not found", err.Error()) -} - -func (suite *vaultTestSuite) TestGetVaultAccountValue_ShareNotFound() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Deposit from acc1 so that vault record exists - err := suite.Keeper.Deposit(suite.Ctx, acc1.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // Query from acc2 with no share record - _, err = suite.Keeper.GetVaultAccountValue(suite.Ctx, vaultDenom, acc2.GetAddress()) - suite.Require().Error(err) - suite.Require().Equal("account vault share record for usdx not found", err.Error()) -} diff --git a/x/earn/keeper/withdraw.go b/x/earn/keeper/withdraw.go deleted file mode 100644 index 834a5f0f..00000000 --- a/x/earn/keeper/withdraw.go +++ /dev/null @@ -1,168 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/earn/types" -) - -// Withdraw removes the amount of supplied tokens from a vault and transfers it -// back to the account. -func (k *Keeper) Withdraw( - ctx sdk.Context, - from sdk.AccAddress, - wantAmount sdk.Coin, - withdrawStrategy types.StrategyType, -) (sdk.Coin, error) { - // Get AllowedVault, if not found (not a valid vault), return error - allowedVault, found := k.GetAllowedVault(ctx, wantAmount.Denom) - if !found { - return sdk.Coin{}, types.ErrInvalidVaultDenom - } - - if wantAmount.IsZero() { - return sdk.Coin{}, types.ErrInsufficientAmount - } - - // Check if withdraw strategy is supported by vault - if !allowedVault.IsStrategyAllowed(withdrawStrategy) { - return sdk.Coin{}, types.ErrInvalidVaultStrategy - } - - // Check if VaultRecord exists - vaultRecord, found := k.GetVaultRecord(ctx, wantAmount.Denom) - if !found { - return sdk.Coin{}, types.ErrVaultRecordNotFound - } - - // Get account share record for the vault - vaultShareRecord, found := k.GetVaultShareRecord(ctx, from) - if !found { - return sdk.Coin{}, types.ErrVaultShareRecordNotFound - } - - withdrawShares, err := k.ConvertToShares(ctx, wantAmount) - if err != nil { - return sdk.Coin{}, fmt.Errorf("failed to convert assets to shares: %w", err) - } - - accCurrentShares := vaultShareRecord.Shares.AmountOf(wantAmount.Denom) - // Check if account is not withdrawing more shares than they have - if accCurrentShares.LT(withdrawShares.Amount) { - return sdk.Coin{}, errorsmod.Wrapf( - types.ErrInsufficientValue, - "account has less %s vault shares than withdraw shares, %s < %s", - wantAmount.Denom, - accCurrentShares, - withdrawShares.Amount, - ) - } - - // Convert shares to amount to get truncated true share value - withdrawAmount, err := k.ConvertToAssets(ctx, withdrawShares) - if err != nil { - return sdk.Coin{}, fmt.Errorf("failed to convert shares to assets: %w", err) - } - - accountValue, err := k.GetVaultAccountValue(ctx, wantAmount.Denom, from) - if err != nil { - return sdk.Coin{}, fmt.Errorf("failed to get account value: %w", err) - } - - // Check if withdrawAmount > account value - if withdrawAmount.Amount.GT(accountValue.Amount) { - return sdk.Coin{}, errorsmod.Wrapf( - types.ErrInsufficientValue, - "account has less %s vault value than withdraw amount, %s < %s", - withdrawAmount.Denom, - accountValue.Amount, - withdrawAmount.Amount, - ) - } - - // Get the strategy for the vault - strategy, err := k.GetStrategy(allowedVault.Strategies[0]) - if err != nil { - return sdk.Coin{}, err - } - - // Not necessary to check if amount denom is allowed for the strategy, as - // there would be no vault record if it weren't allowed. - - // Withdraw the withdrawAmount from the strategy - if err := strategy.Withdraw(ctx, withdrawAmount); err != nil { - return sdk.Coin{}, fmt.Errorf("failed to withdraw from strategy: %w", err) - } - - // Send coins back to account, must withdraw from strategy first or the - // module account may not have any funds to send. - if err := k.bankKeeper.SendCoinsFromModuleToAccount( - ctx, - types.ModuleName, - from, - sdk.NewCoins(withdrawAmount), - ); err != nil { - return sdk.Coin{}, err - } - - // Check if new account balance of shares results in account share value - // of < 1 of a sdk.Coin. This share value is not able to be withdrawn and - // should just be removed. - isDust, err := k.ShareIsDust( - ctx, - vaultShareRecord.Shares.GetShare(withdrawAmount.Denom).Sub(withdrawShares), - ) - if err != nil { - return sdk.Coin{}, err - } - - if isDust { - // Modify withdrawShares to subtract entire share balance for denom - // This does not modify the actual withdraw coin amount as the - // difference is < 1coin. - withdrawShares = vaultShareRecord.Shares.GetShare(withdrawAmount.Denom) - } - - // Call hook before record is modified with the user's current shares - k.BeforeVaultDepositModified(ctx, wantAmount.Denom, from, accCurrentShares) - - // Decrement VaultRecord and VaultShareRecord supplies - must delete same - // amounts - vaultShareRecord.Shares = vaultShareRecord.Shares.Sub(withdrawShares) - vaultRecord.TotalShares = vaultRecord.TotalShares.Sub(withdrawShares) - - // Update VaultRecord and VaultShareRecord, deletes if zero supply - k.UpdateVaultRecord(ctx, vaultRecord) - k.UpdateVaultShareRecord(ctx, vaultShareRecord) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeVaultWithdraw, - sdk.NewAttribute(types.AttributeKeyVaultDenom, withdrawAmount.Denom), - sdk.NewAttribute(types.AttributeKeyOwner, from.String()), - sdk.NewAttribute(types.AttributeKeyShares, withdrawShares.Amount.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, withdrawAmount.Amount.String()), - ), - ) - - return withdrawAmount, nil -} - -// WithdrawFromModuleAccount removes the amount of supplied tokens from a vault and transfers it -// back to the module account. The module account must be unblocked from receiving transfers. -func (k *Keeper) WithdrawFromModuleAccount( - ctx sdk.Context, - from string, - wantAmount sdk.Coin, - withdrawStrategy types.StrategyType, -) (sdk.Coin, error) { - // Ensure the module account exists to prevent SendCoins from creating a new non-module account. - acc := k.accountKeeper.GetModuleAccount(ctx, from) - if acc == nil { - return sdk.Coin{}, fmt.Errorf("module account not found: %s", from) - } - return k.Withdraw(ctx, acc.GetAddress(), wantAmount, withdrawStrategy) -} diff --git a/x/earn/keeper/withdraw_test.go b/x/earn/keeper/withdraw_test.go deleted file mode 100644 index 7bc10458..00000000 --- a/x/earn/keeper/withdraw_test.go +++ /dev/null @@ -1,274 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/earn/testutil" - "github.com/0glabs/0g-chain/x/earn/types" - "github.com/stretchr/testify/suite" -) - -type withdrawTestSuite struct { - testutil.Suite -} - -func (suite *withdrawTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) -} - -func TestWithdrawTestSuite(t *testing.T) { - suite.Run(t, new(withdrawTestSuite)) -} - -func (suite *withdrawTestSuite) TestWithdraw_NoVaultRecord() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - withdrawAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - // Withdraw without having any prior deposits - _, err := suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), withdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrVaultRecordNotFound) - - // No balance changes - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance), - ) - - suite.ModuleAccountBalanceEqual( - sdk.NewCoins(), - ) -} - -func (suite *withdrawTestSuite) TestWithdraw_NoVaultShareRecord() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - - acc1DepositAmount := sdk.NewCoin(vaultDenom, sdkmath.NewInt(100)) - acc2WithdrawAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - // Create deposit from acc1 so the VaultRecord exists in state - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - err := suite.Keeper.Deposit(suite.Ctx, acc1.GetAddress(), acc1DepositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - acc2 := suite.CreateAccount(sdk.NewCoins(startBalance), 1) - - // Withdraw from acc2 without having any prior deposits - _, err = suite.Keeper.Withdraw(suite.Ctx, acc2.GetAddress(), acc2WithdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrVaultShareRecordNotFound) - - // No balance changes in acc2 - suite.AccountBalanceEqual( - acc2.GetAddress(), - sdk.NewCoins(startBalance), - ) - - suite.VaultTotalValuesEqual(sdk.NewCoins(acc1DepositAmount)) - suite.VaultTotalSharesEqual(types.NewVaultShares( - types.NewVaultShare(acc1DepositAmount.Denom, sdk.NewDecFromInt(acc1DepositAmount.Amount)), - )) -} - -func (suite *withdrawTestSuite) TestWithdraw_ExceedBalance() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - withdrawAmount := sdk.NewInt64Coin(vaultDenom, 200) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), withdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrInsufficientValue) - - // Balances still the same after deposit - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance.Sub(depositAmount)), - ) - - suite.VaultTotalValuesEqual(sdk.NewCoins(depositAmount)) - suite.VaultTotalSharesEqual(types.NewVaultShares( - types.NewVaultShare(depositAmount.Denom, sdk.NewDecFromInt(depositAmount.Amount)), - )) -} - -func (suite *withdrawTestSuite) TestWithdraw_Zero() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - withdrawAmount := sdk.NewInt64Coin(vaultDenom, 0) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - _, err := suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), withdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrInsufficientAmount) - - // No changes in balances - - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance), - ) - - suite.ModuleAccountBalanceEqual( - sdk.NewCoins(), - ) -} - -func (suite *withdrawTestSuite) TestWithdraw_InvalidVault() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - withdrawAmount := sdk.NewInt64Coin(vaultDenom, 1001) - - // Vault not created -- doesn't exist - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - _, err := suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), withdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrInvalidVaultDenom) - - // No changes in balances - - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance), - ) - - suite.ModuleAccountBalanceEqual( - sdk.NewCoins(), - ) -} - -func (suite *withdrawTestSuite) TestWithdraw_InvalidStrategy() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - withdrawAmount := sdk.NewInt64Coin(vaultDenom, 1001) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - _, err := suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), withdrawAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrInvalidVaultStrategy) -} - -func (suite *withdrawTestSuite) TestWithdraw_FullBalance() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - withdrawAmount := sdk.NewInt64Coin(vaultDenom, 100) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), withdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // No net changes in balances - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance), - ) - - suite.ModuleAccountBalanceEqual( - sdk.NewCoins(), - ) -} - -func (suite *withdrawTestSuite) TestWithdraw_Partial() { - vaultDenom := "usdx" - startBalance := sdk.NewInt64Coin(vaultDenom, 1000) - depositAmount := sdk.NewInt64Coin(vaultDenom, 100) - partialWithdrawAmount := sdk.NewInt64Coin(vaultDenom, 50) - - suite.CreateVault(vaultDenom, types.StrategyTypes{types.STRATEGY_TYPE_HARD}, false, nil) - - acc := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - err := suite.Keeper.Deposit(suite.Ctx, acc.GetAddress(), depositAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), partialWithdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance.Sub(depositAmount).Add(partialWithdrawAmount)), - ) - - // Second withdraw for remaining 50 - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), partialWithdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().NoError(err) - - // No more balance to withdraw - _, err = suite.Keeper.Withdraw(suite.Ctx, acc.GetAddress(), partialWithdrawAmount, types.STRATEGY_TYPE_HARD) - suite.Require().Error(err) - suite.Require().ErrorIs(err, types.ErrVaultRecordNotFound, "vault record should be deleted after no more supplied") - - // No net changes in balances - suite.AccountBalanceEqual( - acc.GetAddress(), - sdk.NewCoins(startBalance), - ) - - suite.ModuleAccountBalanceEqual( - sdk.NewCoins(), - ) -} - -func (suite *withdrawTestSuite) TestWithdraw_bKava() { - vaultDenom := "bkava" - coinDenom := testutil.TestBkavaDenoms[0] - - startBalance := sdk.NewInt64Coin(coinDenom, 1000) - depositAmount := sdk.NewInt64Coin(coinDenom, 100) - - acc1 := suite.CreateAccount(sdk.NewCoins(startBalance), 0) - - // vault denom is only "bkava" which has it's own special handler - suite.CreateVault( - vaultDenom, - types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - false, - []sdk.AccAddress{}, - ) - - err := suite.Keeper.Deposit(suite.Ctx, acc1.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError( - err, - "should be able to deposit bkava derivative denom in bkava vault", - ) - - _, err = suite.Keeper.Withdraw(suite.Ctx, acc1.GetAddress(), depositAmount, types.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError( - err, - "should be able to withdraw bkava derivative denom from bkava vault", - ) -} diff --git a/x/earn/module.go b/x/earn/module.go deleted file mode 100644 index 127884f0..00000000 --- a/x/earn/module.go +++ /dev/null @@ -1,146 +0,0 @@ -package earn - -import ( - "context" - "encoding/json" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/0glabs/0g-chain/x/earn/client/cli" - "github.com/0glabs/0g-chain/x/earn/keeper" - "github.com/0glabs/0g-chain/x/earn/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name get module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - gs := types.DefaultGenesisState() - return cdc.MustMarshalJSON(&gs) -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - err := cdc.UnmarshalJSON(bz, &gs) - if err != nil { - return err - } - return gs.Validate() -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the gov module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// GetTxCmd returns the root tx command for the module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -//____________________________________________________________________________ - -// AppModule app module type -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper authkeeper.AccountKeeper - bankKeeper types.BankKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, accountKeeper authkeeper.AccountKeeper, bankKeeper types.BankKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - } -} - -// Name module name -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// RegisterInvariants register module invariants -func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { - keeper.RegisterInvariants(ir, am.keeper) -} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return 1 -} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) -} - -// InitGenesis module init-genesis -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { - var genState types.GenesisState - // Initialize global index to index in genesis state - cdc.MustUnmarshalJSON(gs, &genState) - - InitGenesis(ctx, am.keeper, am.accountKeeper, genState) - - return []abci.ValidatorUpdate{} -} - -// ExportGenesis module export genesis -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(&gs) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) { -} - -// EndBlock module end-block -func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/earn/testutil/suite.go b/x/earn/testutil/suite.go deleted file mode 100644 index 4d938df2..00000000 --- a/x/earn/testutil/suite.go +++ /dev/null @@ -1,459 +0,0 @@ -package testutil - -import ( - "fmt" - "reflect" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/earn/keeper" - "github.com/0glabs/0g-chain/x/earn/types" - "github.com/0glabs/0g-chain/x/hard" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - - hardkeeper "github.com/0glabs/0g-chain/x/hard/keeper" - hardtypes "github.com/0glabs/0g-chain/x/hard/types" - pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" - savingskeeper "github.com/0glabs/0g-chain/x/savings/keeper" - savingstypes "github.com/0glabs/0g-chain/x/savings/types" - - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" -) - -var TestBkavaDenoms = []string{ - "bkava-kavavaloper15gqc744d05xacn4n6w2furuads9fu4pqn6zxlu", - "bkava-kavavaloper15qdefkmwswysgg4qxgqpqr35k3m49pkx8yhpte", - "bkava-kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42", -} - -// Suite implements a test suite for the earn module integration tests -type Suite struct { - suite.Suite - Keeper keeper.Keeper - App app.TestApp - Ctx sdk.Context - BankKeeper bankkeeper.Keeper - AccountKeeper authkeeper.AccountKeeper - - // Strategy Keepers - HardKeeper hardkeeper.Keeper - SavingsKeeper savingskeeper.Keeper -} - -// SetupTest instantiates a new app, keepers, and sets suite state -func (suite *Suite) SetupTest() { - // Pricefeed required for withdrawing from hard - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "usdx:usd", BaseAsset: "usdx", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "usdx:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("10.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - }, - } - - hardGS := hardtypes.NewGenesisState(hardtypes.NewParams( - hardtypes.MoneyMarkets{ - hardtypes.NewMoneyMarket( - "usdx", - hardtypes.NewBorrowLimit( - true, - sdk.MustNewDecFromStr("20000000"), - sdk.MustNewDecFromStr("1"), - ), - "usdx:usd", - sdkmath.NewInt(1000000), - hardtypes.NewInterestRateModel( - sdk.MustNewDecFromStr("0.05"), - sdk.MustNewDecFromStr("2"), - sdk.MustNewDecFromStr("0.8"), - sdk.MustNewDecFromStr("10"), - ), - sdk.MustNewDecFromStr("0.05"), - sdk.ZeroDec(), - ), - hardtypes.NewMoneyMarket( - "busd", - hardtypes.NewBorrowLimit( - true, - sdk.MustNewDecFromStr("20000000"), - sdk.MustNewDecFromStr("1"), - ), - "busd:usd", - sdkmath.NewInt(1000000), - hardtypes.NewInterestRateModel( - sdk.MustNewDecFromStr("0.05"), - sdk.MustNewDecFromStr("2"), - sdk.MustNewDecFromStr("0.8"), - sdk.MustNewDecFromStr("10"), - ), - sdk.MustNewDecFromStr("0.05"), - sdk.ZeroDec(), - ), - hardtypes.NewMoneyMarket( - "kava", - hardtypes.NewBorrowLimit( - true, - sdk.MustNewDecFromStr("20000000"), - sdk.MustNewDecFromStr("1"), - ), - "kava:usd", - sdkmath.NewInt(1000000), - hardtypes.NewInterestRateModel( - sdk.MustNewDecFromStr("0.05"), - sdk.MustNewDecFromStr("2"), - sdk.MustNewDecFromStr("0.8"), - sdk.MustNewDecFromStr("10"), - ), - sdk.MustNewDecFromStr("0.05"), - sdk.ZeroDec(), - ), - }, - sdk.NewDec(10), - ), - hardtypes.DefaultAccumulationTimes, - hardtypes.DefaultDeposits, - hardtypes.DefaultBorrows, - hardtypes.DefaultTotalSupplied, - hardtypes.DefaultTotalBorrowed, - hardtypes.DefaultTotalReserves, - ) - - savingsGS := savingstypes.NewGenesisState( - savingstypes.NewParams( - []string{ - "ukava", - "busd", - "usdx", - TestBkavaDenoms[0], - TestBkavaDenoms[1], - TestBkavaDenoms[2], - }, - ), - nil, - ) - - stakingParams := stakingtypes.DefaultParams() - stakingParams.BondDenom = "ukava" - - stakingGs := stakingtypes.GenesisState{ - Params: stakingParams, - } - - tApp := app.NewTestApp() - - tApp.InitializeFromGenesisStates( - app.GenesisState{ - pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS), - hardtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS), - savingstypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&savingsGS), - stakingtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&stakingGs), - }, - ) - - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - suite.Ctx = ctx - suite.App = tApp - suite.Keeper = tApp.GetEarnKeeper() - suite.BankKeeper = tApp.GetBankKeeper() - suite.AccountKeeper = tApp.GetAccountKeeper() - - suite.HardKeeper = tApp.GetHardKeeper() - suite.SavingsKeeper = tApp.GetSavingsKeeper() - - hard.BeginBlocker(suite.Ctx, suite.HardKeeper) -} - -// GetEvents returns emitted events on the sdk context -func (suite *Suite) GetEvents() sdk.Events { - return suite.Ctx.EventManager().Events() -} - -// AddCoinsToModule adds coins to the earn module account -func (suite *Suite) AddCoinsToModule(amount sdk.Coins) { - // Does not use suite.BankKeeper.MintCoins as module account would not have permission to mint - err := banktestutil.FundModuleAccount(suite.BankKeeper, suite.Ctx, types.ModuleName, amount) - suite.Require().NoError(err) -} - -// RemoveCoinsFromModule removes coins to the earn module account -func (suite *Suite) RemoveCoinsFromModule(amount sdk.Coins) { - // Earn module does not have BurnCoins permission so we need to transfer to gov first to burn - err := suite.BankKeeper.SendCoinsFromModuleToModule(suite.Ctx, types.ModuleAccountName, govtypes.ModuleName, amount) - suite.Require().NoError(err) - err = suite.BankKeeper.BurnCoins(suite.Ctx, govtypes.ModuleName, amount) - suite.Require().NoError(err) -} - -// CreateAccount creates a new account from the provided balance, using index -// to create different new addresses. -func (suite *Suite) CreateAccount(initialBalance sdk.Coins, index int) authtypes.AccountI { - _, addrs := app.GeneratePrivKeyAddressPairs(index + 1) - ak := suite.App.GetAccountKeeper() - - acc := ak.NewAccountWithAddress(suite.Ctx, addrs[index]) - ak.SetAccount(suite.Ctx, acc) - - err := banktestutil.FundAccount(suite.BankKeeper, suite.Ctx, acc.GetAddress(), initialBalance) - suite.Require().NoError(err) - - return acc -} - -// NewAccountFromAddr creates a new account from the provided address with the provided balance -func (suite *Suite) NewAccountFromAddr(addr sdk.AccAddress, balance sdk.Coins) authtypes.AccountI { - ak := suite.App.GetAccountKeeper() - - acc := ak.NewAccountWithAddress(suite.Ctx, addr) - ak.SetAccount(suite.Ctx, acc) - - err := banktestutil.FundAccount(suite.BankKeeper, suite.Ctx, acc.GetAddress(), balance) - suite.Require().NoError(err) - - return acc -} - -// CreateVault adds a new vault to the keeper parameters -func (suite *Suite) CreateVault( - vaultDenom string, - vaultStrategies types.StrategyTypes, - isPrivateVault bool, - allowedDepositors []sdk.AccAddress, -) { - vault := types.NewAllowedVault(vaultDenom, vaultStrategies, isPrivateVault, allowedDepositors) - - allowedVaults := suite.Keeper.GetAllowedVaults(suite.Ctx) - allowedVaults = append(allowedVaults, vault) - - params := types.NewParams(allowedVaults) - - suite.Keeper.SetParams( - suite.Ctx, - params, - ) -} - -// AccountBalanceEqual asserts that the coins match the account balance -func (suite *Suite) AccountBalanceEqual(addr sdk.AccAddress, coins sdk.Coins) { - balance := suite.BankKeeper.GetAllBalances(suite.Ctx, addr) - suite.Equal(coins, balance, fmt.Sprintf("expected account balance to equal coins %s, but got %s", coins, balance)) -} - -// ModuleAccountBalanceEqual asserts that the earn module account balance matches the provided coins -func (suite *Suite) ModuleAccountBalanceEqual(coins sdk.Coins) { - balance := suite.BankKeeper.GetAllBalances( - suite.Ctx, - suite.AccountKeeper.GetModuleAddress(types.ModuleAccountName), - ) - suite.Equal(coins, balance, fmt.Sprintf("expected module account balance to equal coins %s, but got %s", coins, balance)) -} - -// ---------------------------------------------------------------------------- -// Earn - -// VaultTotalValuesEqual asserts that the vault total values match the provided -// values. -func (suite *Suite) VaultTotalValuesEqual(expected sdk.Coins) { - for _, coin := range expected { - vaultBal, err := suite.Keeper.GetVaultTotalValue(suite.Ctx, coin.Denom) - suite.Require().NoError(err, "failed to get vault balance") - suite.Require().Equal(coin, vaultBal) - } -} - -// VaultTotalSharesEqual asserts that the vault total shares match the provided -// values. -func (suite *Suite) VaultTotalSharesEqual(expected types.VaultShares) { - for _, share := range expected { - vaultBal, found := suite.Keeper.GetVaultTotalShares(suite.Ctx, share.Denom) - suite.Require().Truef(found, "%s vault does not exist", share.Denom) - suite.Require().Equal(share.Amount, vaultBal.Amount) - } -} - -// VaultAccountSharesEqual asserts that the vault account shares match the provided -// values. -func (suite *Suite) VaultAccountSharesEqual(accs []sdk.AccAddress, supplies []sdk.Coins) { - for i, acc := range accs { - coins := supplies[i] - - accVaultBal, found := suite.Keeper.GetVaultAccountShares(suite.Ctx, acc) - suite.Require().True(found) - - for _, coin := range coins { - suite.Require().Equal( - coin.Amount, - accVaultBal.AmountOf(coin.Denom), - "expected account vault balance to equal coins %s, but got %s", - coins, accVaultBal, - ) - } - } -} - -// ---------------------------------------------------------------------------- -// Hard - -// HardDepositAmountEqual asserts that the hard deposit amount matches the provided -// values. -func (suite *Suite) HardDepositAmountEqual(expected sdk.Coins) { - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - - hardDeposit, found := suite.HardKeeper.GetSyncedDeposit(suite.Ctx, macc.GetAddress()) - if expected.IsZero() { - suite.Require().False(found) - return - } - - suite.Require().True(found, "hard should have a deposit") - suite.Require().Equalf( - expected, - hardDeposit.Amount, - "hard should have a deposit with the amount %v", - expected, - ) -} - -// ---------------------------------------------------------------------------- -// Savings - -// SavingsDepositAmountEqual asserts that the savings deposit amount matches the -// provided values. -func (suite *Suite) SavingsDepositAmountEqual(expected sdk.Coins) { - macc := suite.AccountKeeper.GetModuleAccount(suite.Ctx, types.ModuleName) - - savingsDeposit, found := suite.SavingsKeeper.GetDeposit(suite.Ctx, macc.GetAddress()) - if expected.IsZero() { - suite.Require().False(found) - return - } - - suite.Require().True(found, "savings should have a deposit") - suite.Require().Equalf( - expected, - savingsDeposit.Amount, - "savings should have a deposit with the amount %v", - expected, - ) -} - -// ---------------------------------------------------------------------------- -// Staking - -// CreateNewUnbondedValidator creates a new validator in the staking module. -// New validators are unbonded until the end blocker is run. -func (suite *Suite) CreateNewUnbondedValidator(addr sdk.ValAddress, selfDelegation sdkmath.Int) stakingtypes.Validator { - // Create a validator - err := suite.deliverMsgCreateValidator(suite.Ctx, addr, suite.NewBondCoin(selfDelegation)) - suite.Require().NoError(err) - - // New validators are created in an unbonded state. Note if the end blocker is run later this validator could become bonded. - - validator, found := suite.App.GetStakingKeeper().GetValidator(suite.Ctx, addr) - suite.Require().True(found) - return validator -} - -// NewBondCoin creates a Coin with the current staking denom. -func (suite *Suite) NewBondCoin(amount sdkmath.Int) sdk.Coin { - stakingDenom := suite.App.GetStakingKeeper().BondDenom(suite.Ctx) - return sdk.NewCoin(stakingDenom, amount) -} - -// CreateDelegation delegates tokens to a validator. -func (suite *Suite) CreateDelegation(valAddr sdk.ValAddress, delegator sdk.AccAddress, amount sdkmath.Int) sdk.Dec { - sk := suite.App.GetStakingKeeper() - - stakingDenom := sk.BondDenom(suite.Ctx) - msg := stakingtypes.NewMsgDelegate( - delegator, - valAddr, - sdk.NewCoin(stakingDenom, amount), - ) - - msgServer := stakingkeeper.NewMsgServerImpl(sk) - _, err := msgServer.Delegate(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - - del, found := sk.GetDelegation(suite.Ctx, delegator, valAddr) - suite.Require().True(found) - return del.Shares -} - -func (suite *Suite) deliverMsgCreateValidator(ctx sdk.Context, address sdk.ValAddress, selfDelegation sdk.Coin) error { - msg, err := stakingtypes.NewMsgCreateValidator( - address, - ed25519.GenPrivKey().PubKey(), - selfDelegation, - stakingtypes.Description{}, - stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - sdkmath.NewInt(1e6), - ) - if err != nil { - return err - } - - msgServer := stakingkeeper.NewMsgServerImpl(suite.App.GetStakingKeeper()) - _, err = msgServer.CreateValidator(sdk.WrapSDKContext(suite.Ctx), msg) - return err -} - -// ---------------------------------------------------------------------------- - -// EventsContains asserts that the expected event is in the provided events -func (suite *Suite) EventsContains(events sdk.Events, expectedEvent sdk.Event) { - foundMatch := false - for _, event := range events { - if event.Type == expectedEvent.Type { - if reflect.DeepEqual(attrsToMap(expectedEvent.Attributes), attrsToMap(event.Attributes)) { - foundMatch = true - } - } - } - - suite.True(foundMatch, fmt.Sprintf("event of type %s not found or did not match", expectedEvent.Type)) -} - -func attrsToMap(attrs []abci.EventAttribute) []sdk.Attribute { // new cosmos changed the event attribute type - out := []sdk.Attribute{} - - for _, attr := range attrs { - out = append(out, sdk.NewAttribute(string(attr.Key), string(attr.Value))) - } - - return out -} diff --git a/x/earn/types/codec.go b/x/earn/types/codec.go deleted file mode 100644 index 8b773ff8..00000000 --- a/x/earn/types/codec.go +++ /dev/null @@ -1,50 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the -// earn module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgDeposit{}, "earn/MsgDeposit", nil) - cdc.RegisterConcrete(&MsgWithdraw{}, "earn/MsgWithdraw", nil) - cdc.RegisterConcrete(&CommunityPoolDepositProposal{}, "kava/CommunityPoolDepositProposal", nil) - cdc.RegisterConcrete(&CommunityPoolWithdrawProposal{}, "kava/CommunityPoolWithdrawProposal", nil) -} - -// RegisterInterfaces registers proto messages under their interfaces for unmarshalling, -// in addition to registerting the msg service for handling tx msgs -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgDeposit{}, - &MsgWithdraw{}, - ) - registry.RegisterImplementations((*govv1beta1.Content)(nil), - &CommunityPoolDepositProposal{}, - &CommunityPoolWithdrawProposal{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - // ModuleCdc represents the legacy amino codec for the module - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/earn/types/errors.go b/x/earn/types/errors.go deleted file mode 100644 index f733e8de..00000000 --- a/x/earn/types/errors.go +++ /dev/null @@ -1,14 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -// earn module errors -var ( - ErrInvalidVaultDenom = errorsmod.Register(ModuleName, 2, "invalid vault denom") - ErrInvalidVaultStrategy = errorsmod.Register(ModuleName, 3, "vault does not support this strategy") - ErrInsufficientAmount = errorsmod.Register(ModuleName, 4, "insufficient amount") - ErrInsufficientValue = errorsmod.Register(ModuleName, 5, "insufficient vault account value") - ErrVaultRecordNotFound = errorsmod.Register(ModuleName, 6, "vault record not found") - ErrVaultShareRecordNotFound = errorsmod.Register(ModuleName, 7, "vault share record not found") - ErrAccountDepositNotAllowed = errorsmod.Register(ModuleName, 8, "account is not allowed to deposit to this vault") -) diff --git a/x/earn/types/events.go b/x/earn/types/events.go deleted file mode 100644 index bcb38000..00000000 --- a/x/earn/types/events.go +++ /dev/null @@ -1,12 +0,0 @@ -package types - -// Event types for earn module -const ( - AttributeValueCategory = ModuleName - EventTypeVaultDeposit = "vault_deposit" - EventTypeVaultWithdraw = "vault_withdraw" - AttributeKeyVaultDenom = "vault_denom" - AttributeKeyDepositor = "depositor" - AttributeKeyShares = "shares" - AttributeKeyOwner = "owner" -) diff --git a/x/earn/types/expected_keepers.go b/x/earn/types/expected_keepers.go deleted file mode 100644 index 65bbf027..00000000 --- a/x/earn/types/expected_keepers.go +++ /dev/null @@ -1,63 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" - disttypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - - hardtypes "github.com/0glabs/0g-chain/x/hard/types" - savingstypes "github.com/0glabs/0g-chain/x/savings/types" -) - -// AccountKeeper defines the expected account keeper -type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI - SetModuleAccount(sdk.Context, types.ModuleAccountI) - GetModuleAddress(name string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, name string) types.ModuleAccountI -} - -// BankKeeper defines the expected interface needed to retrieve account balances. -type BankKeeper interface { - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error -} - -// DistributionKeeper defines the expected interface needed for community-pool deposits to earn vaults -type DistributionKeeper interface { - GetFeePool(ctx sdk.Context) (feePool disttypes.FeePool) - SetFeePool(ctx sdk.Context, feePool disttypes.FeePool) - GetDistributionAccount(ctx sdk.Context) types.ModuleAccountI - DistributeFromFeePool(ctx sdk.Context, amount sdk.Coins, receiveAddr sdk.AccAddress) error -} - -// LiquidKeeper defines the expected interface needed for derivative to staked token conversions. -type LiquidKeeper interface { - GetStakedTokensForDerivatives(ctx sdk.Context, derivatives sdk.Coins) (sdk.Coin, error) - IsDerivativeDenom(ctx sdk.Context, denom string) bool -} - -// HardKeeper defines the expected interface needed for the hard strategy. -type HardKeeper interface { - Deposit(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error - Withdraw(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error - - GetSyncedDeposit(ctx sdk.Context, depositor sdk.AccAddress) (hardtypes.Deposit, bool) -} - -// SavingsKeeper defines the expected interface needed for the savings strategy. -type SavingsKeeper interface { - Deposit(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error - Withdraw(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error - - GetDeposit(ctx sdk.Context, depositor sdk.AccAddress) (savingstypes.Deposit, bool) -} - -// EarnHooks are event hooks called when a user's deposit to a earn vault changes. -type EarnHooks interface { - AfterVaultDepositCreated(ctx sdk.Context, vaultDenom string, depositor sdk.AccAddress, sharesOwned sdk.Dec) - BeforeVaultDepositModified(ctx sdk.Context, vaultDenom string, depositor sdk.AccAddress, sharesOwned sdk.Dec) -} diff --git a/x/earn/types/genesis.go b/x/earn/types/genesis.go deleted file mode 100644 index 05eebfb1..00000000 --- a/x/earn/types/genesis.go +++ /dev/null @@ -1,40 +0,0 @@ -package types - -// NewGenesisState creates a new genesis state. -func NewGenesisState( - params Params, - vaultRecords VaultRecords, - vaultShareRecords VaultShareRecords, -) GenesisState { - return GenesisState{ - Params: params, - VaultRecords: vaultRecords, - VaultShareRecords: vaultShareRecords, - } -} - -// Validate validates the module's genesis state -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - - if err := gs.VaultRecords.Validate(); err != nil { - return err - } - - if err := gs.VaultShareRecords.Validate(); err != nil { - return err - } - - return nil -} - -// DefaultGenesisState returns a default genesis state -func DefaultGenesisState() GenesisState { - return NewGenesisState( - DefaultParams(), - VaultRecords{}, - VaultShareRecords{}, - ) -} diff --git a/x/earn/types/genesis.pb.go b/x/earn/types/genesis.pb.go deleted file mode 100644 index 791e5df4..00000000 --- a/x/earn/types/genesis.pb.go +++ /dev/null @@ -1,454 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/earn/v1beta1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// GenesisState defines the earn module's genesis state. -type GenesisState struct { - // params defines all the parameters related to earn - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - // vault_records defines the available vaults - VaultRecords VaultRecords `protobuf:"bytes,2,rep,name=vault_records,json=vaultRecords,proto3,castrepeated=VaultRecords" json:"vault_records"` - // share_records defines the owned shares of each vault - VaultShareRecords VaultShareRecords `protobuf:"bytes,3,rep,name=vault_share_records,json=vaultShareRecords,proto3,castrepeated=VaultShareRecords" json:"vault_share_records"` -} - -func (m *GenesisState) Reset() { *m = GenesisState{} } -func (m *GenesisState) String() string { return proto.CompactTextString(m) } -func (*GenesisState) ProtoMessage() {} -func (*GenesisState) Descriptor() ([]byte, []int) { - return fileDescriptor_514fe130cb964f8c, []int{0} -} -func (m *GenesisState) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisState) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisState.Merge(m, src) -} -func (m *GenesisState) XXX_Size() int { - return m.Size() -} -func (m *GenesisState) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisState.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisState proto.InternalMessageInfo - -func (m *GenesisState) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -func (m *GenesisState) GetVaultRecords() VaultRecords { - if m != nil { - return m.VaultRecords - } - return nil -} - -func (m *GenesisState) GetVaultShareRecords() VaultShareRecords { - if m != nil { - return m.VaultShareRecords - } - return nil -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "kava.earn.v1beta1.GenesisState") -} - -func init() { proto.RegisterFile("kava/earn/v1beta1/genesis.proto", fileDescriptor_514fe130cb964f8c) } - -var fileDescriptor_514fe130cb964f8c = []byte{ - // 300 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcf, 0x4e, 0x2c, 0x4b, - 0xd4, 0x4f, 0x4d, 0x2c, 0xca, 0xd3, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0x4f, - 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x04, 0x29, 0xd0, - 0x03, 0x29, 0xd0, 0x83, 0x2a, 0x90, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0xcb, 0xea, 0x83, 0x58, - 0x10, 0x85, 0x52, 0x72, 0x98, 0x26, 0x15, 0x24, 0x16, 0x25, 0xe6, 0x42, 0x0d, 0x92, 0x92, 0xc5, - 0x94, 0x2f, 0x4b, 0x2c, 0xcd, 0x29, 0x81, 0x48, 0x2b, 0x4d, 0x62, 0xe2, 0xe2, 0x71, 0x87, 0xd8, - 0x1c, 0x5c, 0x92, 0x58, 0x92, 0x2a, 0x64, 0xce, 0xc5, 0x06, 0xd1, 0x2f, 0xc1, 0xa8, 0xc0, 0xa8, - 0xc1, 0x6d, 0x24, 0xa9, 0x87, 0xe1, 0x12, 0xbd, 0x00, 0xb0, 0x02, 0x27, 0x96, 0x13, 0xf7, 0xe4, - 0x19, 0x82, 0xa0, 0xca, 0x85, 0x22, 0xb9, 0x78, 0xc1, 0x06, 0xc7, 0x17, 0xa5, 0x26, 0xe7, 0x17, - 0xa5, 0x14, 0x4b, 0x30, 0x29, 0x30, 0x6b, 0x70, 0x1b, 0xc9, 0x61, 0xd1, 0x1f, 0x06, 0x52, 0x17, - 0x04, 0x56, 0xe6, 0x24, 0x02, 0x32, 0x64, 0xd5, 0x7d, 0x79, 0x1e, 0x24, 0xc1, 0xe2, 0x20, 0x9e, - 0x32, 0x24, 0x9e, 0x50, 0x1e, 0x97, 0x30, 0xc4, 0xe8, 0xe2, 0x8c, 0xc4, 0xa2, 0x54, 0xb8, 0x05, - 0xcc, 0x60, 0x0b, 0x94, 0x71, 0x59, 0x10, 0x0c, 0x52, 0x0c, 0xb5, 0x45, 0x12, 0x6a, 0x8b, 0x20, - 0xba, 0x4c, 0x71, 0x90, 0x60, 0x19, 0xba, 0x90, 0x93, 0xe3, 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, - 0xc9, 0x31, 0x3e, 0x78, 0x24, 0xc7, 0x38, 0xe1, 0xb1, 0x1c, 0xc3, 0x85, 0xc7, 0x72, 0x0c, 0x37, - 0x1e, 0xcb, 0x31, 0x44, 0xa9, 0xa7, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, - 0x1b, 0xa4, 0xe7, 0x24, 0x26, 0x15, 0xeb, 0x1b, 0xa4, 0xeb, 0x26, 0x67, 0x24, 0x66, 0xe6, 0xe9, - 0x57, 0x40, 0x42, 0xb9, 0xa4, 0xb2, 0x20, 0xb5, 0x38, 0x89, 0x0d, 0x1c, 0xbc, 0xc6, 0x80, 0x00, - 0x00, 0x00, 0xff, 0xff, 0xb7, 0xb3, 0xac, 0xee, 0xe9, 0x01, 0x00, 0x00, -} - -func (m *GenesisState) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.VaultShareRecords) > 0 { - for iNdEx := len(m.VaultShareRecords) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.VaultShareRecords[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.VaultRecords) > 0 { - for iNdEx := len(m.VaultRecords) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.VaultRecords[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *GenesisState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.VaultRecords) > 0 { - for _, e := range m.VaultRecords { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.VaultShareRecords) > 0 { - for _, e := range m.VaultShareRecords { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *GenesisState) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field VaultRecords", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.VaultRecords = append(m.VaultRecords, VaultRecord{}) - if err := m.VaultRecords[len(m.VaultRecords)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field VaultShareRecords", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.VaultShareRecords = append(m.VaultShareRecords, VaultShareRecord{}) - if err := m.VaultShareRecords[len(m.VaultShareRecords)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/earn/types/keys.go b/x/earn/types/keys.go deleted file mode 100644 index ede49dfd..00000000 --- a/x/earn/types/keys.go +++ /dev/null @@ -1,36 +0,0 @@ -package types - -import sdk "github.com/cosmos/cosmos-sdk/types" - -const ( - // ModuleName name that will be used throughout the module - ModuleName = "earn" - - // ModuleAccountName name of module account used to hold liquidity - ModuleAccountName = "earn" - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey Top level router key - RouterKey = ModuleName - - // DefaultParamspace default name for parameter store - DefaultParamspace = ModuleName -) - -// key prefixes for store -var ( - VaultRecordKeyPrefix = []byte{0x01} // denom -> vault - VaultShareRecordKeyPrefix = []byte{0x02} // depositor address -> vault shares -) - -// VaultKey returns a key generated from a vault denom -func VaultKey(denom string) []byte { - return []byte(denom) -} - -// DepositorVaultSharesKey returns a key from a depositor address -func DepositorVaultSharesKey(depositor sdk.AccAddress) []byte { - return depositor.Bytes() -} diff --git a/x/earn/types/mocks/EarnHooks.go b/x/earn/types/mocks/EarnHooks.go deleted file mode 100644 index 97df2f16..00000000 --- a/x/earn/types/mocks/EarnHooks.go +++ /dev/null @@ -1,38 +0,0 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. - -package mocks - -import ( - types "github.com/cosmos/cosmos-sdk/types" - mock "github.com/stretchr/testify/mock" -) - -// EarnHooks is an autogenerated mock type for the EarnHooks type -type EarnHooks struct { - mock.Mock -} - -// AfterVaultDepositCreated provides a mock function with given fields: ctx, vaultDenom, depositor, sharesOwned -func (_m *EarnHooks) AfterVaultDepositCreated(ctx types.Context, vaultDenom string, depositor types.AccAddress, sharesOwned types.Dec) { - _m.Called(ctx, vaultDenom, depositor, sharesOwned) -} - -// BeforeVaultDepositModified provides a mock function with given fields: ctx, vaultDenom, depositor, sharesOwned -func (_m *EarnHooks) BeforeVaultDepositModified(ctx types.Context, vaultDenom string, depositor types.AccAddress, sharesOwned types.Dec) { - _m.Called(ctx, vaultDenom, depositor, sharesOwned) -} - -type mockConstructorTestingTNewEarnHooks interface { - mock.TestingT - Cleanup(func()) -} - -// NewEarnHooks creates a new instance of EarnHooks. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewEarnHooks(t mockConstructorTestingTNewEarnHooks) *EarnHooks { - mock := &EarnHooks{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/x/earn/types/msg.go b/x/earn/types/msg.go deleted file mode 100644 index 4adbeeab..00000000 --- a/x/earn/types/msg.go +++ /dev/null @@ -1,125 +0,0 @@ -package types - -import ( - 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/auth/migrations/legacytx" -) - -var ( - _ sdk.Msg = &MsgDeposit{} - _ sdk.Msg = &MsgWithdraw{} - _ legacytx.LegacyMsg = &MsgDeposit{} - _ legacytx.LegacyMsg = &MsgWithdraw{} -) - -// legacy message types -const ( - TypeMsgDeposit = "earn_msg_deposit" - TypeMsgWithdraw = "earn_msg_withdraw" -) - -// NewMsgDeposit returns a new MsgDeposit. -func NewMsgDeposit(depositor string, amount sdk.Coin, strategy StrategyType) *MsgDeposit { - return &MsgDeposit{ - Depositor: depositor, - Amount: amount, - Strategy: strategy, - } -} - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgDeposit) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Depositor); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if err := msg.Amount.Validate(); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, err.Error()) - } - - if err := msg.Strategy.Validate(); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, err.Error()) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgDeposit) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgDeposit) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - panic(err) - } - - return []sdk.AccAddress{depositor} -} - -// Route implements the LegacyMsg.Route method. -func (msg MsgDeposit) Route() string { - return RouterKey -} - -// Type implements the LegacyMsg.Type method. -func (msg MsgDeposit) Type() string { - return TypeMsgDeposit -} - -// NewMsgWithdraw returns a new MsgWithdraw. -func NewMsgWithdraw(from string, amount sdk.Coin, strategy StrategyType) *MsgWithdraw { - return &MsgWithdraw{ - From: from, - Amount: amount, - Strategy: strategy, - } -} - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgWithdraw) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.From); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if err := msg.Amount.Validate(); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, err.Error()) - } - - if err := msg.Strategy.Validate(); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, err.Error()) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgWithdraw) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgWithdraw) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - panic(err) - } - - return []sdk.AccAddress{depositor} -} - -// Route implements the LegacyMsg.Route method. -func (msg MsgWithdraw) Route() string { - return RouterKey -} - -// Type implements the LegacyMsg.Type method. -func (msg MsgWithdraw) Type() string { - return TypeMsgWithdraw -} diff --git a/x/earn/types/params.go b/x/earn/types/params.go deleted file mode 100644 index 5a5b18e2..00000000 --- a/x/earn/types/params.go +++ /dev/null @@ -1,51 +0,0 @@ -package types - -import ( - fmt "fmt" - - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -// Parameter keys and default values -var ( - KeyAllowedVaults = []byte("AllowedVaults") - DefaultAllowedVaults = AllowedVaults{} -) - -// NewParams returns a new params object -func NewParams(allowedVaults AllowedVaults) Params { - return Params{ - AllowedVaults: allowedVaults, - } -} - -// DefaultParams returns default params for earn module -func DefaultParams() Params { - return NewParams(DefaultAllowedVaults) -} - -// ParamKeyTable for earn module. -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements params.ParamSet -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyAllowedVaults, &p.AllowedVaults, validateAllowedVaultsParams), - } -} - -// Validate checks that the parameters have valid values. -func (p Params) Validate() error { - return p.AllowedVaults.Validate() -} - -func validateAllowedVaultsParams(i interface{}) error { - p, ok := i.(AllowedVaults) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return p.Validate() -} diff --git a/x/earn/types/params.pb.go b/x/earn/types/params.pb.go deleted file mode 100644 index 51e28945..00000000 --- a/x/earn/types/params.pb.go +++ /dev/null @@ -1,331 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/earn/v1beta1/params.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// Params defines the parameters of the earn module. -type Params struct { - AllowedVaults AllowedVaults `protobuf:"bytes,1,rep,name=allowed_vaults,json=allowedVaults,proto3,castrepeated=AllowedVaults" json:"allowed_vaults"` -} - -func (m *Params) Reset() { *m = Params{} } -func (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_b9b515f90f68dc5a, []int{0} -} -func (m *Params) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Params.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Params) XXX_Merge(src proto.Message) { - xxx_messageInfo_Params.Merge(m, src) -} -func (m *Params) XXX_Size() int { - return m.Size() -} -func (m *Params) XXX_DiscardUnknown() { - xxx_messageInfo_Params.DiscardUnknown(m) -} - -var xxx_messageInfo_Params proto.InternalMessageInfo - -func (m *Params) GetAllowedVaults() AllowedVaults { - if m != nil { - return m.AllowedVaults - } - return nil -} - -func init() { - proto.RegisterType((*Params)(nil), "kava.earn.v1beta1.Params") -} - -func init() { proto.RegisterFile("kava/earn/v1beta1/params.proto", fileDescriptor_b9b515f90f68dc5a) } - -var fileDescriptor_b9b515f90f68dc5a = []byte{ - // 218 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcb, 0x4e, 0x2c, 0x4b, - 0xd4, 0x4f, 0x4d, 0x2c, 0xca, 0xd3, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x2f, 0x48, - 0x2c, 0x4a, 0xcc, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x04, 0xc9, 0xeb, 0x81, - 0xe4, 0xf5, 0xa0, 0xf2, 0x52, 0x22, 0xe9, 0xf9, 0xe9, 0xf9, 0x60, 0x59, 0x7d, 0x10, 0x0b, 0xa2, - 0x50, 0x4a, 0x16, 0xd3, 0xa0, 0xb2, 0xc4, 0xd2, 0x9c, 0x12, 0x88, 0xb4, 0x52, 0x3a, 0x17, 0x5b, - 0x00, 0xd8, 0x5c, 0xa1, 0x58, 0x2e, 0xbe, 0xc4, 0x9c, 0x9c, 0xfc, 0xf2, 0xd4, 0x94, 0x78, 0xb0, - 0x82, 0x62, 0x09, 0x46, 0x05, 0x66, 0x0d, 0x6e, 0x23, 0x79, 0x3d, 0x0c, 0xab, 0xf4, 0x1c, 0x21, - 0x0a, 0xc3, 0x40, 0xea, 0x9c, 0x44, 0x4f, 0xdc, 0x93, 0x67, 0x58, 0x75, 0x5f, 0x9e, 0x17, 0x59, - 0xb4, 0x38, 0x88, 0x37, 0x11, 0x99, 0xeb, 0xe4, 0x78, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, - 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, - 0x72, 0x0c, 0x51, 0xea, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x06, - 0xe9, 0x39, 0x89, 0x49, 0xc5, 0xfa, 0x06, 0xe9, 0xba, 0xc9, 0x19, 0x89, 0x99, 0x79, 0xfa, 0x15, - 0x10, 0x97, 0x97, 0x54, 0x16, 0xa4, 0x16, 0x27, 0xb1, 0x81, 0x9d, 0x6c, 0x0c, 0x08, 0x00, 0x00, - 0xff, 0xff, 0x64, 0xe3, 0xb9, 0x14, 0x1c, 0x01, 0x00, 0x00, -} - -func (m *Params) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Params) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.AllowedVaults) > 0 { - for iNdEx := len(m.AllowedVaults) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.AllowedVaults[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintParams(dAtA []byte, offset int, v uint64) int { - offset -= sovParams(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.AllowedVaults) > 0 { - for _, e := range m.AllowedVaults { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - return n -} - -func sovParams(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozParams(x uint64) (n int) { - return sovParams(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Params) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Params: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AllowedVaults", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.AllowedVaults = append(m.AllowedVaults, AllowedVault{}) - if err := m.AllowedVaults[len(m.AllowedVaults)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParams(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParams - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipParams(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParams - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParams - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParams - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthParams - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupParams - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthParams - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthParams = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowParams = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupParams = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/earn/types/proposal.go b/x/earn/types/proposal.go deleted file mode 100644 index ee4433b8..00000000 --- a/x/earn/types/proposal.go +++ /dev/null @@ -1,118 +0,0 @@ -package types - -import ( - fmt "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" - govcodec "github.com/cosmos/cosmos-sdk/x/gov/codec" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -const ( - // ProposalTypeCommunityPoolDeposit defines the type for a CommunityPoolDepositProposal - ProposalTypeCommunityPoolDeposit = "CommunityPoolDeposit" - // ProposalTypeCommunityPoolWithdraw defines the type for a CommunityPoolDepositProposal - ProposalTypeCommunityPoolWithdraw = "CommunityPoolWithdraw" -) - -// Assert CommunityPoolDepositProposal implements govtypes.Content at compile-time -var ( - _ govv1beta1.Content = &CommunityPoolDepositProposal{} - _ govv1beta1.Content = &CommunityPoolWithdrawProposal{} -) - -func init() { - govv1beta1.RegisterProposalType(ProposalTypeCommunityPoolDeposit) - govcodec.ModuleCdc.Amino.RegisterConcrete(&CommunityPoolDepositProposal{}, "kava/CommunityPoolDepositProposal", nil) - govv1beta1.RegisterProposalType(ProposalTypeCommunityPoolWithdraw) - govcodec.ModuleCdc.Amino.RegisterConcrete(&CommunityPoolWithdrawProposal{}, "kava/CommunityPoolWithdrawProposal", nil) -} - -// NewCommunityPoolDepositProposal creates a new community pool deposit proposal. -func NewCommunityPoolDepositProposal(title, description string, amount sdk.Coin) *CommunityPoolDepositProposal { - return &CommunityPoolDepositProposal{ - Title: title, - Description: description, - Amount: amount, - } -} - -// GetTitle returns the title of a community pool deposit proposal. -func (cdp *CommunityPoolDepositProposal) GetTitle() string { return cdp.Title } - -// GetDescription returns the description of a community pool deposit proposal. -func (cdp *CommunityPoolDepositProposal) GetDescription() string { return cdp.Description } - -// GetDescription returns the routing key of a community pool deposit proposal. -func (cdp *CommunityPoolDepositProposal) ProposalRoute() string { return RouterKey } - -// ProposalType returns the type of a community pool deposit proposal. -func (cdp *CommunityPoolDepositProposal) ProposalType() string { - return ProposalTypeCommunityPoolDeposit -} - -// String implements fmt.Stringer -func (cdp *CommunityPoolDepositProposal) String() string { - - var b strings.Builder - b.WriteString(fmt.Sprintf(`Community Pool Deposit Proposal: - Title: %s - Description: %s - Amount: %s -`, cdp.Title, cdp.Description, cdp.Amount)) - return b.String() -} - -// ValidateBasic stateless validation of a community pool multi-spend proposal. -func (cdp *CommunityPoolDepositProposal) ValidateBasic() error { - err := govv1beta1.ValidateAbstract(cdp) - if err != nil { - return err - } - return cdp.Amount.Validate() -} - -// NewCommunityPoolWithdrawProposal creates a new community pool deposit proposal. -func NewCommunityPoolWithdrawProposal(title, description string, amount sdk.Coin) *CommunityPoolWithdrawProposal { - return &CommunityPoolWithdrawProposal{ - Title: title, - Description: description, - Amount: amount, - } -} - -// GetTitle returns the title of a community pool withdraw proposal. -func (cdp *CommunityPoolWithdrawProposal) GetTitle() string { return cdp.Title } - -// GetDescription returns the description of a community pool withdraw proposal. -func (cdp *CommunityPoolWithdrawProposal) GetDescription() string { return cdp.Description } - -// GetDescription returns the routing key of a community pool withdraw proposal. -func (cdp *CommunityPoolWithdrawProposal) ProposalRoute() string { return RouterKey } - -// ProposalType returns the type of a community pool withdraw proposal. -func (cdp *CommunityPoolWithdrawProposal) ProposalType() string { - return ProposalTypeCommunityPoolWithdraw -} - -// String implements fmt.Stringer -func (cdp *CommunityPoolWithdrawProposal) String() string { - - var b strings.Builder - b.WriteString(fmt.Sprintf(`Community Pool Withdraw Proposal: - Title: %s - Description: %s - Amount: %s -`, cdp.Title, cdp.Description, cdp.Amount)) - return b.String() -} - -// ValidateBasic stateless validation of a community pool multi-spend proposal. -func (cdp *CommunityPoolWithdrawProposal) ValidateBasic() error { - err := govv1beta1.ValidateAbstract(cdp) - if err != nil { - return err - } - return cdp.Amount.Validate() -} diff --git a/x/earn/types/proposal.pb.go b/x/earn/types/proposal.pb.go deleted file mode 100644 index 8228d76b..00000000 --- a/x/earn/types/proposal.pb.go +++ /dev/null @@ -1,1285 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/earn/v1beta1/proposal.proto - -package types - -import ( - fmt "fmt" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// CommunityPoolDepositProposal deposits from the community pool into an earn vault -type CommunityPoolDepositProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *CommunityPoolDepositProposal) Reset() { *m = CommunityPoolDepositProposal{} } -func (*CommunityPoolDepositProposal) ProtoMessage() {} -func (*CommunityPoolDepositProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_c374f1a8c57e13e2, []int{0} -} -func (m *CommunityPoolDepositProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityPoolDepositProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityPoolDepositProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CommunityPoolDepositProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityPoolDepositProposal.Merge(m, src) -} -func (m *CommunityPoolDepositProposal) XXX_Size() int { - return m.Size() -} -func (m *CommunityPoolDepositProposal) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityPoolDepositProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityPoolDepositProposal proto.InternalMessageInfo - -// CommunityPoolDepositProposalJSON defines a CommunityPoolDepositProposal with a deposit -type CommunityPoolDepositProposalJSON struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` - Deposit github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,4,rep,name=deposit,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"deposit"` -} - -func (m *CommunityPoolDepositProposalJSON) Reset() { *m = CommunityPoolDepositProposalJSON{} } -func (m *CommunityPoolDepositProposalJSON) String() string { return proto.CompactTextString(m) } -func (*CommunityPoolDepositProposalJSON) ProtoMessage() {} -func (*CommunityPoolDepositProposalJSON) Descriptor() ([]byte, []int) { - return fileDescriptor_c374f1a8c57e13e2, []int{1} -} -func (m *CommunityPoolDepositProposalJSON) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityPoolDepositProposalJSON) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityPoolDepositProposalJSON.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CommunityPoolDepositProposalJSON) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityPoolDepositProposalJSON.Merge(m, src) -} -func (m *CommunityPoolDepositProposalJSON) XXX_Size() int { - return m.Size() -} -func (m *CommunityPoolDepositProposalJSON) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityPoolDepositProposalJSON.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityPoolDepositProposalJSON proto.InternalMessageInfo - -// CommunityPoolWithdrawProposal withdraws from an earn vault back to community pool -type CommunityPoolWithdrawProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *CommunityPoolWithdrawProposal) Reset() { *m = CommunityPoolWithdrawProposal{} } -func (*CommunityPoolWithdrawProposal) ProtoMessage() {} -func (*CommunityPoolWithdrawProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_c374f1a8c57e13e2, []int{2} -} -func (m *CommunityPoolWithdrawProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityPoolWithdrawProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityPoolWithdrawProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CommunityPoolWithdrawProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityPoolWithdrawProposal.Merge(m, src) -} -func (m *CommunityPoolWithdrawProposal) XXX_Size() int { - return m.Size() -} -func (m *CommunityPoolWithdrawProposal) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityPoolWithdrawProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityPoolWithdrawProposal proto.InternalMessageInfo - -// CommunityPoolWithdrawProposalJSON defines a CommunityPoolWithdrawProposal with a deposit -type CommunityPoolWithdrawProposalJSON struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` - Deposit github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,4,rep,name=deposit,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"deposit"` -} - -func (m *CommunityPoolWithdrawProposalJSON) Reset() { *m = CommunityPoolWithdrawProposalJSON{} } -func (m *CommunityPoolWithdrawProposalJSON) String() string { return proto.CompactTextString(m) } -func (*CommunityPoolWithdrawProposalJSON) ProtoMessage() {} -func (*CommunityPoolWithdrawProposalJSON) Descriptor() ([]byte, []int) { - return fileDescriptor_c374f1a8c57e13e2, []int{3} -} -func (m *CommunityPoolWithdrawProposalJSON) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityPoolWithdrawProposalJSON) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityPoolWithdrawProposalJSON.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CommunityPoolWithdrawProposalJSON) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityPoolWithdrawProposalJSON.Merge(m, src) -} -func (m *CommunityPoolWithdrawProposalJSON) XXX_Size() int { - return m.Size() -} -func (m *CommunityPoolWithdrawProposalJSON) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityPoolWithdrawProposalJSON.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityPoolWithdrawProposalJSON proto.InternalMessageInfo - -func init() { - proto.RegisterType((*CommunityPoolDepositProposal)(nil), "kava.earn.v1beta1.CommunityPoolDepositProposal") - proto.RegisterType((*CommunityPoolDepositProposalJSON)(nil), "kava.earn.v1beta1.CommunityPoolDepositProposalJSON") - proto.RegisterType((*CommunityPoolWithdrawProposal)(nil), "kava.earn.v1beta1.CommunityPoolWithdrawProposal") - proto.RegisterType((*CommunityPoolWithdrawProposalJSON)(nil), "kava.earn.v1beta1.CommunityPoolWithdrawProposalJSON") -} - -func init() { proto.RegisterFile("kava/earn/v1beta1/proposal.proto", fileDescriptor_c374f1a8c57e13e2) } - -var fileDescriptor_c374f1a8c57e13e2 = []byte{ - // 376 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xc8, 0x4e, 0x2c, 0x4b, - 0xd4, 0x4f, 0x4d, 0x2c, 0xca, 0xd3, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x2f, 0x28, - 0xca, 0x2f, 0xc8, 0x2f, 0x4e, 0xcc, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x04, 0xa9, - 0xd0, 0x03, 0xa9, 0xd0, 0x83, 0xaa, 0x90, 0x92, 0x4b, 0xce, 0x2f, 0xce, 0xcd, 0x2f, 0xd6, 0x4f, - 0x4a, 0x2c, 0x4e, 0x85, 0x6b, 0x4b, 0xce, 0xcf, 0xcc, 0x83, 0x68, 0x91, 0x12, 0x49, 0xcf, 0x4f, - 0xcf, 0x07, 0x33, 0xf5, 0x41, 0x2c, 0x88, 0xa8, 0xd2, 0x4c, 0x46, 0x2e, 0x19, 0xe7, 0xfc, 0xdc, - 0xdc, 0xd2, 0xbc, 0xcc, 0x92, 0xca, 0x80, 0xfc, 0xfc, 0x1c, 0x97, 0xd4, 0x82, 0xfc, 0xe2, 0xcc, - 0x92, 0x00, 0xa8, 0x7d, 0x42, 0x22, 0x5c, 0xac, 0x25, 0x99, 0x25, 0x39, 0xa9, 0x12, 0x8c, 0x0a, - 0x8c, 0x1a, 0x9c, 0x41, 0x10, 0x8e, 0x90, 0x02, 0x17, 0x77, 0x4a, 0x6a, 0x71, 0x72, 0x51, 0x66, - 0x41, 0x49, 0x66, 0x7e, 0x9e, 0x04, 0x13, 0x58, 0x0e, 0x59, 0x48, 0xc8, 0x9c, 0x8b, 0x2d, 0x31, - 0x37, 0xbf, 0x34, 0xaf, 0x44, 0x82, 0x59, 0x81, 0x51, 0x83, 0xdb, 0x48, 0x52, 0x0f, 0xe2, 0x3e, - 0x3d, 0x90, 0xfb, 0x60, 0x8e, 0xd6, 0x73, 0xce, 0xcf, 0xcc, 0x73, 0x62, 0x39, 0x71, 0x4f, 0x9e, - 0x21, 0x08, 0xaa, 0xdc, 0x8a, 0xa3, 0x63, 0x81, 0x3c, 0xc3, 0x8c, 0x05, 0xf2, 0x0c, 0x4a, 0x2d, - 0x4c, 0x5c, 0x0a, 0xf8, 0xdc, 0xe6, 0x15, 0xec, 0xef, 0x47, 0x77, 0xf7, 0x09, 0xa5, 0x72, 0xb1, - 0xa7, 0x40, 0xdc, 0x21, 0xc1, 0xa2, 0xc0, 0x8c, 0x5f, 0xa7, 0x01, 0x48, 0xe7, 0xaa, 0xfb, 0xf2, - 0x1a, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0xd0, 0x68, 0x82, 0x50, - 0xba, 0xc5, 0x29, 0xd9, 0xfa, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x60, 0x0d, 0xc5, 0x41, 0x30, 0xb3, - 0xe1, 0xc1, 0xc0, 0xa8, 0x34, 0x8b, 0x91, 0x4b, 0x16, 0x25, 0x18, 0xc2, 0x33, 0x4b, 0x32, 0x52, - 0x8a, 0x12, 0xcb, 0x07, 0x43, 0x1c, 0xb5, 0x32, 0x71, 0x29, 0xe2, 0x75, 0xdc, 0xc8, 0x88, 0x24, - 0x27, 0xc7, 0x13, 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, - 0x63, 0x39, 0x86, 0x0b, 0x8f, 0xe5, 0x18, 0x6e, 0x3c, 0x96, 0x63, 0x88, 0x52, 0x47, 0x32, 0xd6, - 0x20, 0x3d, 0x27, 0x31, 0xa9, 0x58, 0xdf, 0x20, 0x5d, 0x37, 0x39, 0x23, 0x31, 0x33, 0x4f, 0xbf, - 0x02, 0x92, 0xc9, 0xc1, 0x66, 0x27, 0xb1, 0x81, 0x73, 0xa4, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, - 0xdc, 0x8a, 0x33, 0x31, 0xfe, 0x03, 0x00, 0x00, -} - -func (m *CommunityPoolDepositProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CommunityPoolDepositProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityPoolDepositProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CommunityPoolDepositProposalJSON) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CommunityPoolDepositProposalJSON) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityPoolDepositProposalJSON) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Deposit) > 0 { - for iNdEx := len(m.Deposit) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposit[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CommunityPoolWithdrawProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CommunityPoolWithdrawProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityPoolWithdrawProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CommunityPoolWithdrawProposalJSON) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CommunityPoolWithdrawProposalJSON) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityPoolWithdrawProposalJSON) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Deposit) > 0 { - for iNdEx := len(m.Deposit) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposit[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintProposal(dAtA []byte, offset int, v uint64) int { - offset -= sovProposal(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *CommunityPoolDepositProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovProposal(uint64(l)) - return n -} - -func (m *CommunityPoolDepositProposalJSON) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovProposal(uint64(l)) - if len(m.Deposit) > 0 { - for _, e := range m.Deposit { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func (m *CommunityPoolWithdrawProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovProposal(uint64(l)) - return n -} - -func (m *CommunityPoolWithdrawProposalJSON) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovProposal(uint64(l)) - if len(m.Deposit) > 0 { - for _, e := range m.Deposit { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func sovProposal(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozProposal(x uint64) (n int) { - return sovProposal(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *CommunityPoolDepositProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CommunityPoolDepositProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityPoolDepositProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommunityPoolDepositProposalJSON) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CommunityPoolDepositProposalJSON: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityPoolDepositProposalJSON: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposit", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Deposit = append(m.Deposit, types.Coin{}) - if err := m.Deposit[len(m.Deposit)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommunityPoolWithdrawProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CommunityPoolWithdrawProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityPoolWithdrawProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommunityPoolWithdrawProposalJSON) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CommunityPoolWithdrawProposalJSON: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityPoolWithdrawProposalJSON: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposit", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Deposit = append(m.Deposit, types.Coin{}) - if err := m.Deposit[len(m.Deposit)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipProposal(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProposal - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProposal - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProposal - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthProposal - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupProposal - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthProposal - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthProposal = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowProposal = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupProposal = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/earn/types/query.go b/x/earn/types/query.go deleted file mode 100644 index 5bc93996..00000000 --- a/x/earn/types/query.go +++ /dev/null @@ -1,35 +0,0 @@ -package types - -import "github.com/cosmos/cosmos-sdk/types/query" - -// NewQueryParamsRequest returns a new QueryParamsRequest -func NewQueryParamsRequest() *QueryParamsRequest { - return &QueryParamsRequest{} -} - -// NewQueryVaultsRequest returns a new QueryVaultsRequest -func NewQueryVaultsRequest() *QueryVaultsRequest { - return &QueryVaultsRequest{} -} - -// NewQueryVaultRequest returns a new QueryVaultRequest -func NewQueryVaultRequest(denom string) *QueryVaultRequest { - return &QueryVaultRequest{ - Denom: denom, - } -} - -// NewQueryDepositsRequest returns a new QueryDepositsRequest -func NewQueryDepositsRequest( - depositor string, - denom string, - ValueInStakedTokens bool, - pagination *query.PageRequest, -) *QueryDepositsRequest { - return &QueryDepositsRequest{ - Depositor: depositor, - Denom: denom, - ValueInStakedTokens: ValueInStakedTokens, - Pagination: pagination, - } -} diff --git a/x/earn/types/query.pb.go b/x/earn/types/query.pb.go deleted file mode 100644 index f9534c12..00000000 --- a/x/earn/types/query.pb.go +++ /dev/null @@ -1,2932 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/earn/v1beta1/query.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - query "github.com/cosmos/cosmos-sdk/types/query" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// QueryParamsRequest defines the request type for querying x/earn parameters. -type QueryParamsRequest struct { -} - -func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } -func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryParamsRequest) ProtoMessage() {} -func (*QueryParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{0} -} -func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsRequest.Merge(m, src) -} -func (m *QueryParamsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo - -// QueryParamsResponse defines the response type for querying x/earn parameters. -type QueryParamsResponse struct { - // params represents the earn module parameters - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` -} - -func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } -func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryParamsResponse) ProtoMessage() {} -func (*QueryParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{1} -} -func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsResponse.Merge(m, src) -} -func (m *QueryParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo - -// QueryVaultsRequest is the request type for the Query/Vaults RPC method. -type QueryVaultsRequest struct { -} - -func (m *QueryVaultsRequest) Reset() { *m = QueryVaultsRequest{} } -func (m *QueryVaultsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryVaultsRequest) ProtoMessage() {} -func (*QueryVaultsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{2} -} -func (m *QueryVaultsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryVaultsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryVaultsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryVaultsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryVaultsRequest.Merge(m, src) -} -func (m *QueryVaultsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryVaultsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryVaultsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryVaultsRequest proto.InternalMessageInfo - -// QueryVaultsResponse is the response type for the Query/Vaults RPC method. -type QueryVaultsResponse struct { - // vaults represents the earn module vaults - Vaults []VaultResponse `protobuf:"bytes,1,rep,name=vaults,proto3" json:"vaults"` -} - -func (m *QueryVaultsResponse) Reset() { *m = QueryVaultsResponse{} } -func (m *QueryVaultsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryVaultsResponse) ProtoMessage() {} -func (*QueryVaultsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{3} -} -func (m *QueryVaultsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryVaultsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryVaultsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryVaultsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryVaultsResponse.Merge(m, src) -} -func (m *QueryVaultsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryVaultsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryVaultsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryVaultsResponse proto.InternalMessageInfo - -// QueryVaultRequest is the request type for the Query/Vault RPC method. -type QueryVaultRequest struct { - // vault filters vault by denom - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` -} - -func (m *QueryVaultRequest) Reset() { *m = QueryVaultRequest{} } -func (m *QueryVaultRequest) String() string { return proto.CompactTextString(m) } -func (*QueryVaultRequest) ProtoMessage() {} -func (*QueryVaultRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{4} -} -func (m *QueryVaultRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryVaultRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryVaultRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryVaultRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryVaultRequest.Merge(m, src) -} -func (m *QueryVaultRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryVaultRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryVaultRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryVaultRequest proto.InternalMessageInfo - -// QueryVaultResponse is the response type for the Query/Vault RPC method. -type QueryVaultResponse struct { - // vault represents the queried earn module vault - Vault VaultResponse `protobuf:"bytes,1,opt,name=vault,proto3" json:"vault"` -} - -func (m *QueryVaultResponse) Reset() { *m = QueryVaultResponse{} } -func (m *QueryVaultResponse) String() string { return proto.CompactTextString(m) } -func (*QueryVaultResponse) ProtoMessage() {} -func (*QueryVaultResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{5} -} -func (m *QueryVaultResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryVaultResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryVaultResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryVaultResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryVaultResponse.Merge(m, src) -} -func (m *QueryVaultResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryVaultResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryVaultResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryVaultResponse proto.InternalMessageInfo - -// VaultResponse is the response type for a vault. -type VaultResponse struct { - // denom represents the denom of the vault - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - // VaultStrategy is the strategy used for this vault. - Strategies StrategyTypes `protobuf:"varint,2,rep,packed,name=strategies,proto3,enum=kava.earn.v1beta1.StrategyType,castrepeated=StrategyTypes" json:"strategies,omitempty"` - // IsPrivateVault is true if the vault only allows depositors contained in - // AllowedDepositors. - IsPrivateVault bool `protobuf:"varint,3,opt,name=is_private_vault,json=isPrivateVault,proto3" json:"is_private_vault,omitempty"` - // AllowedDepositors is a list of addresses that are allowed to deposit to - // this vault if IsPrivateVault is true. Addresses not contained in this list - // are not allowed to deposit into this vault. If IsPrivateVault is false, - // this should be empty and ignored. - AllowedDepositors []string `protobuf:"bytes,4,rep,name=allowed_depositors,json=allowedDepositors,proto3" json:"allowed_depositors,omitempty"` - // TotalShares is the total amount of shares issued to depositors. - TotalShares string `protobuf:"bytes,5,opt,name=total_shares,json=totalShares,proto3" json:"total_shares,omitempty"` - // TotalValue is the total value of denom coins supplied to the vault if the - // vault were to be liquidated. - TotalValue github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,6,opt,name=total_value,json=totalValue,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"total_value"` -} - -func (m *VaultResponse) Reset() { *m = VaultResponse{} } -func (m *VaultResponse) String() string { return proto.CompactTextString(m) } -func (*VaultResponse) ProtoMessage() {} -func (*VaultResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{6} -} -func (m *VaultResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *VaultResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_VaultResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *VaultResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_VaultResponse.Merge(m, src) -} -func (m *VaultResponse) XXX_Size() int { - return m.Size() -} -func (m *VaultResponse) XXX_DiscardUnknown() { - xxx_messageInfo_VaultResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_VaultResponse proto.InternalMessageInfo - -// QueryDepositsRequest is the request type for the Query/Deposits RPC method. -type QueryDepositsRequest struct { - // depositor optionally filters deposits by depositor - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - // denom optionally filters deposits by vault denom - Denom string `protobuf:"bytes,2,opt,name=denom,proto3" json:"denom,omitempty"` - // respond with vault value in ukava for bkava vaults - ValueInStakedTokens bool `protobuf:"varint,3,opt,name=value_in_staked_tokens,json=valueInStakedTokens,proto3" json:"value_in_staked_tokens,omitempty"` - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,4,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDepositsRequest) Reset() { *m = QueryDepositsRequest{} } -func (m *QueryDepositsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsRequest) ProtoMessage() {} -func (*QueryDepositsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{7} -} -func (m *QueryDepositsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryDepositsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsRequest.Merge(m, src) -} -func (m *QueryDepositsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsRequest proto.InternalMessageInfo - -// QueryDepositsResponse is the response type for the Query/Deposits RPC method. -type QueryDepositsResponse struct { - // deposits returns the deposits matching the requested parameters - Deposits []DepositResponse `protobuf:"bytes,1,rep,name=deposits,proto3" json:"deposits"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDepositsResponse) Reset() { *m = QueryDepositsResponse{} } -func (m *QueryDepositsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsResponse) ProtoMessage() {} -func (*QueryDepositsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{8} -} -func (m *QueryDepositsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryDepositsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsResponse.Merge(m, src) -} -func (m *QueryDepositsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsResponse proto.InternalMessageInfo - -// DepositResponse defines a deposit query response type. -type DepositResponse struct { - // depositor represents the owner of the deposit. - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - // Shares represent the issued shares from their corresponding vaults. - Shares VaultShares `protobuf:"bytes,2,rep,name=shares,proto3,castrepeated=VaultShares" json:"shares"` - // Value represents the total accumulated value of denom coins supplied to - // vaults. This may be greater than or equal to amount_supplied depending on - // the strategy. - Value github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,3,rep,name=value,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"value"` -} - -func (m *DepositResponse) Reset() { *m = DepositResponse{} } -func (m *DepositResponse) String() string { return proto.CompactTextString(m) } -func (*DepositResponse) ProtoMessage() {} -func (*DepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{9} -} -func (m *DepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DepositResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *DepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_DepositResponse.Merge(m, src) -} -func (m *DepositResponse) XXX_Size() int { - return m.Size() -} -func (m *DepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_DepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_DepositResponse proto.InternalMessageInfo - -// QueryTotalSupplyRequest defines the request type for Query/TotalSupply method. -type QueryTotalSupplyRequest struct { -} - -func (m *QueryTotalSupplyRequest) Reset() { *m = QueryTotalSupplyRequest{} } -func (m *QueryTotalSupplyRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalSupplyRequest) ProtoMessage() {} -func (*QueryTotalSupplyRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{10} -} -func (m *QueryTotalSupplyRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalSupplyRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalSupplyRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTotalSupplyRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalSupplyRequest.Merge(m, src) -} -func (m *QueryTotalSupplyRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalSupplyRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalSupplyRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalSupplyRequest proto.InternalMessageInfo - -// TotalSupplyResponse defines the response type for the Query/TotalSupply method. -type QueryTotalSupplyResponse struct { - // Height is the block height at which these totals apply - Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` - // Result is a list of coins supplied to earn - Result github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=result,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"result"` -} - -func (m *QueryTotalSupplyResponse) Reset() { *m = QueryTotalSupplyResponse{} } -func (m *QueryTotalSupplyResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalSupplyResponse) ProtoMessage() {} -func (*QueryTotalSupplyResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63f8dee2f3192a6b, []int{11} -} -func (m *QueryTotalSupplyResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalSupplyResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalSupplyResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTotalSupplyResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalSupplyResponse.Merge(m, src) -} -func (m *QueryTotalSupplyResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalSupplyResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalSupplyResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalSupplyResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.earn.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.earn.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryVaultsRequest)(nil), "kava.earn.v1beta1.QueryVaultsRequest") - proto.RegisterType((*QueryVaultsResponse)(nil), "kava.earn.v1beta1.QueryVaultsResponse") - proto.RegisterType((*QueryVaultRequest)(nil), "kava.earn.v1beta1.QueryVaultRequest") - proto.RegisterType((*QueryVaultResponse)(nil), "kava.earn.v1beta1.QueryVaultResponse") - proto.RegisterType((*VaultResponse)(nil), "kava.earn.v1beta1.VaultResponse") - proto.RegisterType((*QueryDepositsRequest)(nil), "kava.earn.v1beta1.QueryDepositsRequest") - proto.RegisterType((*QueryDepositsResponse)(nil), "kava.earn.v1beta1.QueryDepositsResponse") - proto.RegisterType((*DepositResponse)(nil), "kava.earn.v1beta1.DepositResponse") - proto.RegisterType((*QueryTotalSupplyRequest)(nil), "kava.earn.v1beta1.QueryTotalSupplyRequest") - proto.RegisterType((*QueryTotalSupplyResponse)(nil), "kava.earn.v1beta1.QueryTotalSupplyResponse") -} - -func init() { proto.RegisterFile("kava/earn/v1beta1/query.proto", fileDescriptor_63f8dee2f3192a6b) } - -var fileDescriptor_63f8dee2f3192a6b = []byte{ - // 977 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x56, 0xcf, 0x6f, 0x1b, 0x45, - 0x14, 0xf6, 0xda, 0xb1, 0x95, 0x3c, 0xd3, 0x42, 0x26, 0xa6, 0xd8, 0x2e, 0x59, 0x3b, 0x4b, 0x9b, - 0x98, 0x40, 0x76, 0xd3, 0x54, 0x82, 0x4b, 0x41, 0xc2, 0x14, 0xaa, 0x70, 0x40, 0x65, 0x13, 0x7a, - 0x40, 0x42, 0xd6, 0xd8, 0x1e, 0xad, 0x57, 0x71, 0x76, 0xb6, 0x3b, 0x63, 0x43, 0x40, 0x5c, 0xfa, - 0x0f, 0x80, 0xc4, 0x81, 0x03, 0x77, 0x0e, 0x3d, 0xf7, 0x8f, 0xc8, 0xb1, 0x2a, 0x17, 0xc4, 0xa1, - 0x25, 0x09, 0x67, 0xce, 0x1c, 0xd1, 0xfc, 0x58, 0x7b, 0x1d, 0xaf, 0xe3, 0x08, 0xf5, 0x64, 0xcf, - 0xfb, 0xf1, 0x7d, 0xdf, 0x9b, 0x79, 0xf3, 0x66, 0x61, 0xf5, 0x00, 0x0f, 0xb1, 0x43, 0x70, 0x14, - 0x38, 0xc3, 0x5b, 0x6d, 0xc2, 0xf1, 0x2d, 0xe7, 0xe1, 0x80, 0x44, 0x47, 0x76, 0x18, 0x51, 0x4e, - 0xd1, 0xb2, 0x70, 0xdb, 0xc2, 0x6d, 0x6b, 0x77, 0x75, 0xb3, 0x43, 0xd9, 0x21, 0x65, 0x4e, 0x1b, - 0x33, 0xa2, 0x62, 0x47, 0x99, 0x21, 0xf6, 0xfc, 0x00, 0x73, 0x9f, 0x06, 0x2a, 0xbd, 0x6a, 0x26, - 0x63, 0xe3, 0xa8, 0x0e, 0xf5, 0x63, 0x7f, 0x45, 0xf9, 0x5b, 0x72, 0xe5, 0xa8, 0x85, 0x76, 0x95, - 0x3c, 0xea, 0x51, 0x65, 0x17, 0xff, 0xb4, 0xf5, 0x4d, 0x8f, 0x52, 0xaf, 0x4f, 0x1c, 0x1c, 0xfa, - 0x0e, 0x0e, 0x02, 0xca, 0x25, 0x5b, 0x9c, 0x63, 0x4e, 0x17, 0x13, 0xe2, 0x08, 0x1f, 0xc6, 0xfe, - 0xfa, 0xb4, 0x9f, 0xf1, 0x08, 0x73, 0xe2, 0xe9, 0x7a, 0xab, 0x29, 0xdb, 0x31, 0xc4, 0x83, 0x3e, - 0x57, 0x6e, 0xab, 0x04, 0xe8, 0x0b, 0x51, 0xf1, 0x7d, 0x89, 0xea, 0x92, 0x87, 0x03, 0xc2, 0xb8, - 0xf5, 0x39, 0xac, 0x4c, 0x58, 0x59, 0x48, 0x03, 0x46, 0xd0, 0xfb, 0x50, 0x50, 0xec, 0x65, 0xa3, - 0x6e, 0x34, 0x8a, 0x3b, 0x15, 0x7b, 0x6a, 0x33, 0x6d, 0x95, 0xd2, 0x5c, 0x38, 0x7e, 0x5e, 0xcb, - 0xb8, 0x3a, 0x7c, 0xc4, 0xf2, 0x40, 0x30, 0x8f, 0x58, 0xbe, 0xd4, 0x2c, 0xb1, 0x55, 0xb3, 0x7c, - 0x08, 0x05, 0xa9, 0x50, 0xb0, 0xe4, 0x1a, 0xc5, 0x9d, 0x7a, 0x0a, 0x8b, 0x4c, 0x89, 0x33, 0x62, - 0x32, 0x95, 0x65, 0xbd, 0x0d, 0xcb, 0x63, 0x58, 0xcd, 0x85, 0x4a, 0x90, 0xef, 0x92, 0x80, 0x1e, - 0x4a, 0xe5, 0x4b, 0xae, 0x5a, 0x58, 0x6e, 0x52, 0xd7, 0x48, 0xc0, 0x1d, 0xc8, 0x4b, 0x28, 0x5d, - 0xe5, 0x65, 0xf9, 0x55, 0x92, 0xf5, 0x4f, 0x16, 0xae, 0x4c, 0xe2, 0xa5, 0x72, 0x23, 0x17, 0x40, - 0x1f, 0x95, 0x4f, 0x58, 0x39, 0x5b, 0xcf, 0x35, 0xae, 0xee, 0xd4, 0x52, 0xa8, 0xf6, 0xf4, 0x79, - 0xee, 0x1f, 0x85, 0xa4, 0xb9, 0xfc, 0xf8, 0x45, 0xed, 0x4a, 0xd2, 0xc2, 0xdc, 0x04, 0x0a, 0x6a, - 0xc0, 0x6b, 0xbe, 0xe8, 0x3d, 0x7f, 0x88, 0x39, 0x69, 0xa9, 0x22, 0x72, 0x75, 0xa3, 0xb1, 0xe8, - 0x5e, 0xf5, 0xd9, 0x7d, 0x65, 0x96, 0xda, 0xd0, 0x3d, 0x40, 0xb8, 0xdf, 0xa7, 0xdf, 0x90, 0x6e, - 0xab, 0x4b, 0x42, 0xca, 0x7c, 0x4e, 0x23, 0x56, 0x5e, 0xa8, 0xe7, 0x1a, 0x4b, 0xcd, 0xf2, 0xb3, - 0x27, 0x5b, 0x25, 0xdd, 0xba, 0x1f, 0x75, 0xbb, 0x11, 0x61, 0x6c, 0x8f, 0x47, 0x7e, 0xe0, 0xb9, - 0xcb, 0x3a, 0xe7, 0xee, 0x28, 0x05, 0xad, 0xc1, 0x2b, 0x9c, 0x72, 0xdc, 0x6f, 0xb1, 0x1e, 0x8e, - 0x08, 0x2b, 0xe7, 0x65, 0x8d, 0x45, 0x69, 0xdb, 0x93, 0x26, 0xf4, 0x35, 0xa8, 0x65, 0x6b, 0x88, - 0xfb, 0x03, 0x52, 0x2e, 0x88, 0x88, 0xe6, 0x1d, 0xb1, 0x67, 0x7f, 0x3e, 0xaf, 0xad, 0x7b, 0x3e, - 0xef, 0x0d, 0xda, 0x76, 0x87, 0x1e, 0xea, 0xeb, 0xa2, 0x7f, 0xb6, 0x58, 0xf7, 0xc0, 0xe1, 0xa2, - 0x44, 0x7b, 0x37, 0xe0, 0xcf, 0x9e, 0x6c, 0x81, 0x96, 0xb4, 0x1b, 0x70, 0x17, 0x24, 0xe0, 0x03, - 0x81, 0x67, 0x9d, 0x18, 0x50, 0x92, 0xa7, 0xa8, 0x55, 0xc5, 0xfd, 0x85, 0xde, 0x83, 0xa5, 0x51, - 0x6d, 0x6a, 0xef, 0x2f, 0x28, 0x6d, 0x1c, 0x3a, 0x3e, 0xaf, 0x6c, 0xf2, 0xbc, 0x6e, 0xc3, 0x35, - 0xa9, 0xbf, 0xe5, 0x07, 0x2d, 0xc6, 0xf1, 0x01, 0xe9, 0xb6, 0x38, 0x3d, 0x20, 0x01, 0xd3, 0x3b, - 0xbc, 0x22, 0xbd, 0xbb, 0xc1, 0x9e, 0xf4, 0xed, 0x4b, 0x17, 0xfa, 0x14, 0x60, 0x3c, 0x42, 0xca, - 0x0b, 0xb2, 0x9f, 0xd6, 0x6d, 0x2d, 0x40, 0xcc, 0x10, 0x5b, 0xcd, 0xa6, 0xf1, 0xed, 0xf1, 0x88, - 0x96, 0xef, 0x26, 0x32, 0xad, 0xdf, 0x0c, 0x78, 0xfd, 0x5c, 0x8d, 0xba, 0xb9, 0xee, 0xc2, 0xa2, - 0x56, 0x1e, 0xdf, 0x17, 0x2b, 0xa5, 0x89, 0x74, 0xda, 0xb9, 0x8e, 0x1d, 0x65, 0xa2, 0x7b, 0x13, - 0x3a, 0xb3, 0x52, 0xe7, 0xc6, 0x5c, 0x9d, 0x0a, 0x6c, 0x42, 0xe8, 0xbf, 0x06, 0xbc, 0x7a, 0x8e, - 0xec, 0x7f, 0x9f, 0xc3, 0x67, 0x50, 0xd0, 0x4d, 0x95, 0x95, 0x85, 0xad, 0xce, 0xba, 0x88, 0xb2, - 0xcf, 0x9a, 0x2b, 0xa2, 0xa6, 0xc7, 0x2f, 0x6a, 0xc5, 0xb1, 0x8d, 0xb9, 0x1a, 0x01, 0x61, 0x71, - 0xa7, 0x45, 0xf7, 0xe5, 0x24, 0x54, 0x65, 0xa2, 0xb6, 0x18, 0xec, 0x63, 0xea, 0x07, 0xcd, 0x6d, - 0x0d, 0xd3, 0xb8, 0x44, 0x63, 0x8a, 0x04, 0xe6, 0x2a, 0x64, 0xab, 0x02, 0x6f, 0xc8, 0x23, 0xda, - 0x97, 0xad, 0x3f, 0x08, 0xc3, 0xfe, 0x51, 0x3c, 0xe9, 0x7e, 0x31, 0xa0, 0x3c, 0xed, 0xd3, 0xdb, - 0x73, 0x0d, 0x0a, 0x3d, 0xe2, 0x7b, 0x3d, 0x35, 0x6f, 0x72, 0xae, 0x5e, 0xa1, 0x0e, 0x14, 0x22, - 0xc2, 0xc4, 0x15, 0xce, 0xbe, 0x7c, 0xcd, 0x1a, 0x7a, 0xe7, 0xd7, 0x3c, 0xe4, 0xa5, 0x32, 0xf4, - 0x1d, 0x14, 0xd4, 0xec, 0x46, 0x37, 0x53, 0xf6, 0x79, 0xfa, 0x91, 0xa8, 0xae, 0xcf, 0x0b, 0x53, - 0xf5, 0x59, 0x6b, 0x8f, 0x7e, 0xff, 0xfb, 0xe7, 0xec, 0x75, 0x54, 0x71, 0x66, 0x3d, 0x66, 0x82, - 0x5b, 0x3d, 0x02, 0xb3, 0xb9, 0x27, 0x9e, 0x8e, 0xd9, 0xdc, 0x93, 0x6f, 0xc9, 0x85, 0xdc, 0xea, - 0xb9, 0x40, 0x8f, 0x0c, 0xc8, 0xab, 0x99, 0x78, 0xe3, 0x42, 0xd0, 0x98, 0xfa, 0xe6, 0x9c, 0x28, - 0xcd, 0xfc, 0xae, 0x64, 0x5e, 0x47, 0x37, 0x66, 0x32, 0x3b, 0xdf, 0xcb, 0xc1, 0xf2, 0xc1, 0xe6, - 0xe6, 0x0f, 0x42, 0xc4, 0x62, 0x7c, 0xb5, 0xd1, 0xc6, 0x2c, 0x86, 0x73, 0x03, 0xae, 0xda, 0x98, - 0x1f, 0xa8, 0xd5, 0xbc, 0x25, 0xd5, 0xac, 0xa2, 0xeb, 0x29, 0x6a, 0x46, 0x43, 0xe0, 0x47, 0x03, - 0x8a, 0x89, 0x06, 0x45, 0x9b, 0xb3, 0xe0, 0xa7, 0x3b, 0xbc, 0xfa, 0xce, 0xa5, 0x62, 0xb5, 0x9a, - 0x0d, 0xa9, 0x66, 0x0d, 0xd5, 0x52, 0xd4, 0xe8, 0xc7, 0x44, 0x26, 0x34, 0x3f, 0x39, 0x3e, 0x31, - 0x33, 0xc7, 0xa7, 0xa6, 0xf1, 0xf4, 0xd4, 0x34, 0xfe, 0x3a, 0x35, 0x8d, 0x9f, 0xce, 0xcc, 0xcc, - 0xd3, 0x33, 0x33, 0xf3, 0xc7, 0x99, 0x99, 0xf9, 0x6a, 0x23, 0xd1, 0xed, 0xdb, 0x5e, 0x1f, 0xb7, - 0x99, 0xb3, 0xed, 0x6d, 0x75, 0x7a, 0xd8, 0x0f, 0x9c, 0x6f, 0x15, 0xaa, 0x6c, 0xf9, 0x76, 0x41, - 0x7e, 0xeb, 0xdc, 0xfe, 0x2f, 0x00, 0x00, 0xff, 0xff, 0x0f, 0x4d, 0xf0, 0x32, 0x1b, 0x0a, 0x00, - 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - // Params queries all parameters of the earn module. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Vaults queries all vaults - Vaults(ctx context.Context, in *QueryVaultsRequest, opts ...grpc.CallOption) (*QueryVaultsResponse, error) - // Vault queries a single vault based on the vault denom - Vault(ctx context.Context, in *QueryVaultRequest, opts ...grpc.CallOption) (*QueryVaultResponse, error) - // Deposits queries deposit details based on depositor address and vault - Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, error) - // TotalSupply returns the total sum of all coins currently locked into the earn module. - TotalSupply(ctx context.Context, in *QueryTotalSupplyRequest, opts ...grpc.CallOption) (*QueryTotalSupplyResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { - out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, "/kava.earn.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Vaults(ctx context.Context, in *QueryVaultsRequest, opts ...grpc.CallOption) (*QueryVaultsResponse, error) { - out := new(QueryVaultsResponse) - err := c.cc.Invoke(ctx, "/kava.earn.v1beta1.Query/Vaults", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Vault(ctx context.Context, in *QueryVaultRequest, opts ...grpc.CallOption) (*QueryVaultResponse, error) { - out := new(QueryVaultResponse) - err := c.cc.Invoke(ctx, "/kava.earn.v1beta1.Query/Vault", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, error) { - out := new(QueryDepositsResponse) - err := c.cc.Invoke(ctx, "/kava.earn.v1beta1.Query/Deposits", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalSupply(ctx context.Context, in *QueryTotalSupplyRequest, opts ...grpc.CallOption) (*QueryTotalSupplyResponse, error) { - out := new(QueryTotalSupplyResponse) - err := c.cc.Invoke(ctx, "/kava.earn.v1beta1.Query/TotalSupply", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries all parameters of the earn module. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Vaults queries all vaults - Vaults(context.Context, *QueryVaultsRequest) (*QueryVaultsResponse, error) - // Vault queries a single vault based on the vault denom - Vault(context.Context, *QueryVaultRequest) (*QueryVaultResponse, error) - // Deposits queries deposit details based on depositor address and vault - Deposits(context.Context, *QueryDepositsRequest) (*QueryDepositsResponse, error) - // TotalSupply returns the total sum of all coins currently locked into the earn module. - TotalSupply(context.Context, *QueryTotalSupplyRequest) (*QueryTotalSupplyResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") -} -func (*UnimplementedQueryServer) Vaults(ctx context.Context, req *QueryVaultsRequest) (*QueryVaultsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Vaults not implemented") -} -func (*UnimplementedQueryServer) Vault(ctx context.Context, req *QueryVaultRequest) (*QueryVaultResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Vault not implemented") -} -func (*UnimplementedQueryServer) Deposits(ctx context.Context, req *QueryDepositsRequest) (*QueryDepositsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposits not implemented") -} -func (*UnimplementedQueryServer) TotalSupply(ctx context.Context, req *QueryTotalSupplyRequest) (*QueryTotalSupplyResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalSupply not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryParamsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Params(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.earn.v1beta1.Query/Params", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Vaults_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryVaultsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Vaults(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.earn.v1beta1.Query/Vaults", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Vaults(ctx, req.(*QueryVaultsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Vault_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryVaultRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Vault(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.earn.v1beta1.Query/Vault", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Vault(ctx, req.(*QueryVaultRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Deposits_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryDepositsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Deposits(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.earn.v1beta1.Query/Deposits", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Deposits(ctx, req.(*QueryDepositsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalSupply_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalSupplyRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalSupply(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.earn.v1beta1.Query/TotalSupply", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalSupply(ctx, req.(*QueryTotalSupplyRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.earn.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Vaults", - Handler: _Query_Vaults_Handler, - }, - { - MethodName: "Vault", - Handler: _Query_Vault_Handler, - }, - { - MethodName: "Deposits", - Handler: _Query_Deposits_Handler, - }, - { - MethodName: "TotalSupply", - Handler: _Query_TotalSupply_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/earn/v1beta1/query.proto", -} - -func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryVaultsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryVaultsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryVaultsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryVaultsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryVaultsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryVaultsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Vaults) > 0 { - for iNdEx := len(m.Vaults) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Vaults[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryVaultRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryVaultRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryVaultRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryVaultResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryVaultResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryVaultResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Vault.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *VaultResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *VaultResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *VaultResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.TotalValue.Size() - i -= size - if _, err := m.TotalValue.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - if len(m.TotalShares) > 0 { - i -= len(m.TotalShares) - copy(dAtA[i:], m.TotalShares) - i = encodeVarintQuery(dAtA, i, uint64(len(m.TotalShares))) - i-- - dAtA[i] = 0x2a - } - if len(m.AllowedDepositors) > 0 { - for iNdEx := len(m.AllowedDepositors) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.AllowedDepositors[iNdEx]) - copy(dAtA[i:], m.AllowedDepositors[iNdEx]) - i = encodeVarintQuery(dAtA, i, uint64(len(m.AllowedDepositors[iNdEx]))) - i-- - dAtA[i] = 0x22 - } - } - if m.IsPrivateVault { - i-- - if m.IsPrivateVault { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x18 - } - if len(m.Strategies) > 0 { - dAtA4 := make([]byte, len(m.Strategies)*10) - var j3 int - for _, num := range m.Strategies { - for num >= 1<<7 { - dAtA4[j3] = uint8(uint64(num)&0x7f | 0x80) - num >>= 7 - j3++ - } - dAtA4[j3] = uint8(num) - j3++ - } - i -= j3 - copy(dAtA[i:], dAtA4[:j3]) - i = encodeVarintQuery(dAtA, i, uint64(j3)) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDepositsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryDepositsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - if m.ValueInStakedTokens { - i-- - if m.ValueInStakedTokens { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x18 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0x12 - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDepositsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryDepositsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Deposits) > 0 { - for iNdEx := len(m.Deposits) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposits[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *DepositResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *DepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Value) > 0 { - for iNdEx := len(m.Value) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Value[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Shares) > 0 { - for iNdEx := len(m.Shares) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Shares[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalSupplyRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryTotalSupplyRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalSupplyRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryTotalSupplyResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryTotalSupplyResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalSupplyResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Result) > 0 { - for iNdEx := len(m.Result) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Result[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if m.Height != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.Height)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryParamsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryVaultsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryVaultsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Vaults) > 0 { - for _, e := range m.Vaults { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryVaultRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryVaultResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Vault.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *VaultResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.Strategies) > 0 { - l = 0 - for _, e := range m.Strategies { - l += sovQuery(uint64(e)) - } - n += 1 + sovQuery(uint64(l)) + l - } - if m.IsPrivateVault { - n += 2 - } - if len(m.AllowedDepositors) > 0 { - for _, s := range m.AllowedDepositors { - l = len(s) - n += 1 + l + sovQuery(uint64(l)) - } - } - l = len(m.TotalShares) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = m.TotalValue.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryDepositsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.ValueInStakedTokens { - n += 2 - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDepositsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Deposits) > 0 { - for _, e := range m.Deposits { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *DepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.Shares) > 0 { - for _, e := range m.Shares { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.Value) > 0 { - for _, e := range m.Value { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryTotalSupplyRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryTotalSupplyResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Height != 0 { - n += 1 + sovQuery(uint64(m.Height)) - } - if len(m.Result) > 0 { - for _, e := range m.Result { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryVaultsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryVaultsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryVaultsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryVaultsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryVaultsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryVaultsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Vaults", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Vaults = append(m.Vaults, VaultResponse{}) - if err := m.Vaults[len(m.Vaults)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryVaultRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryVaultRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryVaultRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryVaultResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryVaultResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryVaultResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Vault", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Vault.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *VaultResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: VaultResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: VaultResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType == 0 { - var v StrategyType - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= StrategyType(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Strategies = append(m.Strategies, v) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - if elementCount != 0 && len(m.Strategies) == 0 { - m.Strategies = make([]StrategyType, 0, elementCount) - } - for iNdEx < postIndex { - var v StrategyType - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= StrategyType(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Strategies = append(m.Strategies, v) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field Strategies", wireType) - } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field IsPrivateVault", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.IsPrivateVault = bool(v != 0) - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AllowedDepositors", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.AllowedDepositors = append(m.AllowedDepositors, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalShares", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TotalShares = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalValue", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TotalValue.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDepositsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryDepositsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ValueInStakedTokens", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.ValueInStakedTokens = bool(v != 0) - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDepositsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryDepositsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposits", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Deposits = append(m.Deposits, DepositResponse{}) - if err := m.Deposits[len(m.Deposits)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DepositResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Shares", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Shares = append(m.Shares, VaultShare{}) - if err := m.Shares[len(m.Shares)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Value = append(m.Value, types.Coin{}) - if err := m.Value[len(m.Value)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTotalSupplyRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTotalSupplyRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalSupplyRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTotalSupplyResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTotalSupplyResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalSupplyResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) - } - m.Height = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Height |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Result = append(m.Result, types.Coin{}) - if err := m.Result[len(m.Result)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/earn/types/query.pb.gw.go b/x/earn/types/query.pb.gw.go deleted file mode 100644 index 408bd2a3..00000000 --- a/x/earn/types/query.pb.gw.go +++ /dev/null @@ -1,467 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/earn/v1beta1/query.proto - -/* -Package types is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package types - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join - -func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Params(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Vaults_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryVaultsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Vaults(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Vaults_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryVaultsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Vaults(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Vault_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryVaultRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["denom"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "denom") - } - - protoReq.Denom, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "denom", err) - } - - msg, err := client.Vault(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Vault_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryVaultRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["denom"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "denom") - } - - protoReq.Denom, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "denom", err) - } - - msg, err := server.Vault(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Deposits_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Deposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Deposits(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Deposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Deposits(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_TotalSupply_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalSupplyRequest - var metadata runtime.ServerMetadata - - msg, err := client.TotalSupply(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TotalSupply_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalSupplyRequest - var metadata runtime.ServerMetadata - - msg, err := server.TotalSupply(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Vaults_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Vaults_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Vaults_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Vault_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Vault_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Vault_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Deposits_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Deposits_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Deposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalSupply_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_TotalSupply_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TotalSupply_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Vaults_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Vaults_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Vaults_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Vault_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Vault_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Vault_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Deposits_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Deposits_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Deposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalSupply_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_TotalSupply_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TotalSupply_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "earn", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Vaults_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "earn", "v1beta1", "vaults"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Vault_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 3, 0, 4, 1, 5, 4}, []string{"kava", "earn", "v1beta1", "vaults", "denom"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Deposits_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "earn", "v1beta1", "deposits"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TotalSupply_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "earn", "v1beta1", "total_supply"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Vaults_0 = runtime.ForwardResponseMessage - - forward_Query_Vault_0 = runtime.ForwardResponseMessage - - forward_Query_Deposits_0 = runtime.ForwardResponseMessage - - forward_Query_TotalSupply_0 = runtime.ForwardResponseMessage -) diff --git a/x/earn/types/share.go b/x/earn/types/share.go deleted file mode 100644 index 1e6d1531..00000000 --- a/x/earn/types/share.go +++ /dev/null @@ -1,383 +0,0 @@ -package types - -import ( - fmt "fmt" - "sort" - "strings" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// NewVaultShare returns a new VaultShare -func NewVaultShare(denom string, amount sdk.Dec) VaultShare { - share := VaultShare{ - Denom: denom, - Amount: amount, - } - - if err := share.Validate(); err != nil { - panic(err) - } - - return share -} - -// Validate returns an error if a VaultShare is invalid. -func (share VaultShare) Validate() error { - if err := sdk.ValidateDenom(share.Denom); err != nil { - return errorsmod.Wrap(ErrInvalidVaultDenom, err.Error()) - } - - if share.Amount.IsNil() { - return fmt.Errorf("nil share amount: %s", share.Amount) - } - - if share.Amount.IsNegative() { - return fmt.Errorf("vault share amount %v is negative", share.Amount) - } - - return nil -} - -// IsValid returns true if the VaultShare is valid -func (share VaultShare) IsValid() bool { - return share.Validate() == nil -} - -func (share VaultShare) IsPositive() bool { - return share.Amount.IsPositive() -} - -// Add adds amounts of two vault shares with same denom. If the shares differ in -// denom then it panics. -func (share VaultShare) Add(vsB VaultShare) VaultShare { - if share.Denom != vsB.Denom { - panic(fmt.Sprintf("invalid share denominations; %s, %s", share.Denom, vsB.Denom)) - } - - return NewVaultShare(share.Denom, share.Amount.Add(vsB.Amount)) -} - -// IsZero returns if this represents no shares -func (share VaultShare) IsZero() bool { - return share.Amount.IsZero() -} - -// IsNegative returns true if the share amount is negative and false otherwise. -func (share VaultShare) IsNegative() bool { - return share.Amount.IsNegative() -} - -// Sub subtracts amounts of two vault shares with same denom. If the shares -// differ in denom then it panics. -func (share VaultShare) Sub(vsB VaultShare) VaultShare { - if share.Denom != vsB.Denom { - panic(fmt.Sprintf("invalid share denominations; %s, %s", share.Denom, vsB.Denom)) - } - - res := NewVaultShare(share.Denom, share.Amount.Sub(vsB.Amount)) - if res.Amount.IsNegative() { - panic("negative share amount") - } - - return res -} - -func (share VaultShare) String() string { - return fmt.Sprintf("%v%v", share.Amount, share.Denom) -} - -// VaultShares is a slice of VaultShare. -type VaultShares []VaultShare - -// NewVaultShares returns new VaultShares -func NewVaultShares(shares ...VaultShare) VaultShares { - newVaultShares := sanitizeVaultShares(shares) - if err := newVaultShares.Validate(); err != nil { - panic(fmt.Errorf("invalid share set %s: %w", newVaultShares, err)) - } - - return newVaultShares -} - -func sanitizeVaultShares(shares VaultShares) VaultShares { - newVaultShares := removeZeroShares(shares) - if len(newVaultShares) == 0 { - return VaultShares{} - } - - return newVaultShares.Sort() -} - -// Validate returns an error if a slice of VaultShares is invalid. -func (shares VaultShares) Validate() error { - switch len(shares) { - case 0: - return nil - - case 1: - if err := sdk.ValidateDenom(shares[0].Denom); err != nil { - return err - } - if !shares[0].IsPositive() { - return fmt.Errorf("share %s amount is not positive", shares[0]) - } - return nil - default: - // check single share case - if err := (VaultShares{shares[0]}).Validate(); err != nil { - return err - } - - lowDenom := shares[0].Denom - seenDenoms := make(map[string]bool) - seenDenoms[lowDenom] = true - - for _, share := range shares[1:] { - if seenDenoms[share.Denom] { - return fmt.Errorf("duplicate denomination %s", share.Denom) - } - if err := sdk.ValidateDenom(share.Denom); err != nil { - return err - } - if share.Denom <= lowDenom { - return fmt.Errorf("denomination %s is not sorted", share.Denom) - } - if !share.IsPositive() { - return fmt.Errorf("share %s amount is not positive", share.Denom) - } - - // we compare each share against the last denom - lowDenom = share.Denom - seenDenoms[share.Denom] = true - } - - return nil - } -} - -// IsValid returns true if the VaultShares are valid -func (shares VaultShares) IsValid() bool { - return shares.Validate() == nil -} - -// Add adds two sets of VaultShares. -func (shares VaultShares) Add(sharesB ...VaultShare) VaultShares { - return shares.safeAdd(sharesB) -} - -// safeAdd will perform addition of two shares sets. If both share sets are -// empty, then an empty set is returned. If only a single set is empty, the -// other set is returned. Otherwise, the shares are compared in order of their -// denomination and addition only occurs when the denominations match, otherwise -// the share is simply added to the sum assuming it's not zero. -// The function panics if `shares` or `sharesB` are not sorted (ascending). -func (shares VaultShares) safeAdd(sharesB VaultShares) VaultShares { - // probably the best way will be to make Shares and interface and hide the structure - // definition (type alias) - if !shares.isSorted() { - panic("Shares (self) must be sorted") - } - if !sharesB.isSorted() { - panic("Wrong argument: shares must be sorted") - } - - sum := (VaultShares)(nil) - indexA, indexB := 0, 0 - lenA, lenB := len(shares), len(sharesB) - - for { - if indexA == lenA { - if indexB == lenB { - // return nil shares if both sets are empty - return sum - } - - // return set B (excluding zero shares) if set A is empty - return append(sum, removeZeroShares(sharesB[indexB:])...) - } else if indexB == lenB { - // return set A (excluding zero shares) if set B is empty - return append(sum, removeZeroShares(shares[indexA:])...) - } - - shareA, shareB := shares[indexA], sharesB[indexB] - - switch strings.Compare(shareA.Denom, shareB.Denom) { - case -1: // share A denom < share B denom - if !shareA.IsZero() { - sum = append(sum, shareA) - } - - indexA++ - - case 0: // share A denom == share B denom - res := shareA.Add(shareB) - if !res.IsZero() { - sum = append(sum, res) - } - - indexA++ - indexB++ - - case 1: // share A denom > share B denom - if !shareB.IsZero() { - sum = append(sum, shareB) - } - - indexB++ - } - } -} - -// Sub subtracts a set of shares from another. -// -// e.g. -// {2A, 3B} - {A} = {A, 3B} -// {2A} - {0B} = {2A} -// {A, B} - {A} = {B} -// -// CONTRACT: Sub will never return Shares where one Share has a non-positive -// amount. In otherwords, IsValid will always return true. -func (shares VaultShares) Sub(sharesB ...VaultShare) VaultShares { - diff, hasNeg := shares.SafeSub(sharesB) - if hasNeg { - panic("negative share amount") - } - - return diff -} - -// SafeSub performs the same arithmetic as Sub but returns a boolean if any -// negative share amount was returned. -// The function panics if `shares` or `sharesB` are not sorted (ascending). -func (shares VaultShares) SafeSub(sharesB VaultShares) (VaultShares, bool) { - diff := shares.safeAdd(sharesB.negative()) - return diff, diff.IsAnyNegative() -} - -// IsAnyNegative returns true if there is at least one share whose amount -// is negative; returns false otherwise. It returns false if the share set -// is empty too. -func (shares VaultShares) IsAnyNegative() bool { - for _, share := range shares { - if share.IsNegative() { - return true - } - } - - return false -} - -// negative returns a set of shares with all amount negative. -func (shares VaultShares) negative() VaultShares { - res := make(VaultShares, 0, len(shares)) - - for _, share := range shares { - res = append(res, VaultShare{ - Denom: share.Denom, - Amount: share.Amount.Neg(), - }) - } - - return res -} - -// AmountOf returns the amount of shares of the given denom. -func (shares VaultShares) AmountOf(denom string) sdk.Dec { - for _, s := range shares { - if s.Denom == denom { - return s.Amount - } - } - - return sdk.ZeroDec() -} - -// GetShare the single share of the given denom. -func (shares VaultShares) GetShare(denom string) VaultShare { - for _, s := range shares { - if s.Denom == denom { - return s - } - } - - return NewVaultShare(denom, sdk.ZeroDec()) -} - -// IsZero returns true if the VaultShares is empty. -func (shares VaultShares) IsZero() bool { - for _, s := range shares { - // If any amount is non-zero, false - if !s.Amount.IsZero() { - return false - } - } - - return true -} - -func (shares VaultShares) isSorted() bool { - for i := 1; i < len(shares); i++ { - if shares[i-1].Denom > shares[i].Denom { - return false - } - } - return true -} - -func (shares VaultShares) String() string { - if len(shares) == 0 { - return "" - } - - out := "" - for _, share := range shares { - out += fmt.Sprintf("%v,", share.String()) - } - - return out[:len(out)-1] -} - -// removeZeroShares removes all zero shares from the given share set in-place. -func removeZeroShares(shares VaultShares) VaultShares { - for i := 0; i < len(shares); i++ { - if shares[i].IsZero() { - break - } else if i == len(shares)-1 { - return shares - } - } - - var result VaultShares - if len(shares) > 0 { - result = make(VaultShares, 0, len(shares)-1) - } - - for _, share := range shares { - if !share.IsZero() { - result = append(result, share) - } - } - - return result -} - -// ---------------------------------------------------------------------------- -// VaultShares sort interface - -func (shares VaultShares) Len() int { return len(shares) } - -// Less implements sort.Interface for VaultShares -func (shares VaultShares) Less(i, j int) bool { return shares[i].Denom < shares[j].Denom } - -// Swap implements sort.Interface for VaultShares -func (shares VaultShares) Swap(i, j int) { shares[i], shares[j] = shares[j], shares[i] } - -var _ sort.Interface = VaultShares{} - -// Sort is a helper function to sort the set of vault shares in-place -func (shares VaultShares) Sort() VaultShares { - sort.Sort(shares) - return shares -} diff --git a/x/earn/types/share_test.go b/x/earn/types/share_test.go deleted file mode 100644 index 05287aee..00000000 --- a/x/earn/types/share_test.go +++ /dev/null @@ -1,446 +0,0 @@ -package types_test - -import ( - "strings" - "testing" - - "github.com/0glabs/0g-chain/x/earn/types" - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var ( - testDenom1 = "ukava" - testDenom2 = "usdx" -) - -func d(i int64) sdk.Dec { - return sdk.NewDec(i) -} - -type vaultShareTestSuite struct { - suite.Suite -} - -func TestVaultShareTestSuite(t *testing.T) { - suite.Run(t, new(vaultShareTestSuite)) -} - -func (s *vaultShareTestSuite) TestNewVaultShareFromDec() { - s.Require().NotPanics(func() { - types.NewVaultShare(testDenom1, sdk.NewDec(5)) - }) - s.Require().NotPanics(func() { - types.NewVaultShare(testDenom1, sdk.ZeroDec()) - }) - s.Require().NotPanics(func() { - types.NewVaultShare(strings.ToUpper(testDenom1), sdk.NewDec(5)) - }) - s.Require().Panics(func() { - types.NewVaultShare(testDenom1, sdk.NewDec(-5)) - }) -} - -func (s *vaultShareTestSuite) TestAddVaultShare() { - vaultShareA1 := types.NewVaultShare(testDenom1, sdk.NewDecWithPrec(11, 1)) - vaultShareA2 := types.NewVaultShare(testDenom1, sdk.NewDecWithPrec(22, 1)) - vaultShareB1 := types.NewVaultShare(testDenom2, sdk.NewDecWithPrec(11, 1)) - - // regular add - res := vaultShareA1.Add(vaultShareA1) - s.Require().Equal(vaultShareA2, res, "sum of shares is incorrect") - - // bad denom add - s.Require().Panics(func() { - vaultShareA1.Add(vaultShareB1) - }, "expected panic on sum of different denoms") -} - -func (s *vaultShareTestSuite) TestAddVaultShares() { - one := sdk.NewDec(1) - zero := sdk.NewDec(0) - two := sdk.NewDec(2) - - cases := []struct { - inputOne types.VaultShares - inputTwo types.VaultShares - expected types.VaultShares - }{ - { - types.VaultShares{ - {testDenom1, one}, - {testDenom2, one}, - }, - types.VaultShares{ - {testDenom1, one}, - {testDenom2, one}, - }, - types.VaultShares{ - {testDenom1, two}, - {testDenom2, two}, - }, - }, - { - types.VaultShares{ - {testDenom1, zero}, - {testDenom2, one}, - }, - types.VaultShares{ - {testDenom1, zero}, - {testDenom2, zero}, - }, - types.VaultShares{ - {testDenom2, one}, - }, - }, - { - types.VaultShares{ - {testDenom1, zero}, - {testDenom2, zero}, - }, - types.VaultShares{ - {testDenom1, zero}, - {testDenom2, zero}, - }, - types.VaultShares(nil), - }, - } - - for tcIndex, tc := range cases { - res := tc.inputOne.Add(tc.inputTwo...) - s.Require().Equal(tc.expected, res, "sum of shares is incorrect, tc #%d", tcIndex) - } -} - -func (s *vaultShareTestSuite) TestFilteredZeroVaultShares() { - cases := []struct { - name string - input types.VaultShares - original string - expected string - }{ - { - name: "all greater than zero", - input: types.VaultShares{ - {"testa", sdk.NewDec(1)}, - {"testb", sdk.NewDec(2)}, - {"testc", sdk.NewDec(3)}, - {"testd", sdk.NewDec(4)}, - {"teste", sdk.NewDec(5)}, - }, - original: "1.000000000000000000testa,2.000000000000000000testb,3.000000000000000000testc,4.000000000000000000testd,5.000000000000000000teste", - expected: "1.000000000000000000testa,2.000000000000000000testb,3.000000000000000000testc,4.000000000000000000testd,5.000000000000000000teste", - }, - { - name: "zero share in middle", - input: types.VaultShares{ - {"testa", sdk.NewDec(1)}, - {"testb", sdk.NewDec(2)}, - {"testc", sdk.NewDec(0)}, - {"testd", sdk.NewDec(4)}, - {"teste", sdk.NewDec(5)}, - }, - original: "1.000000000000000000testa,2.000000000000000000testb,0.000000000000000000testc,4.000000000000000000testd,5.000000000000000000teste", - expected: "1.000000000000000000testa,2.000000000000000000testb,4.000000000000000000testd,5.000000000000000000teste", - }, - { - name: "zero share end (unordered)", - input: types.VaultShares{ - {"teste", sdk.NewDec(5)}, - {"testc", sdk.NewDec(3)}, - {"testa", sdk.NewDec(1)}, - {"testd", sdk.NewDec(4)}, - {"testb", sdk.NewDec(0)}, - }, - original: "5.000000000000000000teste,3.000000000000000000testc,1.000000000000000000testa,4.000000000000000000testd,0.000000000000000000testb", - expected: "1.000000000000000000testa,3.000000000000000000testc,4.000000000000000000testd,5.000000000000000000teste", - }, - } - - for _, tt := range cases { - undertest := types.NewVaultShares(tt.input...) - s.Require().Equal(tt.expected, undertest.String(), "NewVaultShares must return expected results") - s.Require().Equal(tt.original, tt.input.String(), "input must be unmodified and match original") - } -} - -func (s *vaultShareTestSuite) TestIsValid() { - tests := []struct { - share types.VaultShare - expectPass bool - msg string - }{ - { - types.NewVaultShare("mytoken", sdk.NewDec(10)), - true, - "valid shares should have passed", - }, - { - types.VaultShare{Denom: "BTC", Amount: sdk.NewDec(10)}, - true, - "valid uppercase denom", - }, - { - types.VaultShare{Denom: "Bitshare", Amount: sdk.NewDec(10)}, - true, - "valid mixed case denom", - }, - { - types.VaultShare{Denom: "btc", Amount: sdk.NewDec(-10)}, - false, - "negative amount", - }, - } - - for _, tc := range tests { - tc := tc - if tc.expectPass { - s.Require().True(tc.share.IsValid(), tc.msg) - } else { - s.Require().False(tc.share.IsValid(), tc.msg) - } - } -} - -func (s *vaultShareTestSuite) TestSubVaultShare() { - tests := []struct { - share types.VaultShare - expectPass bool - msg string - }{ - { - types.NewVaultShare("mytoken", sdk.NewDec(20)), - true, - "valid shares should have passed", - }, - { - types.NewVaultShare("othertoken", sdk.NewDec(20)), - false, - "denom mismatch", - }, - { - types.NewVaultShare("mytoken", sdk.NewDec(9)), - false, - "negative amount", - }, - } - - vaultShare := types.NewVaultShare("mytoken", sdk.NewDec(10)) - - for _, tc := range tests { - tc := tc - if tc.expectPass { - equal := tc.share.Sub(vaultShare) - s.Require().Equal(equal, vaultShare, tc.msg) - } else { - s.Require().Panics(func() { tc.share.Sub(vaultShare) }, tc.msg) - } - } -} - -func (s *vaultShareTestSuite) TestSubVaultShares() { - tests := []struct { - shares types.VaultShares - expectPass bool - msg string - }{ - { - types.NewVaultShares(types.NewVaultShare("mytoken", d(10)), types.NewVaultShare("btc", d(20)), types.NewVaultShare("eth", d(30))), - true, - "sorted shares should have passed", - }, - { - types.VaultShares{types.NewVaultShare("mytoken", d(10)), types.NewVaultShare("btc", d(20)), types.NewVaultShare("eth", d(30))}, - false, - "unorted shares should panic", - }, - { - types.VaultShares{types.VaultShare{Denom: "BTC", Amount: sdk.NewDec(10)}, types.NewVaultShare("eth", d(15)), types.NewVaultShare("mytoken", d(5))}, - false, - "invalid denoms", - }, - } - - vaultShares := types.NewVaultShares(types.NewVaultShare("btc", d(10)), types.NewVaultShare("eth", d(15)), types.NewVaultShare("mytoken", d(5))) - - for _, tc := range tests { - tc := tc - if tc.expectPass { - equal := tc.shares.Sub(vaultShares...) - s.Require().Equal(equal, vaultShares, tc.msg) - } else { - s.Require().Panics(func() { tc.shares.Sub(vaultShares...) }, tc.msg) - } - } -} - -func (s *vaultShareTestSuite) TestSortVaultShares() { - good := types.VaultShares{ - types.NewVaultShare("gas", d(1)), - types.NewVaultShare("mineral", d(1)), - types.NewVaultShare("tree", d(1)), - } - empty := types.VaultShares{ - types.NewVaultShare("gold", d(0)), - } - badSort1 := types.VaultShares{ - types.NewVaultShare("tree", d(1)), - types.NewVaultShare("gas", d(1)), - types.NewVaultShare("mineral", d(1)), - } - badSort2 := types.VaultShares{ // both are after the first one, but the second and third are in the wrong order - types.NewVaultShare("gas", d(1)), - types.NewVaultShare("tree", d(1)), - types.NewVaultShare("mineral", d(1)), - } - badAmt := types.VaultShares{ - types.NewVaultShare("gas", d(1)), - types.NewVaultShare("tree", d(0)), - types.NewVaultShare("mineral", d(1)), - } - dup := types.VaultShares{ - types.NewVaultShare("gas", d(1)), - types.NewVaultShare("gas", d(1)), - types.NewVaultShare("mineral", d(1)), - } - cases := []struct { - name string - shares types.VaultShares - before, after bool // valid before/after sort - }{ - {"valid shares", good, true, true}, - {"empty shares", empty, false, false}, - {"unsorted shares (1)", badSort1, false, true}, - {"unsorted shares (2)", badSort2, false, true}, - {"zero amount shares", badAmt, false, false}, - {"duplicate shares", dup, false, false}, - } - - for _, tc := range cases { - s.Require().Equal(tc.before, tc.shares.IsValid(), "share validity is incorrect before sorting; %s", tc.name) - tc.shares.Sort() - s.Require().Equal(tc.after, tc.shares.IsValid(), "share validity is incorrect after sorting; %s", tc.name) - } -} - -func (s *vaultShareTestSuite) TestVaultSharesValidate() { - testCases := []struct { - input types.VaultShares - expectedPass bool - }{ - {types.VaultShares{}, true}, - {types.VaultShares{types.VaultShare{testDenom1, sdk.NewDec(5)}}, true}, - {types.VaultShares{types.VaultShare{testDenom1, sdk.NewDec(5)}, types.VaultShare{testDenom2, sdk.NewDec(100000)}}, true}, - {types.VaultShares{types.VaultShare{testDenom1, sdk.NewDec(-5)}}, false}, - {types.VaultShares{types.VaultShare{"BTC", sdk.NewDec(5)}}, true}, - {types.VaultShares{types.VaultShare{"0BTC", sdk.NewDec(5)}}, false}, - {types.VaultShares{types.VaultShare{testDenom1, sdk.NewDec(5)}, types.VaultShare{"B", sdk.NewDec(100000)}}, false}, - {types.VaultShares{types.VaultShare{testDenom1, sdk.NewDec(5)}, types.VaultShare{testDenom2, sdk.NewDec(-100000)}}, false}, - {types.VaultShares{types.VaultShare{testDenom1, sdk.NewDec(-5)}, types.VaultShare{testDenom2, sdk.NewDec(100000)}}, false}, - {types.VaultShares{types.VaultShare{"BTC", sdk.NewDec(5)}, types.VaultShare{testDenom2, sdk.NewDec(100000)}}, true}, - {types.VaultShares{types.VaultShare{"0BTC", sdk.NewDec(5)}, types.VaultShare{testDenom2, sdk.NewDec(100000)}}, false}, - } - - for i, tc := range testCases { - err := tc.input.Validate() - if tc.expectedPass { - s.Require().NoError(err, "unexpected result for test case #%d, input: %v", i, tc.input) - } else { - s.Require().Error(err, "unexpected result for test case #%d, input: %v", i, tc.input) - } - } -} - -func (s *vaultShareTestSuite) TestVaultSharesString() { - testCases := []struct { - input types.VaultShares - expected string - }{ - {types.VaultShares{}, ""}, - { - types.VaultShares{ - types.NewVaultShare("atom", sdk.NewDecWithPrec(5040000000000000000, sdk.Precision)), - types.NewVaultShare("stake", sdk.NewDecWithPrec(4000000000000000, sdk.Precision)), - }, - "5.040000000000000000atom,0.004000000000000000stake", - }, - } - - for i, tc := range testCases { - out := tc.input.String() - s.Require().Equal(tc.expected, out, "unexpected result for test case #%d, input: %v", i, tc.input) - } -} - -func (s *vaultShareTestSuite) TestNewVaultSharesWithIsValid() { - fake1 := append(types.NewVaultShares(types.NewVaultShare("mytoken", d(10))), types.VaultShare{Denom: "10BTC", Amount: sdk.NewDec(10)}) - fake2 := append(types.NewVaultShares(types.NewVaultShare("mytoken", d(10))), types.VaultShare{Denom: "BTC", Amount: sdk.NewDec(-10)}) - - tests := []struct { - share types.VaultShares - expectPass bool - msg string - }{ - { - types.NewVaultShares(types.NewVaultShare("mytoken", d(10))), - true, - "valid shares should have passed", - }, - { - fake1, - false, - "invalid denoms", - }, - { - fake2, - false, - "negative amount", - }, - } - - for _, tc := range tests { - tc := tc - if tc.expectPass { - s.Require().True(tc.share.IsValid(), tc.msg) - } else { - s.Require().False(tc.share.IsValid(), tc.msg) - } - } -} - -func (s *vaultShareTestSuite) TestVaultShares_AddVaultShareWithIsValid() { - lengthTestVaultShares := types.NewVaultShares().Add(types.NewVaultShare("mytoken", d(10))).Add(types.VaultShare{Denom: "BTC", Amount: sdk.NewDec(10)}) - s.Require().Equal(2, len(lengthTestVaultShares), "should be 2") - - tests := []struct { - share types.VaultShares - expectPass bool - msg string - }{ - { - types.NewVaultShares().Add(types.NewVaultShare("mytoken", d(10))), - true, - "valid shares should have passed", - }, - { - types.NewVaultShares().Add(types.NewVaultShare("mytoken", d(10))).Add(types.VaultShare{Denom: "0BTC", Amount: sdk.NewDec(10)}), - false, - "invalid denoms", - }, - { - types.NewVaultShares().Add(types.NewVaultShare("mytoken", d(10))).Add(types.VaultShare{Denom: "BTC", Amount: sdk.NewDec(-10)}), - false, - "negative amount", - }, - } - - for _, tc := range tests { - tc := tc - if tc.expectPass { - s.Require().True(tc.share.IsValid(), tc.msg) - } else { - s.Require().False(tc.share.IsValid(), tc.msg) - } - } -} diff --git a/x/earn/types/strategy.go b/x/earn/types/strategy.go deleted file mode 100644 index 5afe5d9d..00000000 --- a/x/earn/types/strategy.go +++ /dev/null @@ -1,62 +0,0 @@ -package types - -import ( - "fmt" - "strings" -) - -// IsValid returns true if the StrategyType status is valid and false otherwise. -func (s StrategyType) IsValid() bool { - return s == STRATEGY_TYPE_HARD || s == STRATEGY_TYPE_SAVINGS -} - -// Validate returns an error if the StrategyType is invalid. -func (s StrategyType) Validate() error { - if !s.IsValid() { - return fmt.Errorf("invalid strategy %s", s) - } - - return nil -} - -// NewStrategyTypeFromString converts string to StrategyType type -func NewStrategyTypeFromString(str string) StrategyType { - switch strings.ToLower(str) { - case "hard": - return STRATEGY_TYPE_HARD - case "savings": - return STRATEGY_TYPE_SAVINGS - default: - return STRATEGY_TYPE_UNSPECIFIED - } -} - -// StrategyTypes defines a slice of StrategyType -type StrategyTypes []StrategyType - -// Validate returns an error if StrategyTypes are invalid. -func (strategies StrategyTypes) Validate() error { - if len(strategies) == 0 { - return fmt.Errorf("empty StrategyTypes") - } - - if len(strategies) != 1 { - return fmt.Errorf("must have exactly one strategy type, multiple strategies are not supported") - } - - uniqueStrategies := make(map[StrategyType]bool) - - for _, strategy := range strategies { - if err := strategy.Validate(); err != nil { - return err - } - - if _, found := uniqueStrategies[strategy]; found { - return fmt.Errorf("duplicate strategy %s", strategy) - } - - uniqueStrategies[strategy] = true - } - - return nil -} diff --git a/x/earn/types/strategy.pb.go b/x/earn/types/strategy.pb.go deleted file mode 100644 index 53fecfe6..00000000 --- a/x/earn/types/strategy.pb.go +++ /dev/null @@ -1,81 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/earn/v1beta1/strategy.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - math "math" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// StrategyType is the type of strategy that a vault uses to optimize yields. -type StrategyType int32 - -const ( - // STRATEGY_TYPE_UNSPECIFIED represents an unspecified or invalid strategy type. - STRATEGY_TYPE_UNSPECIFIED StrategyType = 0 - // STRATEGY_TYPE_HARD represents the strategy that deposits assets in the Hard - // module. - STRATEGY_TYPE_HARD StrategyType = 1 - // STRATEGY_TYPE_SAVINGS represents the strategy that deposits assets in the - // Savings module. - STRATEGY_TYPE_SAVINGS StrategyType = 2 -) - -var StrategyType_name = map[int32]string{ - 0: "STRATEGY_TYPE_UNSPECIFIED", - 1: "STRATEGY_TYPE_HARD", - 2: "STRATEGY_TYPE_SAVINGS", -} - -var StrategyType_value = map[string]int32{ - "STRATEGY_TYPE_UNSPECIFIED": 0, - "STRATEGY_TYPE_HARD": 1, - "STRATEGY_TYPE_SAVINGS": 2, -} - -func (x StrategyType) String() string { - return proto.EnumName(StrategyType_name, int32(x)) -} - -func (StrategyType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_257c4968dd48fa09, []int{0} -} - -func init() { - proto.RegisterEnum("kava.earn.v1beta1.StrategyType", StrategyType_name, StrategyType_value) -} - -func init() { proto.RegisterFile("kava/earn/v1beta1/strategy.proto", fileDescriptor_257c4968dd48fa09) } - -var fileDescriptor_257c4968dd48fa09 = []byte{ - // 226 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xc8, 0x4e, 0x2c, 0x4b, - 0xd4, 0x4f, 0x4d, 0x2c, 0xca, 0xd3, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x2f, 0x2e, - 0x29, 0x4a, 0x2c, 0x49, 0x4d, 0xaf, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x04, 0xa9, - 0xd0, 0x03, 0xa9, 0xd0, 0x83, 0xaa, 0x90, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0xcb, 0xea, 0x83, - 0x58, 0x10, 0x85, 0x5a, 0x69, 0x5c, 0x3c, 0xc1, 0x50, 0xad, 0x21, 0x95, 0x05, 0xa9, 0x42, 0xb2, - 0x5c, 0x92, 0xc1, 0x21, 0x41, 0x8e, 0x21, 0xae, 0xee, 0x91, 0xf1, 0x21, 0x91, 0x01, 0xae, 0xf1, - 0xa1, 0x7e, 0xc1, 0x01, 0xae, 0xce, 0x9e, 0x6e, 0x9e, 0xae, 0x2e, 0x02, 0x0c, 0x42, 0x62, 0x5c, - 0x42, 0xa8, 0xd2, 0x1e, 0x8e, 0x41, 0x2e, 0x02, 0x8c, 0x42, 0x92, 0x5c, 0xa2, 0xa8, 0xe2, 0xc1, - 0x8e, 0x61, 0x9e, 0x7e, 0xee, 0xc1, 0x02, 0x4c, 0x52, 0x2c, 0x1d, 0x8b, 0xe5, 0x18, 0x9c, 0x1c, - 0x4f, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, - 0x18, 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0x4a, 0x3d, 0x3d, 0xb3, 0x24, 0xa3, - 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, 0xdf, 0x20, 0x3d, 0x27, 0x31, 0xa9, 0x58, 0xdf, 0x20, 0x5d, - 0x37, 0x39, 0x23, 0x31, 0x33, 0x4f, 0xbf, 0x02, 0xe2, 0xc9, 0x92, 0xca, 0x82, 0xd4, 0xe2, 0x24, - 0x36, 0xb0, 0x8b, 0x8d, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x56, 0xe7, 0x50, 0xe7, 0xfe, 0x00, - 0x00, 0x00, -} diff --git a/x/earn/types/strategy_test.go b/x/earn/types/strategy_test.go deleted file mode 100644 index 5311677e..00000000 --- a/x/earn/types/strategy_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/0glabs/0g-chain/x/earn/types" - "github.com/stretchr/testify/require" -) - -func TestNewStrategyTypeFromString(t *testing.T) { - tests := []struct { - name string - strategy string - expected types.StrategyType - }{ - { - name: "hard", - strategy: "hard", - expected: types.STRATEGY_TYPE_HARD, - }, - { - name: "savings", - strategy: "savings", - expected: types.STRATEGY_TYPE_SAVINGS, - }, - { - name: "unspecified", - strategy: "not a valid strategy name", - expected: types.STRATEGY_TYPE_UNSPECIFIED, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - actual := types.NewStrategyTypeFromString(tc.strategy) - if actual != tc.expected { - t.Errorf("expected %s, got %s", tc.expected, actual) - } - }) - } -} - -func TestValidateStrategyTypes(t *testing.T) { - type errArgs struct { - expectPass bool - contains string - } - - tests := []struct { - name string - strategies types.StrategyTypes - errArgs errArgs - }{ - { - name: "valid - hard", - strategies: types.StrategyTypes{types.STRATEGY_TYPE_HARD}, - errArgs: errArgs{ - expectPass: true, - }, - }, - { - name: "valid - savings", - strategies: types.StrategyTypes{types.STRATEGY_TYPE_SAVINGS}, - errArgs: errArgs{ - expectPass: true, - }, - }, - { - name: "invalid - duplicate", - strategies: types.StrategyTypes{ - types.STRATEGY_TYPE_SAVINGS, - types.STRATEGY_TYPE_SAVINGS, - }, - errArgs: errArgs{ - expectPass: false, - // This will change to duplicate error if multiple strategies are supported - contains: "must have exactly one strategy type, multiple strategies are not supported", - }, - }, - { - name: "invalid - unspecified", - strategies: types.StrategyTypes{types.STRATEGY_TYPE_UNSPECIFIED}, - errArgs: errArgs{ - expectPass: false, - contains: "invalid strategy", - }, - }, - { - name: "invalid - zero", - strategies: types.StrategyTypes{}, - errArgs: errArgs{ - expectPass: false, - contains: "empty StrategyTypes", - }, - }, - { - name: "invalid - more than 1", - strategies: types.StrategyTypes{ - types.STRATEGY_TYPE_HARD, - types.STRATEGY_TYPE_SAVINGS, - }, - errArgs: errArgs{ - expectPass: false, - contains: "must have exactly one strategy type, multiple strategies are not supported", - }, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - err := tc.strategies.Validate() - if tc.errArgs.expectPass { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), tc.errArgs.contains) - } - }) - } -} diff --git a/x/earn/types/tx.pb.go b/x/earn/types/tx.pb.go deleted file mode 100644 index 766fd200..00000000 --- a/x/earn/types/tx.pb.go +++ /dev/null @@ -1,1120 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/earn/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// MsgDeposit represents a message for depositing assedts into a vault -type MsgDeposit struct { - // depositor represents the address to deposit funds from - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - // Amount represents the token to deposit. The vault corresponds to the denom - // of the amount coin. - Amount types.Coin `protobuf:"bytes,2,opt,name=amount,proto3" json:"amount"` - // Strategy is the vault strategy to use. - Strategy StrategyType `protobuf:"varint,3,opt,name=strategy,proto3,enum=kava.earn.v1beta1.StrategyType" json:"strategy,omitempty"` -} - -func (m *MsgDeposit) Reset() { *m = MsgDeposit{} } -func (m *MsgDeposit) String() string { return proto.CompactTextString(m) } -func (*MsgDeposit) ProtoMessage() {} -func (*MsgDeposit) Descriptor() ([]byte, []int) { - return fileDescriptor_2e9dcf48a3fa0009, []int{0} -} -func (m *MsgDeposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDeposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDeposit.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgDeposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDeposit.Merge(m, src) -} -func (m *MsgDeposit) XXX_Size() int { - return m.Size() -} -func (m *MsgDeposit) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDeposit.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDeposit proto.InternalMessageInfo - -// MsgDepositResponse defines the Msg/Deposit response type. -type MsgDepositResponse struct { - Shares VaultShare `protobuf:"bytes,1,opt,name=shares,proto3" json:"shares"` -} - -func (m *MsgDepositResponse) Reset() { *m = MsgDepositResponse{} } -func (m *MsgDepositResponse) String() string { return proto.CompactTextString(m) } -func (*MsgDepositResponse) ProtoMessage() {} -func (*MsgDepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2e9dcf48a3fa0009, []int{1} -} -func (m *MsgDepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDepositResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgDepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDepositResponse.Merge(m, src) -} -func (m *MsgDepositResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgDepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDepositResponse proto.InternalMessageInfo - -func (m *MsgDepositResponse) GetShares() VaultShare { - if m != nil { - return m.Shares - } - return VaultShare{} -} - -// MsgWithdraw represents a message for withdrawing liquidity from a vault -type MsgWithdraw struct { - // from represents the address we are withdrawing for - From string `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"` - // Amount represents the token to withdraw. The vault corresponds to the denom - // of the amount coin. - Amount types.Coin `protobuf:"bytes,2,opt,name=amount,proto3" json:"amount"` - // Strategy is the vault strategy to use. - Strategy StrategyType `protobuf:"varint,3,opt,name=strategy,proto3,enum=kava.earn.v1beta1.StrategyType" json:"strategy,omitempty"` -} - -func (m *MsgWithdraw) Reset() { *m = MsgWithdraw{} } -func (m *MsgWithdraw) String() string { return proto.CompactTextString(m) } -func (*MsgWithdraw) ProtoMessage() {} -func (*MsgWithdraw) Descriptor() ([]byte, []int) { - return fileDescriptor_2e9dcf48a3fa0009, []int{2} -} -func (m *MsgWithdraw) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdraw) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdraw.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgWithdraw) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdraw.Merge(m, src) -} -func (m *MsgWithdraw) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdraw) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdraw.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdraw proto.InternalMessageInfo - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -type MsgWithdrawResponse struct { - Shares VaultShare `protobuf:"bytes,1,opt,name=shares,proto3" json:"shares"` -} - -func (m *MsgWithdrawResponse) Reset() { *m = MsgWithdrawResponse{} } -func (m *MsgWithdrawResponse) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawResponse) ProtoMessage() {} -func (*MsgWithdrawResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2e9dcf48a3fa0009, []int{3} -} -func (m *MsgWithdrawResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgWithdrawResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawResponse.Merge(m, src) -} -func (m *MsgWithdrawResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawResponse proto.InternalMessageInfo - -func (m *MsgWithdrawResponse) GetShares() VaultShare { - if m != nil { - return m.Shares - } - return VaultShare{} -} - -func init() { - proto.RegisterType((*MsgDeposit)(nil), "kava.earn.v1beta1.MsgDeposit") - proto.RegisterType((*MsgDepositResponse)(nil), "kava.earn.v1beta1.MsgDepositResponse") - proto.RegisterType((*MsgWithdraw)(nil), "kava.earn.v1beta1.MsgWithdraw") - proto.RegisterType((*MsgWithdrawResponse)(nil), "kava.earn.v1beta1.MsgWithdrawResponse") -} - -func init() { proto.RegisterFile("kava/earn/v1beta1/tx.proto", fileDescriptor_2e9dcf48a3fa0009) } - -var fileDescriptor_2e9dcf48a3fa0009 = []byte{ - // 447 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x93, 0x41, 0x8b, 0x13, 0x31, - 0x1c, 0xc5, 0x27, 0x6e, 0xa9, 0xbb, 0x29, 0x08, 0xc6, 0x3d, 0x74, 0x07, 0x36, 0x2d, 0x05, 0xb5, - 0x07, 0x37, 0xd9, 0xad, 0xa0, 0xe0, 0x9e, 0xb6, 0x7a, 0x2d, 0xe2, 0x54, 0x14, 0xbc, 0x48, 0xa6, - 0x8d, 0xe9, 0xe0, 0x76, 0x32, 0xe4, 0x9f, 0xd6, 0xed, 0x37, 0xf0, 0xe8, 0x47, 0xf0, 0xec, 0x59, - 0xf0, 0xea, 0x71, 0x8f, 0x8b, 0x27, 0x4f, 0x22, 0xed, 0x17, 0x91, 0x69, 0x32, 0x53, 0xa1, 0xa5, - 0x5e, 0x84, 0xbd, 0x25, 0xf9, 0xbd, 0x97, 0xbe, 0xff, 0xeb, 0x04, 0x87, 0xef, 0xc5, 0x54, 0x70, - 0x29, 0x4c, 0xca, 0xa7, 0x27, 0xb1, 0xb4, 0xe2, 0x84, 0xdb, 0x0b, 0x96, 0x19, 0x6d, 0x35, 0xb9, - 0x9d, 0x33, 0x96, 0x33, 0xe6, 0x59, 0x48, 0x07, 0x1a, 0xc6, 0x1a, 0x78, 0x2c, 0x40, 0x96, 0x86, - 0x81, 0x4e, 0x52, 0x67, 0x09, 0x0f, 0x1c, 0x7f, 0xbb, 0xdc, 0x71, 0xb7, 0xf1, 0x68, 0x5f, 0x69, - 0xa5, 0xdd, 0x79, 0xbe, 0xf2, 0xa7, 0xcd, 0xf5, 0xdf, 0x07, 0x6b, 0x84, 0x95, 0x6a, 0xe6, 0x15, - 0x87, 0xeb, 0x8a, 0xa9, 0x98, 0x9c, 0x5b, 0x87, 0x5b, 0xdf, 0x11, 0xc6, 0x3d, 0x50, 0xcf, 0x64, - 0xa6, 0x21, 0xb1, 0xe4, 0x11, 0xde, 0x1b, 0xba, 0xa5, 0x36, 0x75, 0xd4, 0x44, 0xed, 0xbd, 0x6e, - 0xfd, 0xc7, 0xd7, 0xa3, 0x7d, 0x1f, 0xe5, 0x6c, 0x38, 0x34, 0x12, 0xa0, 0x6f, 0x4d, 0x92, 0xaa, - 0x68, 0x25, 0x25, 0x8f, 0x71, 0x55, 0x8c, 0xf5, 0x24, 0xb5, 0xf5, 0x1b, 0x4d, 0xd4, 0xae, 0x75, - 0x0e, 0x98, 0x77, 0xe4, 0x93, 0x16, 0xe3, 0xb3, 0xa7, 0x3a, 0x49, 0xbb, 0x95, 0xcb, 0x5f, 0x8d, - 0x20, 0xf2, 0x72, 0x72, 0x8a, 0x77, 0x8b, 0xc0, 0xf5, 0x9d, 0x26, 0x6a, 0xdf, 0xea, 0x34, 0xd8, - 0x5a, 0x6f, 0xac, 0xef, 0x25, 0x2f, 0x67, 0x99, 0x8c, 0x4a, 0xc3, 0x93, 0xca, 0xc7, 0xcf, 0x8d, - 0xa0, 0xf5, 0x02, 0x93, 0xd5, 0x04, 0x91, 0x84, 0x4c, 0xa7, 0x20, 0xc9, 0x29, 0xae, 0xc2, 0x48, - 0x18, 0x09, 0xcb, 0x31, 0x6a, 0x9d, 0xc3, 0x0d, 0xd7, 0xbe, 0xca, 0x8b, 0xe8, 0xe7, 0xaa, 0x22, - 0x95, 0xb3, 0xb4, 0xbe, 0x21, 0x5c, 0xeb, 0x81, 0x7a, 0x9d, 0xd8, 0xd1, 0xd0, 0x88, 0x0f, 0xe4, - 0x01, 0xae, 0xbc, 0x33, 0x7a, 0xfc, 0xcf, 0x46, 0x96, 0xaa, 0x6b, 0x2d, 0x23, 0xc2, 0x77, 0xfe, - 0x0a, 0xfe, 0x5f, 0xda, 0xe8, 0x7c, 0x41, 0x78, 0xa7, 0x07, 0x8a, 0x3c, 0xc7, 0x37, 0x8b, 0xef, - 0x64, 0x93, 0x7f, 0xf5, 0x27, 0x84, 0x77, 0xb7, 0xe2, 0x32, 0x55, 0x84, 0x77, 0xcb, 0x8a, 0xe9, - 0x66, 0x4b, 0xc1, 0xc3, 0x7b, 0xdb, 0x79, 0x71, 0x67, 0xf7, 0xec, 0x72, 0x4e, 0xd1, 0xd5, 0x9c, - 0xa2, 0xdf, 0x73, 0x8a, 0x3e, 0x2d, 0x68, 0x70, 0xb5, 0xa0, 0xc1, 0xcf, 0x05, 0x0d, 0xde, 0xdc, - 0x57, 0x89, 0x1d, 0x4d, 0x62, 0x36, 0xd0, 0x63, 0x7e, 0xac, 0xce, 0x45, 0x0c, 0xfc, 0x58, 0x1d, - 0x0d, 0x46, 0x22, 0x49, 0xf9, 0x85, 0x7b, 0x21, 0x76, 0x96, 0x49, 0x88, 0xab, 0xcb, 0xa7, 0xf1, - 0xf0, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x56, 0x26, 0x8d, 0x84, 0xdd, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - // Deposit defines a method for depositing assets into a vault - Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) - // Withdraw defines a method for withdrawing assets into a vault - Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) { - out := new(MsgDepositResponse) - err := c.cc.Invoke(ctx, "/kava.earn.v1beta1.Msg/Deposit", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) { - out := new(MsgWithdrawResponse) - err := c.cc.Invoke(ctx, "/kava.earn.v1beta1.Msg/Withdraw", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // Deposit defines a method for depositing assets into a vault - Deposit(context.Context, *MsgDeposit) (*MsgDepositResponse, error) - // Withdraw defines a method for withdrawing assets into a vault - Withdraw(context.Context, *MsgWithdraw) (*MsgWithdrawResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Deposit(ctx context.Context, req *MsgDeposit) (*MsgDepositResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposit not implemented") -} -func (*UnimplementedMsgServer) Withdraw(ctx context.Context, req *MsgWithdraw) (*MsgWithdrawResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Withdraw not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Deposit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgDeposit) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Deposit(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.earn.v1beta1.Msg/Deposit", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Deposit(ctx, req.(*MsgDeposit)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Withdraw_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgWithdraw) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Withdraw(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.earn.v1beta1.Msg/Withdraw", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Withdraw(ctx, req.(*MsgWithdraw)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.earn.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Deposit", - Handler: _Msg_Deposit_Handler, - }, - { - MethodName: "Withdraw", - Handler: _Msg_Withdraw_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/earn/v1beta1/tx.proto", -} - -func (m *MsgDeposit) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgDeposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDeposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Strategy != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Strategy)) - i-- - dAtA[i] = 0x18 - } - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgDepositResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgDepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Shares.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *MsgWithdraw) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgWithdraw) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdraw) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Strategy != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Strategy)) - i-- - dAtA[i] = 0x18 - } - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.From) > 0 { - i -= len(m.From) - copy(dAtA[i:], m.From) - i = encodeVarintTx(dAtA, i, uint64(len(m.From))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgWithdrawResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Shares.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgDeposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTx(uint64(l)) - if m.Strategy != 0 { - n += 1 + sovTx(uint64(m.Strategy)) - } - return n -} - -func (m *MsgDepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Shares.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgWithdraw) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.From) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTx(uint64(l)) - if m.Strategy != 0 { - n += 1 + sovTx(uint64(m.Strategy)) - } - return n -} - -func (m *MsgWithdrawResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Shares.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgDeposit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDeposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDeposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Strategy", wireType) - } - m.Strategy = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Strategy |= StrategyType(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDepositResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Shares", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Shares.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdraw) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdraw: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdraw: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.From = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Strategy", wireType) - } - m.Strategy = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Strategy |= StrategyType(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Shares", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Shares.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/earn/types/vault.go b/x/earn/types/vault.go deleted file mode 100644 index 907c25e1..00000000 --- a/x/earn/types/vault.go +++ /dev/null @@ -1,171 +0,0 @@ -package types - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// NewVaultRecord returns a new VaultRecord with 0 supply. -func NewVaultRecord(vaultDenom string, amount sdk.Dec) VaultRecord { - return VaultRecord{ - TotalShares: NewVaultShare(vaultDenom, amount), - } -} - -// Validate returns an error if a VaultRecord is invalid. -func (vr *VaultRecord) Validate() error { - return vr.TotalShares.Validate() -} - -// VaultRecords is a slice of VaultRecord. -type VaultRecords []VaultRecord - -// Validate returns an error if a slice of VaultRecords is invalid. -func (vrs VaultRecords) Validate() error { - denoms := make(map[string]bool) - - for _, vr := range vrs { - if err := vr.Validate(); err != nil { - return err - } - - if denoms[vr.TotalShares.Denom] { - return fmt.Errorf("duplicate vault denom %s", vr.TotalShares.Denom) - } - - denoms[vr.TotalShares.Denom] = true - } - - return nil -} - -// NewVaultShareRecord returns a new VaultShareRecord with the provided supplied -// coins. -func NewVaultShareRecord(depositor sdk.AccAddress, shares VaultShares) VaultShareRecord { - return VaultShareRecord{ - Depositor: depositor, - Shares: shares, - } -} - -// Validate returns an error if an VaultShareRecord is invalid. -func (vsr VaultShareRecord) Validate() error { - if vsr.Depositor.Empty() { - return fmt.Errorf("depositor is empty") - } - - if err := vsr.Shares.Validate(); err != nil { - return fmt.Errorf("invalid vault share record shares: %w", err) - } - - return nil -} - -// VaultShareRecords is a slice of VaultShareRecord. -type VaultShareRecords []VaultShareRecord - -// Validate returns an error if a slice of VaultRecords is invalid. -func (vsrs VaultShareRecords) Validate() error { - addrs := make(map[string]bool) - - for _, vr := range vsrs { - if err := vr.Validate(); err != nil { - return err - } - - if _, found := addrs[vr.Depositor.String()]; found { - return fmt.Errorf("duplicate address %s", vr.Depositor.String()) - } - - addrs[vr.Depositor.String()] = true - } - - return nil -} - -// NewAllowedVault returns a new AllowedVault with the given values. -func NewAllowedVault( - denom string, - strategyTypes StrategyTypes, - isPrivateVault bool, - allowedDepositors []sdk.AccAddress, -) AllowedVault { - return AllowedVault{ - Denom: denom, - Strategies: strategyTypes, - IsPrivateVault: isPrivateVault, - AllowedDepositors: allowedDepositors, - } -} - -// Validate returns an error if the AllowedVault is invalid -func (a *AllowedVault) Validate() error { - if err := sdk.ValidateDenom(a.Denom); err != nil { - return errorsmod.Wrap(ErrInvalidVaultDenom, err.Error()) - } - - // Private -> 1+ allowed depositors - // Non-private -> 0 allowed depositors - if a.IsPrivateVault && len(a.AllowedDepositors) == 0 { - return fmt.Errorf("private vaults require non-empty AllowedDepositors") - } - - if !a.IsPrivateVault && len(a.AllowedDepositors) > 0 { - return fmt.Errorf("non-private vaults cannot have any AllowedDepositors") - } - - return a.Strategies.Validate() -} - -// IsStrategyAllowed returns true if the given strategy type is allowed for the -// vault. -func (a *AllowedVault) IsStrategyAllowed(strategy StrategyType) bool { - for _, s := range a.Strategies { - if s == strategy { - return true - } - } - - return false -} - -// IsAccountAllowed returns true if the given account is allowed to deposit into -// the vault. -func (a *AllowedVault) IsAccountAllowed(account sdk.AccAddress) bool { - // Anyone can deposit to non-private vaults - if !a.IsPrivateVault { - return true - } - - for _, addr := range a.AllowedDepositors { - if addr.Equals(account) { - return true - } - } - - return false -} - -// AllowedVaults is a slice of AllowedVault. -type AllowedVaults []AllowedVault - -// Validate returns an error if the AllowedVaults is invalid. -func (a AllowedVaults) Validate() error { - denoms := make(map[string]bool) - - for _, v := range a { - if err := v.Validate(); err != nil { - return err - } - - if denoms[v.Denom] { - return fmt.Errorf("duplicate vault denom %s", v.Denom) - } - - denoms[v.Denom] = true - } - - return nil -} diff --git a/x/earn/types/vault.pb.go b/x/earn/types/vault.pb.go deleted file mode 100644 index 83ffcdb0..00000000 --- a/x/earn/types/vault.pb.go +++ /dev/null @@ -1,1174 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/earn/v1beta1/vault.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// AllowedVault is a vault that is allowed to be created. These can be -// modified via parameter governance. -type AllowedVault struct { - // Denom is the only supported denomination of the vault for deposits and withdrawals. - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - // VaultStrategy is the strategy used for this vault. - Strategies StrategyTypes `protobuf:"varint,2,rep,packed,name=strategies,proto3,enum=kava.earn.v1beta1.StrategyType,castrepeated=StrategyTypes" json:"strategies,omitempty"` - // IsPrivateVault is true if the vault only allows depositors contained in - // AllowedDepositors. - IsPrivateVault bool `protobuf:"varint,3,opt,name=is_private_vault,json=isPrivateVault,proto3" json:"is_private_vault,omitempty"` - // AllowedDepositors is a list of addresses that are allowed to deposit to - // this vault if IsPrivateVault is true. Addresses not contained in this list - // are not allowed to deposit into this vault. If IsPrivateVault is false, - // this should be empty and ignored. - AllowedDepositors []github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,4,rep,name=allowed_depositors,json=allowedDepositors,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"allowed_depositors,omitempty"` -} - -func (m *AllowedVault) Reset() { *m = AllowedVault{} } -func (m *AllowedVault) String() string { return proto.CompactTextString(m) } -func (*AllowedVault) ProtoMessage() {} -func (*AllowedVault) Descriptor() ([]byte, []int) { - return fileDescriptor_884eb89509fbdc04, []int{0} -} -func (m *AllowedVault) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AllowedVault) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AllowedVault.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *AllowedVault) XXX_Merge(src proto.Message) { - xxx_messageInfo_AllowedVault.Merge(m, src) -} -func (m *AllowedVault) XXX_Size() int { - return m.Size() -} -func (m *AllowedVault) XXX_DiscardUnknown() { - xxx_messageInfo_AllowedVault.DiscardUnknown(m) -} - -var xxx_messageInfo_AllowedVault proto.InternalMessageInfo - -func (m *AllowedVault) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *AllowedVault) GetStrategies() StrategyTypes { - if m != nil { - return m.Strategies - } - return nil -} - -func (m *AllowedVault) GetIsPrivateVault() bool { - if m != nil { - return m.IsPrivateVault - } - return false -} - -func (m *AllowedVault) GetAllowedDepositors() []github_com_cosmos_cosmos_sdk_types.AccAddress { - if m != nil { - return m.AllowedDepositors - } - return nil -} - -// VaultRecord is the state of a vault. -type VaultRecord struct { - // TotalShares is the total distributed number of shares in the vault. - TotalShares VaultShare `protobuf:"bytes,1,opt,name=total_shares,json=totalShares,proto3" json:"total_shares"` -} - -func (m *VaultRecord) Reset() { *m = VaultRecord{} } -func (m *VaultRecord) String() string { return proto.CompactTextString(m) } -func (*VaultRecord) ProtoMessage() {} -func (*VaultRecord) Descriptor() ([]byte, []int) { - return fileDescriptor_884eb89509fbdc04, []int{1} -} -func (m *VaultRecord) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *VaultRecord) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_VaultRecord.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *VaultRecord) XXX_Merge(src proto.Message) { - xxx_messageInfo_VaultRecord.Merge(m, src) -} -func (m *VaultRecord) XXX_Size() int { - return m.Size() -} -func (m *VaultRecord) XXX_DiscardUnknown() { - xxx_messageInfo_VaultRecord.DiscardUnknown(m) -} - -var xxx_messageInfo_VaultRecord proto.InternalMessageInfo - -func (m *VaultRecord) GetTotalShares() VaultShare { - if m != nil { - return m.TotalShares - } - return VaultShare{} -} - -// VaultShareRecord defines the vault shares owned by a depositor. -type VaultShareRecord struct { - // Depositor represents the owner of the shares - Depositor github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=depositor,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"depositor,omitempty"` - // Shares represent the vault shares owned by the depositor. - Shares VaultShares `protobuf:"bytes,2,rep,name=shares,proto3,castrepeated=VaultShares" json:"shares"` -} - -func (m *VaultShareRecord) Reset() { *m = VaultShareRecord{} } -func (m *VaultShareRecord) String() string { return proto.CompactTextString(m) } -func (*VaultShareRecord) ProtoMessage() {} -func (*VaultShareRecord) Descriptor() ([]byte, []int) { - return fileDescriptor_884eb89509fbdc04, []int{2} -} -func (m *VaultShareRecord) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *VaultShareRecord) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_VaultShareRecord.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *VaultShareRecord) XXX_Merge(src proto.Message) { - xxx_messageInfo_VaultShareRecord.Merge(m, src) -} -func (m *VaultShareRecord) XXX_Size() int { - return m.Size() -} -func (m *VaultShareRecord) XXX_DiscardUnknown() { - xxx_messageInfo_VaultShareRecord.DiscardUnknown(m) -} - -var xxx_messageInfo_VaultShareRecord proto.InternalMessageInfo - -func (m *VaultShareRecord) GetDepositor() github_com_cosmos_cosmos_sdk_types.AccAddress { - if m != nil { - return m.Depositor - } - return nil -} - -func (m *VaultShareRecord) GetShares() VaultShares { - if m != nil { - return m.Shares - } - return nil -} - -// VaultShare defines shares of a vault owned by a depositor. -type VaultShare struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=amount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"amount"` -} - -func (m *VaultShare) Reset() { *m = VaultShare{} } -func (*VaultShare) ProtoMessage() {} -func (*VaultShare) Descriptor() ([]byte, []int) { - return fileDescriptor_884eb89509fbdc04, []int{3} -} -func (m *VaultShare) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *VaultShare) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_VaultShare.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *VaultShare) XXX_Merge(src proto.Message) { - xxx_messageInfo_VaultShare.Merge(m, src) -} -func (m *VaultShare) XXX_Size() int { - return m.Size() -} -func (m *VaultShare) XXX_DiscardUnknown() { - xxx_messageInfo_VaultShare.DiscardUnknown(m) -} - -var xxx_messageInfo_VaultShare proto.InternalMessageInfo - -func (m *VaultShare) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func init() { - proto.RegisterType((*AllowedVault)(nil), "kava.earn.v1beta1.AllowedVault") - proto.RegisterType((*VaultRecord)(nil), "kava.earn.v1beta1.VaultRecord") - proto.RegisterType((*VaultShareRecord)(nil), "kava.earn.v1beta1.VaultShareRecord") - proto.RegisterType((*VaultShare)(nil), "kava.earn.v1beta1.VaultShare") -} - -func init() { proto.RegisterFile("kava/earn/v1beta1/vault.proto", fileDescriptor_884eb89509fbdc04) } - -var fileDescriptor_884eb89509fbdc04 = []byte{ - // 492 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x53, 0x3f, 0x6f, 0xd3, 0x40, - 0x14, 0xb7, 0x93, 0x10, 0xd1, 0x4b, 0xa8, 0x1a, 0xb7, 0x83, 0xa9, 0x54, 0xdb, 0xca, 0x00, 0x5e, - 0x6c, 0xb7, 0x65, 0x43, 0x2c, 0xb1, 0x22, 0x84, 0x98, 0xd0, 0xb5, 0x30, 0xb0, 0x44, 0x17, 0xfb, - 0x70, 0xac, 0x3a, 0xb9, 0xc8, 0xef, 0x92, 0x92, 0x85, 0xcf, 0xc0, 0x88, 0xc4, 0xc2, 0xdc, 0xb9, - 0x9f, 0x01, 0x75, 0xac, 0x3a, 0x21, 0x86, 0x14, 0x25, 0xdf, 0x82, 0x09, 0xdd, 0x1f, 0x35, 0x91, - 0x02, 0x82, 0x81, 0xc9, 0xbe, 0xdf, 0x7b, 0xef, 0xf7, 0xe7, 0xd9, 0x87, 0x0e, 0xce, 0xc8, 0x94, - 0x44, 0x94, 0x94, 0xa3, 0x68, 0x7a, 0xd4, 0xa7, 0x9c, 0x1c, 0x45, 0x53, 0x32, 0x29, 0x78, 0x38, - 0x2e, 0x19, 0x67, 0x56, 0x4b, 0x94, 0x43, 0x51, 0x0e, 0x75, 0x79, 0xff, 0x61, 0xc2, 0x60, 0xc8, - 0xa0, 0x27, 0x1b, 0x22, 0x75, 0x50, 0xdd, 0xfb, 0x7b, 0x19, 0xcb, 0x98, 0xc2, 0xc5, 0x9b, 0x46, - 0xbd, 0x4d, 0x09, 0xe0, 0x25, 0xe1, 0x34, 0x9b, 0xa9, 0x8e, 0xf6, 0xe7, 0x0a, 0x6a, 0x76, 0x8a, - 0x82, 0x9d, 0xd3, 0xf4, 0x8d, 0x10, 0xb7, 0xf6, 0xd0, 0xbd, 0x94, 0x8e, 0xd8, 0xd0, 0x36, 0x3d, - 0xd3, 0xdf, 0xc2, 0xea, 0x60, 0x61, 0x84, 0xf4, 0x60, 0x4e, 0xc1, 0xae, 0x78, 0x55, 0x7f, 0xfb, - 0xd8, 0x0d, 0x37, 0x1c, 0x86, 0x27, 0x9a, 0xfd, 0x74, 0x36, 0xa6, 0x71, 0xeb, 0xe2, 0xd6, 0x7d, - 0xb0, 0x8e, 0x00, 0x5e, 0x63, 0xb1, 0x7c, 0xb4, 0x93, 0x8b, 0x2c, 0xf9, 0x94, 0x70, 0xda, 0x93, - 0xd1, 0xed, 0xaa, 0x67, 0xfa, 0xf7, 0xf1, 0x76, 0x0e, 0xaf, 0x14, 0xac, 0x3c, 0x9d, 0x23, 0x8b, - 0x28, 0x8f, 0xbd, 0x94, 0x8e, 0x19, 0xe4, 0x9c, 0x95, 0x60, 0xd7, 0xbc, 0xaa, 0xdf, 0x8c, 0x5f, - 0xfc, 0x9c, 0xbb, 0x41, 0x96, 0xf3, 0xc1, 0xa4, 0x1f, 0x26, 0x6c, 0xa8, 0xb7, 0xa2, 0x1f, 0x01, - 0xa4, 0x67, 0x11, 0x17, 0xca, 0x61, 0x27, 0x49, 0x3a, 0x69, 0x5a, 0x52, 0x80, 0x9b, 0xcb, 0x60, - 0x57, 0xef, 0x4e, 0x23, 0xf1, 0x8c, 0x53, 0xc0, 0x2d, 0xad, 0xd1, 0xbd, 0x93, 0x68, 0xbf, 0x46, - 0x0d, 0xe9, 0x00, 0xd3, 0x84, 0x95, 0xa9, 0xf5, 0x1c, 0x35, 0x39, 0xe3, 0xa4, 0xe8, 0xc1, 0x80, - 0x94, 0x14, 0xe4, 0x8a, 0x1a, 0xc7, 0x07, 0xbf, 0xd9, 0x83, 0x9c, 0x3a, 0x11, 0x5d, 0x71, 0xed, - 0x6a, 0xee, 0x1a, 0xb8, 0x21, 0x07, 0x25, 0x02, 0xed, 0xaf, 0x26, 0xda, 0x59, 0x75, 0x68, 0xf2, - 0x77, 0x68, 0xeb, 0x2e, 0x9c, 0x64, 0xfe, 0x9f, 0xd9, 0x56, 0xd4, 0xd6, 0x4b, 0x54, 0xd7, 0xf6, - 0xc5, 0x67, 0xfc, 0xab, 0xfd, 0x5d, 0x61, 0xff, 0xe2, 0xd6, 0x6d, 0xac, 0x30, 0xc0, 0x9a, 0xa1, - 0xfd, 0x01, 0xa1, 0x15, 0xfc, 0x87, 0x5f, 0xe7, 0x14, 0xd5, 0xc9, 0x90, 0x4d, 0x46, 0xdc, 0xae, - 0x08, 0x38, 0x7e, 0x26, 0x08, 0xbf, 0xcf, 0xdd, 0x47, 0xff, 0x10, 0xac, 0x4b, 0x93, 0x9b, 0xcb, - 0x00, 0xe9, 0x44, 0x5d, 0x9a, 0x60, 0xcd, 0xf5, 0xb4, 0xf6, 0xe9, 0x8b, 0x6b, 0xc4, 0x9d, 0xab, - 0x85, 0x63, 0x5e, 0x2f, 0x1c, 0xf3, 0xc7, 0xc2, 0x31, 0x3f, 0x2e, 0x1d, 0xe3, 0x7a, 0xe9, 0x18, - 0xdf, 0x96, 0x8e, 0xf1, 0xf6, 0xf1, 0x1a, 0xfb, 0x61, 0x56, 0x90, 0x3e, 0x44, 0x87, 0x59, 0x90, - 0x0c, 0x48, 0x3e, 0x8a, 0xde, 0xab, 0x1b, 0x21, 0x25, 0xfa, 0x75, 0x79, 0x0f, 0x9e, 0xfc, 0x0a, - 0x00, 0x00, 0xff, 0xff, 0x3f, 0x6e, 0x41, 0xab, 0x8e, 0x03, 0x00, 0x00, -} - -func (m *AllowedVault) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AllowedVault) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AllowedVault) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.AllowedDepositors) > 0 { - for iNdEx := len(m.AllowedDepositors) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.AllowedDepositors[iNdEx]) - copy(dAtA[i:], m.AllowedDepositors[iNdEx]) - i = encodeVarintVault(dAtA, i, uint64(len(m.AllowedDepositors[iNdEx]))) - i-- - dAtA[i] = 0x22 - } - } - if m.IsPrivateVault { - i-- - if m.IsPrivateVault { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x18 - } - if len(m.Strategies) > 0 { - dAtA2 := make([]byte, len(m.Strategies)*10) - var j1 int - for _, num := range m.Strategies { - for num >= 1<<7 { - dAtA2[j1] = uint8(uint64(num)&0x7f | 0x80) - num >>= 7 - j1++ - } - dAtA2[j1] = uint8(num) - j1++ - } - i -= j1 - copy(dAtA[i:], dAtA2[:j1]) - i = encodeVarintVault(dAtA, i, uint64(j1)) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintVault(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *VaultRecord) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *VaultRecord) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *VaultRecord) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.TotalShares.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintVault(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *VaultShareRecord) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *VaultShareRecord) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *VaultShareRecord) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Shares) > 0 { - for iNdEx := len(m.Shares) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Shares[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintVault(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintVault(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *VaultShare) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *VaultShare) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *VaultShare) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Amount.Size() - i -= size - if _, err := m.Amount.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintVault(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintVault(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintVault(dAtA []byte, offset int, v uint64) int { - offset -= sovVault(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *AllowedVault) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovVault(uint64(l)) - } - if len(m.Strategies) > 0 { - l = 0 - for _, e := range m.Strategies { - l += sovVault(uint64(e)) - } - n += 1 + sovVault(uint64(l)) + l - } - if m.IsPrivateVault { - n += 2 - } - if len(m.AllowedDepositors) > 0 { - for _, b := range m.AllowedDepositors { - l = len(b) - n += 1 + l + sovVault(uint64(l)) - } - } - return n -} - -func (m *VaultRecord) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.TotalShares.Size() - n += 1 + l + sovVault(uint64(l)) - return n -} - -func (m *VaultShareRecord) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovVault(uint64(l)) - } - if len(m.Shares) > 0 { - for _, e := range m.Shares { - l = e.Size() - n += 1 + l + sovVault(uint64(l)) - } - } - return n -} - -func (m *VaultShare) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovVault(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovVault(uint64(l)) - return n -} - -func sovVault(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozVault(x uint64) (n int) { - return sovVault(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *AllowedVault) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AllowedVault: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AllowedVault: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthVault - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthVault - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType == 0 { - var v StrategyType - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= StrategyType(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Strategies = append(m.Strategies, v) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthVault - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthVault - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - if elementCount != 0 && len(m.Strategies) == 0 { - m.Strategies = make([]StrategyType, 0, elementCount) - } - for iNdEx < postIndex { - var v StrategyType - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= StrategyType(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Strategies = append(m.Strategies, v) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field Strategies", wireType) - } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field IsPrivateVault", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.IsPrivateVault = bool(v != 0) - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AllowedDepositors", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthVault - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthVault - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.AllowedDepositors = append(m.AllowedDepositors, make([]byte, postIndex-iNdEx)) - copy(m.AllowedDepositors[len(m.AllowedDepositors)-1], dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipVault(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthVault - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *VaultRecord) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: VaultRecord: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: VaultRecord: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalShares", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthVault - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthVault - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TotalShares.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipVault(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthVault - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *VaultShareRecord) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: VaultShareRecord: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: VaultShareRecord: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthVault - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthVault - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = append(m.Depositor[:0], dAtA[iNdEx:postIndex]...) - if m.Depositor == nil { - m.Depositor = []byte{} - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Shares", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthVault - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthVault - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Shares = append(m.Shares, VaultShare{}) - if err := m.Shares[len(m.Shares)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipVault(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthVault - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *VaultShare) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: VaultShare: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: VaultShare: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthVault - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthVault - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowVault - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthVault - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthVault - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipVault(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthVault - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipVault(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowVault - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowVault - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowVault - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthVault - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupVault - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthVault - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthVault = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowVault = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupVault = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/earn/types/vault_test.go b/x/earn/types/vault_test.go deleted file mode 100644 index 84ab26f1..00000000 --- a/x/earn/types/vault_test.go +++ /dev/null @@ -1,385 +0,0 @@ -package types_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/earn/types" -) - -func TestVaultRecordValidate(t *testing.T) { - type errArgs struct { - expectPass bool - contains string - } - - tests := []struct { - name string - vaultRecords types.VaultRecords - errArgs errArgs - }{ - { - name: "valid vault records", - vaultRecords: types.VaultRecords{ - { - TotalShares: types.NewVaultShare("usdx", sdk.NewDec(0)), - }, - { - TotalShares: types.NewVaultShare("ukava", sdk.NewDec(5)), - }, - }, - errArgs: errArgs{ - expectPass: true, - }, - }, - { - name: "invalid - duplicate denom", - vaultRecords: types.VaultRecords{ - { - TotalShares: types.NewVaultShare("usdx", sdk.NewDec(0)), - }, - { - TotalShares: types.NewVaultShare("usdx", sdk.NewDec(5)), - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "duplicate vault denom usdx", - }, - }, - { - name: "invalid - invalid denom", - vaultRecords: types.VaultRecords{ - { - TotalShares: types.VaultShare{Denom: "", Amount: sdk.NewDec(0)}, - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "invalid denom", - }, - }, - { - name: "invalid - negative", - vaultRecords: types.VaultRecords{ - { - TotalShares: types.VaultShare{"usdx", sdk.NewDec(-5)}, - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "vault share amount -5.000000000000000000 is negative", - }, - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - err := test.vaultRecords.Validate() - - if test.errArgs.expectPass { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), test.errArgs.contains) - } - }) - } -} - -func TestVaultShareRecordsValidate(t *testing.T) { - _, addrs := app.GeneratePrivKeyAddressPairs(2) - - type errArgs struct { - expectPass bool - contains string - } - - tests := []struct { - name string - vaultRecords types.VaultShareRecords - errArgs errArgs - }{ - { - name: "valid vault share records", - vaultRecords: types.VaultShareRecords{ - { - Depositor: addrs[0], - Shares: types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(0)), - ), - }, - { - Depositor: addrs[1], - Shares: types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(0)), - types.NewVaultShare("ukava", sdk.NewDec(5)), - ), - }, - }, - errArgs: errArgs{ - expectPass: true, - }, - }, - { - name: "invalid - duplicate address", - vaultRecords: types.VaultShareRecords{ - { - Depositor: addrs[0], - Shares: types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(0)), - ), - }, - { - Depositor: addrs[0], - Shares: types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(0)), - types.NewVaultShare("ukava", sdk.NewDec(5)), - ), - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "duplicate address", - }, - }, - { - name: "invalid - invalid address", - vaultRecords: types.VaultShareRecords{ - { - Depositor: sdk.AccAddress{}, - Shares: types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(0)), - ), - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "depositor is empty", - }, - }, - { - name: "invalid - negative", - vaultRecords: types.VaultShareRecords{ - { - Depositor: addrs[0], - // Direct slice, not NewVaultShares() which panics - Shares: types.VaultShares{ - types.VaultShare{"usdx", sdk.NewDec(-5)}, - }, - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "invalid vault share record shares: share -5.000000000000000000usdx amount is not positive", - }, - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - err := test.vaultRecords.Validate() - - if test.errArgs.expectPass { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), test.errArgs.contains) - } - }) - } -} - -func TestAllowedVaultsValidate(t *testing.T) { - type errArgs struct { - expectPass bool - contains string - } - - tests := []struct { - name string - vaultRecords types.AllowedVaults - errArgs errArgs - }{ - { - name: "valid vault share records", - vaultRecords: types.AllowedVaults{ - { - Denom: "usdx", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: []sdk.AccAddress{}, - }, - { - Denom: "busd", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: []sdk.AccAddress{}, - }, - }, - errArgs: errArgs{ - expectPass: true, - }, - }, - { - name: "invalid - duplicate denom", - vaultRecords: types.AllowedVaults{ - { - Denom: "usdx", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: []sdk.AccAddress{}, - }, - { - Denom: "usdx", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: []sdk.AccAddress{}, - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "duplicate vault denom usdx", - }, - }, - { - name: "invalid - invalid denom", - vaultRecords: types.AllowedVaults{ - { - Denom: "", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: []sdk.AccAddress{}, - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "invalid denom", - }, - }, - { - name: "invalid - invalid strategy", - vaultRecords: types.AllowedVaults{ - { - Denom: "usdx", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_UNSPECIFIED}, - IsPrivateVault: false, - AllowedDepositors: []sdk.AccAddress{}, - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "invalid strategy STRATEGY_TYPE_UNSPECIFIED", - }, - }, - { - name: "invalid - private with no allowed depositors", - vaultRecords: types.AllowedVaults{ - { - Denom: "usdx", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: true, - AllowedDepositors: []sdk.AccAddress{}, - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "private vaults require non-empty AllowedDepositors", - }, - }, - { - name: "invalid - public with allowed depositors", - vaultRecords: types.AllowedVaults{ - { - Denom: "usdx", - Strategies: []types.StrategyType{types.STRATEGY_TYPE_HARD}, - IsPrivateVault: false, - AllowedDepositors: []sdk.AccAddress{ - sdk.AccAddress("asdfasdf"), - }, - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "non-private vaults cannot have any AllowedDepositors", - }, - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - err := test.vaultRecords.Validate() - - if test.errArgs.expectPass { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), test.errArgs.contains) - } - }) - } -} - -func TestIsStrategyAllowed(t *testing.T) { - vault := types.NewAllowedVault( - "usdx", - []types.StrategyType{types.STRATEGY_TYPE_HARD}, - true, - []sdk.AccAddress{}, - ) - - require.True(t, vault.IsStrategyAllowed(types.STRATEGY_TYPE_HARD)) - require.False(t, vault.IsStrategyAllowed(types.STRATEGY_TYPE_SAVINGS)) - require.False(t, vault.IsStrategyAllowed(types.STRATEGY_TYPE_UNSPECIFIED)) - require.False(t, vault.IsStrategyAllowed(12345)) -} - -func TestIsAccountAllowed_Private(t *testing.T) { - acc1 := sdk.AccAddress("acc1") - acc2 := sdk.AccAddress("acc2") - acc3 := sdk.AccAddress("acc3") - - vault := types.NewAllowedVault( - "usdx", - []types.StrategyType{types.STRATEGY_TYPE_HARD}, - true, - []sdk.AccAddress{acc1, acc2}, - ) - - assert.True(t, vault.IsAccountAllowed(acc1)) - assert.True(t, vault.IsAccountAllowed(acc2)) - assert.False(t, vault.IsAccountAllowed(acc3)) -} - -func TestIsAccountAllowed_Public(t *testing.T) { - acc1 := sdk.AccAddress("acc1") - acc2 := sdk.AccAddress("acc2") - acc3 := sdk.AccAddress("acc3") - - vault := types.NewAllowedVault( - "usdx", - []types.StrategyType{types.STRATEGY_TYPE_HARD}, - false, - []sdk.AccAddress{}, - ) - - assert.True(t, vault.IsAccountAllowed(acc1)) - assert.True(t, vault.IsAccountAllowed(acc2)) - assert.True(t, vault.IsAccountAllowed(acc3)) -} - -func TestNewVaultShareRecord(t *testing.T) { - _, addrs := app.GeneratePrivKeyAddressPairs(1) - - shares := types.NewVaultShares( - types.NewVaultShare("usdx", sdk.NewDec(0)), - types.NewVaultShare("ukava", sdk.NewDec(5)), - ) - - shareRecord := types.NewVaultShareRecord(addrs[0], shares) - require.Equal(t, shares, shareRecord.Shares) -} diff --git a/x/hard/abci.go b/x/hard/abci.go deleted file mode 100644 index e4656cf1..00000000 --- a/x/hard/abci.go +++ /dev/null @@ -1,17 +0,0 @@ -package hard - -import ( - "time" - - "github.com/0glabs/0g-chain/x/hard/keeper" - "github.com/0glabs/0g-chain/x/hard/types" - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// BeginBlocker updates interest rates -func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { - defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) - - k.ApplyInterestRateUpdates(ctx) -} diff --git a/x/hard/client/cli/query.go b/x/hard/client/cli/query.go deleted file mode 100644 index fd87a97e..00000000 --- a/x/hard/client/cli/query.go +++ /dev/null @@ -1,534 +0,0 @@ -package cli - -import ( - "context" - "fmt" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/0glabs/0g-chain/x/hard/types" -) - -// flags for cli queries -const ( - flagName = "name" - flagDenom = "denom" - flagOwner = "owner" -) - -// GetQueryCmd returns the cli query commands for the module -func GetQueryCmd() *cobra.Command { - hardQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the hard module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - queryParamsCmd(), - queryAccountsCmd(), - queryDepositsCmd(), - queryUnsyncedDepositsCmd(), - queryTotalDepositedCmd(), - queryBorrowsCmd(), - queryUnsyncedBorrowsCmd(), - queryTotalBorrowedCmd(), - queryInterestRateCmd(), - queryReserves(), - queryInterestFactorsCmd(), - } - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - hardQueryCmd.AddCommand(cmds...) - - return hardQueryCmd -} - -func queryParamsCmd() *cobra.Command { - return &cobra.Command{ - Use: "params", - Short: "get the hard module parameters", - Long: "Get the current global hard module parameters.", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.Params(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - } -} - -func queryAccountsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "accounts", - Short: "query hard module accounts", - Long: "Query for all hard module accounts", - Example: fmt.Sprintf(`%[1]s q %[2]s accounts -%[1]s q %[2]s accounts`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - req := &types.QueryAccountsRequest{} - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.Accounts(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - return cmd -} - -func queryUnsyncedDepositsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "unsynced-deposits", - Short: "query hard module unsynced deposits with optional filters", - Long: "query for all hard module unsynced deposits or a specific unsynced deposit using flags", - Example: fmt.Sprintf(`%[1]s q %[2]s unsynced-deposits -%[1]s q %[2]s unsynced-deposits --owner kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny --denom bnb -%[1]s q %[2]s unsynced-deposits --denom ukava -%[1]s q %[2]s unsynced-deposits --denom btcb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - ownerBech, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - req := &types.QueryUnsyncedDepositsRequest{ - Denom: denom, - Pagination: pageReq, - } - - if len(ownerBech) != 0 { - depositOwner, err := sdk.AccAddressFromBech32(ownerBech) - if err != nil { - return err - } - req.Owner = depositOwner.String() - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.UnsyncedDeposits(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddPaginationFlagsToCmd(cmd, "unsynced-deposits") - - cmd.Flags().String(flagOwner, "", "(optional) filter for unsynced deposits by owner address") - cmd.Flags().String(flagDenom, "", "(optional) filter for unsynced deposits by denom") - - return cmd -} - -func queryDepositsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "deposits", - Short: "query hard module deposits with optional filters", - Long: "query for all hard module deposits or a specific deposit using flags", - Example: fmt.Sprintf(`%[1]s q %[2]s deposits -%[1]s q %[2]s deposits --owner kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny --denom bnb -%[1]s q %[2]s deposits --denom ukava -%[1]s q %[2]s deposits --denom btcb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - ownerBech, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - req := &types.QueryDepositsRequest{ - Denom: denom, - Pagination: pageReq, - } - - if len(ownerBech) != 0 { - depositOwner, err := sdk.AccAddressFromBech32(ownerBech) - if err != nil { - return err - } - req.Owner = depositOwner.String() - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.Deposits(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddPaginationFlagsToCmd(cmd, "deposits") - - cmd.Flags().String(flagOwner, "", "(optional) filter for deposits by owner address") - cmd.Flags().String(flagDenom, "", "(optional) filter for deposits by denom") - - return cmd -} - -func queryUnsyncedBorrowsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "unsynced-borrows", - Short: "query hard module unsynced borrows with optional filters", - Long: "query for all hard module unsynced borrows or a specific unsynced borrow using flags", - Example: fmt.Sprintf(`%[1]s q %[2]s unsynced-borrows -%[1]s q %[2]s unsynced-borrows --owner kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny -%[1]s q %[2]s unsynced-borrows --denom bnb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - ownerBech, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - req := &types.QueryUnsyncedBorrowsRequest{ - Denom: denom, - Pagination: pageReq, - } - - if len(ownerBech) != 0 { - borrowOwner, err := sdk.AccAddressFromBech32(ownerBech) - if err != nil { - return err - } - req.Owner = borrowOwner.String() - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.UnsyncedBorrows(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddPaginationFlagsToCmd(cmd, "unsynced borrows") - - cmd.Flags().String(flagOwner, "", "(optional) filter for unsynced borrows by owner address") - cmd.Flags().String(flagDenom, "", "(optional) filter for unsynced borrows by denom") - - return cmd -} - -func queryBorrowsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "borrows", - Short: "query hard module borrows with optional filters", - Long: "query for all hard module borrows or a specific borrow using flags", - Example: fmt.Sprintf(`%[1]s q %[2]s borrows -%[1]s q %[2]s borrows --owner kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny -%[1]s q %[2]s borrows --denom bnb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - ownerBech, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - req := &types.QueryBorrowsRequest{ - Denom: denom, - Pagination: pageReq, - } - - if len(ownerBech) != 0 { - borrowOwner, err := sdk.AccAddressFromBech32(ownerBech) - if err != nil { - return err - } - req.Owner = borrowOwner.String() - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.Borrows(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddPaginationFlagsToCmd(cmd, "borrows") - - cmd.Flags().String(flagOwner, "", "(optional) filter for borrows by owner address") - cmd.Flags().String(flagDenom, "", "(optional) filter for borrows by denom") - - return cmd -} - -func queryTotalBorrowedCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "total-borrowed", - Short: "get total current borrowed amount", - Long: "get the total amount of coins currently borrowed using flags", - Example: fmt.Sprintf(`%[1]s q %[2]s total-borrowed -%[1]s q %[2]s total-borrowed --denom bnb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.TotalBorrowed(context.Background(), &types.QueryTotalBorrowedRequest{ - Denom: denom, - }) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - cmd.Flags().String(flagDenom, "", "(optional) filter total borrowed coins by denom") - - return cmd -} - -func queryTotalDepositedCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "total-deposited", - Short: "get total current deposited amount", - Long: "get the total amount of coins currently deposited using flags", - Example: fmt.Sprintf(`%[1]s q %[2]s total-deposited -%[1]s q %[2]s total-deposited --denom bnb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.TotalDeposited(context.Background(), &types.QueryTotalDepositedRequest{ - Denom: denom, - }) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - cmd.Flags().String(flagDenom, "", "(optional) filter total deposited coins by denom") - - return cmd -} - -func queryInterestRateCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "interest-rate", - Short: "get current money market interest rates", - Long: "get current money market interest rates", - Example: fmt.Sprintf(`%[1]s q %[2]s interest-rate -%[1]s q %[2]s interest-rate --denom bnb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.InterestRate(context.Background(), &types.QueryInterestRateRequest{ - Denom: denom, - }) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - cmd.Flags().String(flagDenom, "", "(optional) filter interest rates by denom") - - return cmd -} - -func queryReserves() *cobra.Command { - cmd := &cobra.Command{ - Use: "reserves", - Short: "get total current Hard module reserves", - Long: "get the total amount of coins currently held as reserve by the Hard module", - Example: fmt.Sprintf(`%[1]s q %[2]s reserves -%[1]s q %[2]s reserves --denom bnb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.Reserves(context.Background(), &types.QueryReservesRequest{ - Denom: denom, - }) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - cmd.Flags().String(flagDenom, "", "(optional) filter reserve coins by denom") - - return cmd -} - -func queryInterestFactorsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "interest-factors", - Short: "get current global interest factors", - Long: "get current global interest factors", - Example: fmt.Sprintf(`%[1]s q %[2]s interest-factors -%[1]s q %[2]s interest-factors --denom bnb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.InterestFactors(context.Background(), &types.QueryInterestFactorsRequest{ - Denom: denom, - }) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - cmd.Flags().String(flagDenom, "", "(optional) filter interest factors by denom") - - return cmd -} diff --git a/x/hard/client/cli/tx.go b/x/hard/client/cli/tx.go deleted file mode 100644 index 97725ffe..00000000 --- a/x/hard/client/cli/tx.go +++ /dev/null @@ -1,205 +0,0 @@ -package cli - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/0glabs/0g-chain/x/hard/types" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - hardTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: fmt.Sprintf("%s transactions subcommands", types.ModuleName), - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - getCmdDeposit(), - getCmdWithdraw(), - getCmdBorrow(), - getCmdRepay(), - getCmdLiquidate(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - hardTxCmd.AddCommand(cmds...) - - return hardTxCmd -} - -func getCmdDeposit() *cobra.Command { - return &cobra.Command{ - Use: "deposit [amount]", - Short: "deposit coins to hard", - Example: fmt.Sprintf( - `%s tx %s deposit 10000000bnb --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - amount, err := sdk.ParseCoinsNormalized(args[0]) - if err != nil { - return err - } - msg := types.NewMsgDeposit(clientCtx.GetFromAddress(), amount) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -func getCmdWithdraw() *cobra.Command { - return &cobra.Command{ - Use: "withdraw [amount]", - Short: "withdraw coins from hard", - Args: cobra.ExactArgs(1), - Example: fmt.Sprintf( - `%s tx %s withdraw 10000000bnb --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - amount, err := sdk.ParseCoinsNormalized(args[0]) - if err != nil { - return err - } - msg := types.NewMsgWithdraw(clientCtx.GetFromAddress(), amount) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -func getCmdBorrow() *cobra.Command { - return &cobra.Command{ - Use: "borrow [amount]", - Short: "borrow tokens from the hard protocol", - Long: strings.TrimSpace(`borrows tokens from the hard protocol`), - Args: cobra.ExactArgs(1), - Example: fmt.Sprintf( - `%s tx %s borrow 1000000000ukava --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - coins, err := sdk.ParseCoinsNormalized(args[0]) - if err != nil { - return err - } - - msg := types.NewMsgBorrow(clientCtx.GetFromAddress(), coins) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -func getCmdRepay() *cobra.Command { - cmd := &cobra.Command{ - Use: "repay [amount]", - Short: "repay tokens to the hard protocol", - Long: strings.TrimSpace(`repay tokens to the hard protocol with optional --owner param to repay another account's loan`), - Args: cobra.ExactArgs(1), - Example: fmt.Sprintf(` -%[1]s tx %[2]s repay 1000000000ukava --from -%[1]s tx %[2]s repay 1000000000ukava,25000000000bnb --from -%[1]s tx %[2]s repay 1000000000ukava,25000000000bnb --owner --from `, version.AppName, types.ModuleName), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - var owner sdk.AccAddress - ownerStr, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - - // Parse optional owner argument or default to sender - if len(ownerStr) > 0 { - ownerAddr, err := sdk.AccAddressFromBech32(ownerStr) - if err != nil { - return err - } - owner = ownerAddr - } else { - owner = clientCtx.GetFromAddress() - } - - coins, err := sdk.ParseCoinsNormalized(args[0]) - if err != nil { - return err - } - - msg := types.NewMsgRepay(clientCtx.GetFromAddress(), owner, coins) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } - - cmd.Flags().String(flagOwner, "", "original borrower's address whose loan will be repaid") - - return cmd -} - -func getCmdLiquidate() *cobra.Command { - return &cobra.Command{ - Use: "liquidate [borrower-addr]", - Short: "liquidate a borrower that's over their loan-to-value ratio", - Long: strings.TrimSpace(`liquidate a borrower that's over their loan-to-value ratio`), - Args: cobra.ExactArgs(1), - Example: fmt.Sprintf( - `%s tx %s liquidate kava1hgcfsuwc889wtdmt8pjy7qffua9dd2tralu64j --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - borrower, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - - msg := types.NewMsgLiquidate(clientCtx.GetFromAddress(), borrower) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} diff --git a/x/hard/genesis.go b/x/hard/genesis.go deleted file mode 100644 index bea0bd72..00000000 --- a/x/hard/genesis.go +++ /dev/null @@ -1,116 +0,0 @@ -package hard - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/hard/keeper" - "github.com/0glabs/0g-chain/x/hard/types" -) - -// InitGenesis initializes the store state from a genesis state. -func InitGenesis(ctx sdk.Context, k keeper.Keeper, accountKeeper types.AccountKeeper, gs types.GenesisState) { - if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) - } - - k.SetParams(ctx, gs.Params) - - for _, mm := range gs.Params.MoneyMarkets { - k.SetMoneyMarket(ctx, mm.Denom, mm) - } - - for _, gat := range gs.PreviousAccumulationTimes { - k.SetPreviousAccrualTime(ctx, gat.CollateralType, gat.PreviousAccumulationTime) - k.SetSupplyInterestFactor(ctx, gat.CollateralType, gat.SupplyInterestFactor) - k.SetBorrowInterestFactor(ctx, gat.CollateralType, gat.BorrowInterestFactor) - } - - for _, deposit := range gs.Deposits { - k.SetDeposit(ctx, deposit) - } - - for _, borrow := range gs.Borrows { - k.SetBorrow(ctx, borrow) - } - - k.SetSuppliedCoins(ctx, gs.TotalSupplied) - k.SetBorrowedCoins(ctx, gs.TotalBorrowed) - k.SetTotalReserves(ctx, gs.TotalReserves) - - // check if the module account exists - DepositModuleAccount := accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) - if DepositModuleAccount == nil { - panic(fmt.Sprintf("%s module account has not been set", DepositModuleAccount)) - } -} - -// ExportGenesis export genesis state for hard module -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { - params := k.GetParams(ctx) - - gats := types.GenesisAccumulationTimes{} - deposits := types.Deposits{} - borrows := types.Borrows{} - - k.IterateDeposits(ctx, func(d types.Deposit) bool { - k.BeforeDepositModified(ctx, d) - syncedDeposit, found := k.GetSyncedDeposit(ctx, d.Depositor) - if !found { - panic(fmt.Sprintf("syncable deposit not found for %s", d.Depositor)) - } - deposits = append(deposits, syncedDeposit) - return false - }) - - k.IterateBorrows(ctx, func(b types.Borrow) bool { - k.BeforeBorrowModified(ctx, b) - syncedBorrow, found := k.GetSyncedBorrow(ctx, b.Borrower) - if !found { - panic(fmt.Sprintf("syncable borrow not found for %s", b.Borrower)) - } - borrows = append(borrows, syncedBorrow) - return false - }) - - totalSupplied, found := k.GetSuppliedCoins(ctx) - if !found { - totalSupplied = types.DefaultTotalSupplied - } - totalBorrowed, found := k.GetBorrowedCoins(ctx) - if !found { - totalBorrowed = types.DefaultTotalBorrowed - } - totalReserves, found := k.GetTotalReserves(ctx) - if !found { - totalReserves = types.DefaultTotalReserves - } - - for _, mm := range params.MoneyMarkets { - supplyFactor, f := k.GetSupplyInterestFactor(ctx, mm.Denom) - if !f { - supplyFactor = sdk.OneDec() - } - borrowFactor, f := k.GetBorrowInterestFactor(ctx, mm.Denom) - if !f { - borrowFactor = sdk.OneDec() - } - previousAccrualTime, f := k.GetPreviousAccrualTime(ctx, mm.Denom) - if !f { - // Goverance adds new params at end of block, but mm's previous accrual time is set in begin blocker. - // If a new money market is added and chain is exported before begin blocker runs, then the previous - // accrual time will not be found. We can't set it here because our ctx doesn't contain current block - // time; if we set it to ctx.BlockTime() then on the next block it could accrue interest from Jan 1st - // 0001 to now. To avoid setting up a bad state, we panic. - panic(fmt.Sprintf("expected previous accrual time to be set in state for %s", mm.Denom)) - } - gat := types.NewGenesisAccumulationTime(mm.Denom, previousAccrualTime, supplyFactor, borrowFactor) - gats = append(gats, gat) - - } - return types.NewGenesisState( - params, gats, deposits, borrows, - totalSupplied, totalBorrowed, totalReserves, - ) -} diff --git a/x/hard/genesis_test.go b/x/hard/genesis_test.go deleted file mode 100644 index fc16e2ac..00000000 --- a/x/hard/genesis_test.go +++ /dev/null @@ -1,202 +0,0 @@ -package hard_test - -import ( - "fmt" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/hard" - "github.com/0glabs/0g-chain/x/hard/keeper" - "github.com/0glabs/0g-chain/x/hard/types" -) - -type GenesisTestSuite struct { - suite.Suite - - app app.TestApp - genTime time.Time - ctx sdk.Context - keeper keeper.Keeper - addrs []sdk.AccAddress -} - -func (suite *GenesisTestSuite) SetupTest() { - tApp := app.NewTestApp() - suite.genTime = tmtime.Canonical(time.Date(2021, 1, 1, 1, 1, 1, 1, time.UTC)) - suite.ctx = tApp.NewContext(true, tmproto.Header{Height: 1, Time: suite.genTime}) - suite.keeper = tApp.GetHardKeeper() - suite.app = tApp - - _, addrs := app.GeneratePrivKeyAddressPairs(3) - suite.addrs = addrs -} - -func (suite *GenesisTestSuite) Test_InitExportGenesis() { - loanToValue, _ := sdk.NewDecFromStr("0.6") - params := types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket( - "ukava", - types.NewBorrowLimit( - false, - sdk.NewDec(1e15), - loanToValue, - ), - "kava:usd", - sdkmath.NewInt(1e6), - types.NewInterestRateModel( - sdk.MustNewDecFromStr("0.05"), - sdk.MustNewDecFromStr("2"), - sdk.MustNewDecFromStr("0.8"), - sdk.MustNewDecFromStr("10"), - ), - sdk.MustNewDecFromStr("0.05"), - sdk.ZeroDec(), - ), - }, - sdk.NewDec(10), - ) - - deposits := types.Deposits{ - types.NewDeposit( - suite.addrs[0], - sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e8))), // 100 ukava - types.SupplyInterestFactors{ - { - Denom: "ukava", - Value: sdk.NewDec(1), - }, - }, - ), - } - - var totalSupplied sdk.Coins - for _, deposit := range deposits { - totalSupplied = totalSupplied.Add(deposit.Amount...) - } - - borrows := types.Borrows{ - types.NewBorrow( - suite.addrs[1], - sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e7))), // 10 ukava - types.BorrowInterestFactors{ - { - Denom: "ukava", - Value: sdk.NewDec(1), - }, - }, - ), - } - - var totalBorrowed sdk.Coins - for _, borrow := range borrows { - totalBorrowed = totalBorrowed.Add(borrow.Amount...) - } - - supplyInterestFactor := sdk.MustNewDecFromStr("1.0001") - borrowInterestFactor := sdk.MustNewDecFromStr("1.1234") - accuralTimes := types.GenesisAccumulationTimes{ - types.NewGenesisAccumulationTime("ukava", suite.genTime, supplyInterestFactor, borrowInterestFactor), - } - - hardGenesis := types.NewGenesisState( - params, - accuralTimes, - deposits, - borrows, - totalSupplied, - totalBorrowed, - sdk.Coins{}, - ) - - suite.NotPanics( - func() { - suite.app.InitializeFromGenesisStatesWithTime( - suite.genTime, - app.GenesisState{types.ModuleName: suite.app.AppCodec().MustMarshalJSON(&hardGenesis)}, - ) - }, - ) - - var expectedDeposits types.Deposits - for _, deposit := range deposits { - // Deposit coin amounts - var depositAmount sdk.Coins - for _, coin := range deposit.Amount { - accrualTime, found := getGenesisAccumulationTime(coin.Denom, accuralTimes) - if !found { - panic(fmt.Sprintf("accrual time not found %s", coin.Denom)) - } - expectedAmt := accrualTime.SupplyInterestFactor.MulInt(coin.Amount).RoundInt() - depositAmount = depositAmount.Add(sdk.NewCoin(coin.Denom, expectedAmt)) - } - deposit.Amount = depositAmount - // Deposit interest factor indexes - var indexes types.SupplyInterestFactors - for _, index := range deposit.Index { - accrualTime, found := getGenesisAccumulationTime(index.Denom, accuralTimes) - if !found { - panic(fmt.Sprintf("accrual time not found %s", index.Denom)) - } - index.Value = accrualTime.SupplyInterestFactor - indexes = append(indexes, index) - } - deposit.Index = indexes - expectedDeposits = append(expectedDeposits, deposit) - } - - var expectedBorrows types.Borrows - for _, borrow := range borrows { - // Borrow coin amounts - var borrowAmount sdk.Coins - for _, coin := range borrow.Amount { - accrualTime, found := getGenesisAccumulationTime(coin.Denom, accuralTimes) - if !found { - panic(fmt.Sprintf("accrual time not found %s", coin.Denom)) - } - expectedAmt := accrualTime.BorrowInterestFactor.MulInt(coin.Amount).RoundInt() - borrowAmount = borrowAmount.Add(sdk.NewCoin(coin.Denom, expectedAmt)) - - } - borrow.Amount = borrowAmount - // Borrow interest factor indexes - var indexes types.BorrowInterestFactors - for _, index := range borrow.Index { - accrualTime, found := getGenesisAccumulationTime(index.Denom, accuralTimes) - if !found { - panic(fmt.Sprintf("accrual time not found %s", index.Denom)) - } - index.Value = accrualTime.BorrowInterestFactor - indexes = append(indexes, index) - } - borrow.Index = indexes - expectedBorrows = append(expectedBorrows, borrow) - } - - expectedGenesis := hardGenesis - expectedGenesis.Deposits = expectedDeposits - expectedGenesis.Borrows = expectedBorrows - exportedGenesis := hard.ExportGenesis(suite.ctx, suite.keeper) - suite.Equal(expectedGenesis, exportedGenesis) -} - -func getGenesisAccumulationTime(denom string, ts types.GenesisAccumulationTimes) (types.GenesisAccumulationTime, bool) { - for _, t := range ts { - if t.CollateralType == denom { - return t, true - } - } - return types.GenesisAccumulationTime{}, false -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(GenesisTestSuite)) -} diff --git a/x/hard/keeper/borrow.go b/x/hard/keeper/borrow.go deleted file mode 100644 index 98588a40..00000000 --- a/x/hard/keeper/borrow.go +++ /dev/null @@ -1,302 +0,0 @@ -package keeper - -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" - - "github.com/0glabs/0g-chain/x/hard/types" -) - -// Borrow funds -func (k Keeper) Borrow(ctx sdk.Context, borrower sdk.AccAddress, coins sdk.Coins) error { - // Set any new denoms' global borrow index to 1.0 - for _, coin := range coins { - _, foundInterestFactor := k.GetBorrowInterestFactor(ctx, coin.Denom) - if !foundInterestFactor { - _, foundMm := k.GetMoneyMarket(ctx, coin.Denom) - if foundMm { - k.SetBorrowInterestFactor(ctx, coin.Denom, sdk.OneDec()) - } - } - } - - // Call incentive hooks - existingDeposit, hasExistingDeposit := k.GetDeposit(ctx, borrower) - if hasExistingDeposit { - k.BeforeDepositModified(ctx, existingDeposit) - } - existingBorrow, hasExistingBorrow := k.GetBorrow(ctx, borrower) - if hasExistingBorrow { - k.BeforeBorrowModified(ctx, existingBorrow) - } - - k.SyncSupplyInterest(ctx, borrower) - k.SyncBorrowInterest(ctx, borrower) - - // Validate borrow amount within user and protocol limits - err := k.ValidateBorrow(ctx, borrower, coins) - if err != nil { - return err - } - - // Sends coins from Hard module account to user - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, borrower, coins) - if err != nil { - if errors.Is(err, sdkerrors.ErrInsufficientFunds) { - macc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) - modAccCoins := k.bankKeeper.GetAllBalances(ctx, macc.GetAddress()) - for _, coin := range coins { - _, isNegative := modAccCoins.SafeSub(coin) - if isNegative { - return errorsmod.Wrapf(types.ErrBorrowExceedsAvailableBalance, - "the requested borrow amount of %s exceeds the total amount of %s%s available to borrow", - coin, modAccCoins.AmountOf(coin.Denom), coin.Denom, - ) - } - } - } - return err - } - - interestFactors := types.BorrowInterestFactors{} - currBorrow, foundBorrow := k.GetBorrow(ctx, borrower) - if foundBorrow { - interestFactors = currBorrow.Index - } - for _, coin := range coins { - interestFactorValue, foundValue := k.GetBorrowInterestFactor(ctx, coin.Denom) - if foundValue { - interestFactors = interestFactors.SetInterestFactor(coin.Denom, interestFactorValue) - } - } - - // Calculate new borrow amount - var amount sdk.Coins - if foundBorrow { - amount = currBorrow.Amount.Add(coins...) - } else { - amount = coins - } - - // Construct the user's new/updated borrow with amount and interest factors - borrow := types.NewBorrow(borrower, amount, interestFactors) - if borrow.Amount.Empty() { - k.DeleteBorrow(ctx, borrow) - } else { - k.SetBorrow(ctx, borrow) - } - - // Update total borrowed amount by newly borrowed coins. Don't add user's pending interest as - // it has already been included in the total borrowed coins by the BeginBlocker. - k.IncrementBorrowedCoins(ctx, coins) - - if !hasExistingBorrow { - k.AfterBorrowCreated(ctx, borrow) - } else { - k.AfterBorrowModified(ctx, borrow) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeHardBorrow, - sdk.NewAttribute(types.AttributeKeyBorrower, borrower.String()), - sdk.NewAttribute(types.AttributeKeyBorrowCoins, coins.String()), - ), - ) - - return nil -} - -// ValidateBorrow validates a borrow request against borrower and protocol requirements -func (k Keeper) ValidateBorrow(ctx sdk.Context, borrower sdk.AccAddress, amount sdk.Coins) error { - if amount.IsZero() { - return types.ErrBorrowEmptyCoins - } - - // The reserve coins aren't available for users to borrow - macc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - hardMaccCoins := k.bankKeeper.GetAllBalances(ctx, macc.GetAddress()) - reserveCoins, foundReserveCoins := k.GetTotalReserves(ctx) - if !foundReserveCoins { - reserveCoins = sdk.NewCoins() - } - fundsAvailableToBorrow, isNegative := hardMaccCoins.SafeSub(reserveCoins...) - if isNegative { - return errorsmod.Wrapf(types.ErrReservesExceedCash, "reserves %s > cash %s", reserveCoins, hardMaccCoins) - } - if amount.IsAnyGT(fundsAvailableToBorrow) { - return errorsmod.Wrapf(types.ErrExceedsProtocolBorrowableBalance, "requested borrow %s > available to borrow %s", amount, fundsAvailableToBorrow) - } - - // Get the proposed borrow USD value - proprosedBorrowUSDValue := sdk.ZeroDec() - for _, coin := range amount { - moneyMarket, found := k.GetMoneyMarket(ctx, coin.Denom) - if !found { - return errorsmod.Wrapf(types.ErrMarketNotFound, "no money market found for denom %s", coin.Denom) - } - - // Calculate this coin's USD value and add it borrow's total USD value - assetPriceInfo, err := k.pricefeedKeeper.GetCurrentPrice(ctx, moneyMarket.SpotMarketID) - if err != nil { - return errorsmod.Wrapf(types.ErrPriceNotFound, "no price found for market %s", moneyMarket.SpotMarketID) - } - coinUSDValue := sdk.NewDecFromInt(coin.Amount).Quo(sdk.NewDecFromInt(moneyMarket.ConversionFactor)).Mul(assetPriceInfo.Price) - - // Validate the requested borrow value for the asset against the money market's global borrow limit - if moneyMarket.BorrowLimit.HasMaxLimit { - var assetTotalBorrowedAmount sdkmath.Int - totalBorrowedCoins, found := k.GetBorrowedCoins(ctx) - if !found { - assetTotalBorrowedAmount = sdk.ZeroInt() - } else { - assetTotalBorrowedAmount = totalBorrowedCoins.AmountOf(coin.Denom) - } - newProposedAssetTotalBorrowedAmount := sdk.NewDecFromInt(assetTotalBorrowedAmount.Add(coin.Amount)) - if newProposedAssetTotalBorrowedAmount.GT(moneyMarket.BorrowLimit.MaximumLimit) { - return errorsmod.Wrapf(types.ErrGreaterThanAssetBorrowLimit, - "proposed borrow would result in %s borrowed, but the maximum global asset borrow limit is %s", - newProposedAssetTotalBorrowedAmount, moneyMarket.BorrowLimit.MaximumLimit) - } - } - proprosedBorrowUSDValue = proprosedBorrowUSDValue.Add(coinUSDValue) - } - - // Get the total borrowable USD amount at user's existing deposits - deposit, found := k.GetDeposit(ctx, borrower) - if !found { - return errorsmod.Wrapf(types.ErrDepositsNotFound, "no deposits found for %s", borrower) - } - totalBorrowableAmount := sdk.ZeroDec() - for _, coin := range deposit.Amount { - moneyMarket, found := k.GetMoneyMarket(ctx, coin.Denom) - if !found { - return errorsmod.Wrapf(types.ErrMarketNotFound, "no money market found for denom %s", coin.Denom) - } - - // Calculate the borrowable amount and add it to the user's total borrowable amount - assetPriceInfo, err := k.pricefeedKeeper.GetCurrentPrice(ctx, moneyMarket.SpotMarketID) - if err != nil { - return errorsmod.Wrapf(types.ErrPriceNotFound, "no price found for market %s", moneyMarket.SpotMarketID) - } - depositUSDValue := sdk.NewDecFromInt(coin.Amount).Quo(sdk.NewDecFromInt(moneyMarket.ConversionFactor)).Mul(assetPriceInfo.Price) - borrowableAmountForDeposit := depositUSDValue.Mul(moneyMarket.BorrowLimit.LoanToValue) - totalBorrowableAmount = totalBorrowableAmount.Add(borrowableAmountForDeposit) - } - - // Get the total USD value of user's existing borrows - existingBorrowUSDValue := sdk.ZeroDec() - existingBorrow, found := k.GetBorrow(ctx, borrower) - if found { - for _, coin := range existingBorrow.Amount { - moneyMarket, found := k.GetMoneyMarket(ctx, coin.Denom) - if !found { - return errorsmod.Wrapf(types.ErrMarketNotFound, "no money market found for denom %s", coin.Denom) - } - - // Calculate this borrow coin's USD value and add it to the total previous borrowed USD value - assetPriceInfo, err := k.pricefeedKeeper.GetCurrentPrice(ctx, moneyMarket.SpotMarketID) - if err != nil { - return errorsmod.Wrapf(types.ErrPriceNotFound, "no price found for market %s", moneyMarket.SpotMarketID) - } - coinUSDValue := sdk.NewDecFromInt(coin.Amount).Quo(sdk.NewDecFromInt(moneyMarket.ConversionFactor)).Mul(assetPriceInfo.Price) - existingBorrowUSDValue = existingBorrowUSDValue.Add(coinUSDValue) - } - } - - // Borrow's updated total USD value must be greater than the minimum global USD borrow limit - totalBorrowUSDValue := proprosedBorrowUSDValue.Add(existingBorrowUSDValue) - if totalBorrowUSDValue.LT(k.GetMinimumBorrowUSDValue(ctx)) { - return errorsmod.Wrapf(types.ErrBelowMinimumBorrowValue, "the proposed borrow's USD value $%s is below the minimum borrow limit $%s", totalBorrowUSDValue, k.GetMinimumBorrowUSDValue(ctx)) - } - - // Validate that the proposed borrow's USD value is within user's borrowable limit - if proprosedBorrowUSDValue.GT(totalBorrowableAmount.Sub(existingBorrowUSDValue)) { - return errorsmod.Wrapf(types.ErrInsufficientLoanToValue, "requested borrow %s exceeds the allowable amount as determined by the collateralization ratio", amount) - } - return nil -} - -// IncrementBorrowedCoins increments the total amount of borrowed coins by the newCoins parameter -func (k Keeper) IncrementBorrowedCoins(ctx sdk.Context, newCoins sdk.Coins) { - borrowedCoins, found := k.GetBorrowedCoins(ctx) - if !found { - if !newCoins.Empty() { - k.SetBorrowedCoins(ctx, newCoins) - } - } else { - k.SetBorrowedCoins(ctx, borrowedCoins.Add(newCoins...)) - } -} - -// DecrementBorrowedCoins decrements the total amount of borrowed coins by the coins parameter -func (k Keeper) DecrementBorrowedCoins(ctx sdk.Context, coins sdk.Coins) error { - borrowedCoins, found := k.GetBorrowedCoins(ctx) - if !found { - return errorsmod.Wrapf(types.ErrBorrowedCoinsNotFound, "cannot repay coins if no coins are currently borrowed") - } - - updatedBorrowedCoins, isNegative := borrowedCoins.SafeSub(coins...) - if isNegative { - coinsToSubtract := sdk.NewCoins() - for _, coin := range coins { - if borrowedCoins.AmountOf(coin.Denom).LT(coin.Amount) { - if borrowedCoins.AmountOf(coin.Denom).GT(sdk.ZeroInt()) { - coinsToSubtract = coinsToSubtract.Add(sdk.NewCoin(coin.Denom, borrowedCoins.AmountOf(coin.Denom))) - } - } else { - coinsToSubtract = coinsToSubtract.Add(coin) - } - } - updatedBorrowedCoins = borrowedCoins.Sub(coinsToSubtract...) - } - - k.SetBorrowedCoins(ctx, updatedBorrowedCoins) - return nil -} - -// GetSyncedBorrow returns a borrow object containing current balances and indexes -func (k Keeper) GetSyncedBorrow(ctx sdk.Context, borrower sdk.AccAddress) (types.Borrow, bool) { - borrow, found := k.GetBorrow(ctx, borrower) - if !found { - return types.Borrow{}, false - } - - return k.loadSyncedBorrow(ctx, borrow), true -} - -// loadSyncedBorrow calculates a user's synced borrow, but does not update state -func (k Keeper) loadSyncedBorrow(ctx sdk.Context, borrow types.Borrow) types.Borrow { - totalNewInterest := sdk.Coins{} - newBorrowIndexes := types.BorrowInterestFactors{} - for _, coin := range borrow.Amount { - interestFactorValue, foundInterestFactorValue := k.GetBorrowInterestFactor(ctx, coin.Denom) - if foundInterestFactorValue { - // Locate the interest factor by coin denom in the user's list of interest factors - foundAtIndex := -1 - for i := range borrow.Index { - if borrow.Index[i].Denom == coin.Denom { - foundAtIndex = i - break - } - } - - // Calculate interest owed by user for this asset - if foundAtIndex != -1 { - storedAmount := sdk.NewDecFromInt(borrow.Amount.AmountOf(coin.Denom)) - userLastInterestFactor := borrow.Index[foundAtIndex].Value - coinInterest := (storedAmount.Quo(userLastInterestFactor).Mul(interestFactorValue)).Sub(storedAmount) - totalNewInterest = totalNewInterest.Add(sdk.NewCoin(coin.Denom, coinInterest.TruncateInt())) - } - } - - borrowIndex := types.NewBorrowInterestFactor(coin.Denom, interestFactorValue) - newBorrowIndexes = append(newBorrowIndexes, borrowIndex) - } - - return types.NewBorrow(borrow.Borrower, borrow.Amount.Add(totalNewInterest...), newBorrowIndexes) -} diff --git a/x/hard/keeper/borrow_test.go b/x/hard/keeper/borrow_test.go deleted file mode 100644 index 578aa51c..00000000 --- a/x/hard/keeper/borrow_test.go +++ /dev/null @@ -1,564 +0,0 @@ -package keeper_test - -import ( - "strings" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/hard" - "github.com/0glabs/0g-chain/x/hard/types" - pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" -) - -const ( - USDX_CF = 1000000 - KAVA_CF = 1000000 - BTCB_CF = 100000000 - BNB_CF = 100000000 - BUSD_CF = 100000000 -) - -func (suite *KeeperTestSuite) TestBorrow() { - type args struct { - usdxBorrowLimit sdk.Dec - priceKAVA sdk.Dec - loanToValueKAVA sdk.Dec - priceBTCB sdk.Dec - loanToValueBTCB sdk.Dec - priceBNB sdk.Dec - loanToValueBNB sdk.Dec - borrower sdk.AccAddress - depositCoins []sdk.Coin - previousBorrowCoins sdk.Coins - borrowCoins sdk.Coins - expectedAccountBalance sdk.Coins - expectedModAccountBalance sdk.Coins - } - type errArgs struct { - expectPass bool - contains string - } - type borrowTest struct { - name string - args args - errArgs errArgs - } - testCases := []borrowTest{ - { - "valid", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("100000000000"), - priceKAVA: sdk.MustNewDecFromStr("5.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.6"), - priceBTCB: sdk.MustNewDecFromStr("0.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.01"), - priceBNB: sdk.MustNewDecFromStr("0.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.01"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: []sdk.Coin{sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))}, - previousBorrowCoins: sdk.NewCoins(), - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF)), sdk.NewCoin("btcb", sdkmath.NewInt(100*BTCB_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(100*BNB_CF)), sdk.NewCoin("xyz", sdkmath.NewInt(1))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1080*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(200*USDX_CF)), sdk.NewCoin("busd", sdkmath.NewInt(100*BUSD_CF))), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "invalid: loan-to-value limited", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("100000000000"), - priceKAVA: sdk.MustNewDecFromStr("5.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.6"), - priceBTCB: sdk.MustNewDecFromStr("0.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.01"), - priceBNB: sdk.MustNewDecFromStr("0.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.01"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: []sdk.Coin{sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))}, // 20 KAVA x $5.00 price = $100 - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(61*USDX_CF))), // 61 USDX x $1 price = $61 - expectedAccountBalance: sdk.NewCoins(), - expectedModAccountBalance: sdk.NewCoins(), - }, - errArgs{ - expectPass: false, - contains: "exceeds the allowable amount as determined by the collateralization ratio", - }, - }, - { - "valid: multiple deposits", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("100000000000"), - priceKAVA: sdk.MustNewDecFromStr("2.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.80"), - priceBTCB: sdk.MustNewDecFromStr("10000.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.10"), - priceBNB: sdk.MustNewDecFromStr("0.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.01"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF)), sdk.NewCoin("btcb", sdkmath.NewInt(0.1*BTCB_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(180*USDX_CF))), - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF)), sdk.NewCoin("btcb", sdkmath.NewInt(99.9*BTCB_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(180*USDX_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(100*BNB_CF)), sdk.NewCoin("xyz", sdkmath.NewInt(1))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1050*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(20*USDX_CF)), sdk.NewCoin("btcb", sdkmath.NewInt(0.1*BTCB_CF)), sdk.NewCoin("busd", sdkmath.NewInt(100*BUSD_CF))), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "invalid: multiple deposits", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("100000000000"), - priceKAVA: sdk.MustNewDecFromStr("2.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.80"), - priceBTCB: sdk.MustNewDecFromStr("10000.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.10"), - priceBNB: sdk.MustNewDecFromStr("0.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.01"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF)), sdk.NewCoin("btcb", sdkmath.NewInt(0.1*BTCB_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(181*USDX_CF))), - expectedAccountBalance: sdk.NewCoins(), - expectedModAccountBalance: sdk.NewCoins(), - }, - errArgs{ - expectPass: false, - contains: "exceeds the allowable amount as determined by the collateralization ratio", - }, - }, - { - "valid: multiple previous borrows", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("100000000000"), - priceKAVA: sdk.MustNewDecFromStr("2.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.8"), - priceBTCB: sdk.MustNewDecFromStr("0.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.01"), - priceBNB: sdk.MustNewDecFromStr("5.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.8"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(30*BNB_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), // (50 KAVA x $2.00 price = $100) + (30 BNB x $5.00 price = $150) = $250 - previousBorrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(99*USDX_CF)), sdk.NewCoin("busd", sdkmath.NewInt(100*BUSD_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(1*USDX_CF))), - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF)), sdk.NewCoin("btcb", sdkmath.NewInt(100*BTCB_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF)), sdk.NewCoin("busd", sdkmath.NewInt(100*BUSD_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(70*BNB_CF)), sdk.NewCoin("xyz", sdkmath.NewInt(1))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1050*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(30*BUSD_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF))), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "invalid: over loan-to-value with multiple previous borrows", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("100000000000"), - priceKAVA: sdk.MustNewDecFromStr("2.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.8"), - priceBTCB: sdk.MustNewDecFromStr("0.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.01"), - priceBNB: sdk.MustNewDecFromStr("5.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.8"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(30*BNB_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), // (50 KAVA x $2.00 price = $100) + (30 BNB x $5.00 price = $150) = $250 - previousBorrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF)), sdk.NewCoin("busd", sdkmath.NewInt(100*BUSD_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(1*USDX_CF))), - expectedAccountBalance: sdk.NewCoins(), - expectedModAccountBalance: sdk.NewCoins(), - }, - errArgs{ - expectPass: false, - contains: "exceeds the allowable amount as determined by the collateralization ratio", - }, - }, - { - "invalid: no price for asset", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("100000000000"), - priceKAVA: sdk.MustNewDecFromStr("5.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.6"), - priceBTCB: sdk.MustNewDecFromStr("0.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.01"), - priceBNB: sdk.MustNewDecFromStr("0.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.01"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - previousBorrowCoins: sdk.NewCoins(), - borrowCoins: sdk.NewCoins(sdk.NewCoin("xyz", sdkmath.NewInt(1))), - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF)), sdk.NewCoin("btcb", sdkmath.NewInt(100*BTCB_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(100*BNB_CF)), sdk.NewCoin("xyz", sdkmath.NewInt(1))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1080*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(200*USDX_CF)), sdk.NewCoin("busd", sdkmath.NewInt(100*BUSD_CF))), - }, - errArgs{ - expectPass: false, - contains: "no price found for market", - }, - }, - { - "invalid: borrow exceed module account balance", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("100000000000"), - priceKAVA: sdk.MustNewDecFromStr("2.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.8"), - priceBTCB: sdk.MustNewDecFromStr("0.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.01"), - priceBNB: sdk.MustNewDecFromStr("0.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.01"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - previousBorrowCoins: sdk.NewCoins(), - borrowCoins: sdk.NewCoins(sdk.NewCoin("busd", sdkmath.NewInt(101*BUSD_CF))), - expectedAccountBalance: sdk.NewCoins(), - expectedModAccountBalance: sdk.NewCoins(), - }, - errArgs{ - expectPass: false, - contains: "exceeds borrowable module account balance", - }, - }, - { - "invalid: over global asset borrow limit", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("20000000"), - priceKAVA: sdk.MustNewDecFromStr("2.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.8"), - priceBTCB: sdk.MustNewDecFromStr("0.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.01"), - priceBNB: sdk.MustNewDecFromStr("0.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.01"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - previousBorrowCoins: sdk.NewCoins(), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(25*USDX_CF))), - expectedAccountBalance: sdk.NewCoins(), - expectedModAccountBalance: sdk.NewCoins(), - }, - errArgs{ - expectPass: false, - contains: "fails global asset borrow limit validation", - }, - }, - { - "invalid: borrowing an individual coin type results in a borrow that's under the minimum USD borrow limit", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("20000000"), - priceKAVA: sdk.MustNewDecFromStr("2.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.8"), - priceBTCB: sdk.MustNewDecFromStr("0.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.01"), - priceBNB: sdk.MustNewDecFromStr("0.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.01"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - previousBorrowCoins: sdk.NewCoins(), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(5*USDX_CF))), - expectedAccountBalance: sdk.NewCoins(), - expectedModAccountBalance: sdk.NewCoins(), - }, - errArgs{ - expectPass: false, - contains: "below the minimum borrow limit", - }, - }, - { - "invalid: borrowing multiple coins results in a borrow that's under the minimum USD borrow limit", - args{ - usdxBorrowLimit: sdk.MustNewDecFromStr("20000000"), - priceKAVA: sdk.MustNewDecFromStr("2.00"), - loanToValueKAVA: sdk.MustNewDecFromStr("0.8"), - priceBTCB: sdk.MustNewDecFromStr("0.00"), - loanToValueBTCB: sdk.MustNewDecFromStr("0.01"), - priceBNB: sdk.MustNewDecFromStr("0.00"), - loanToValueBNB: sdk.MustNewDecFromStr("0.01"), - borrower: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - previousBorrowCoins: sdk.NewCoins(), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(5*USDX_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(2*USDX_CF))), - expectedAccountBalance: sdk.NewCoins(), - expectedModAccountBalance: sdk.NewCoins(), - }, - errArgs{ - expectPass: false, - contains: "below the minimum borrow limit", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - // Auth module genesis state - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{ - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF)), - sdk.NewCoin("btcb", sdkmath.NewInt(100*BTCB_CF)), - sdk.NewCoin("bnb", sdkmath.NewInt(100*BNB_CF)), - sdk.NewCoin("xyz", sdkmath.NewInt(1)), - ), - }, - []sdk.AccAddress{tc.args.borrower}, - ) - - // hard module genesis state - hardGS := types.NewGenesisState(types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("usdx", types.NewBorrowLimit(true, tc.args.usdxBorrowLimit, sdk.MustNewDecFromStr("1")), "usdx:usd", sdkmath.NewInt(USDX_CF), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("busd", types.NewBorrowLimit(false, sdk.NewDec(100000000*BUSD_CF), sdk.MustNewDecFromStr("1")), "busd:usd", sdkmath.NewInt(BUSD_CF), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("ukava", types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), tc.args.loanToValueKAVA), "kava:usd", sdkmath.NewInt(KAVA_CF), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("btcb", types.NewBorrowLimit(false, sdk.NewDec(100000000*BTCB_CF), tc.args.loanToValueBTCB), "btcb:usd", sdkmath.NewInt(BTCB_CF), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("bnb", types.NewBorrowLimit(false, sdk.NewDec(100000000*BNB_CF), tc.args.loanToValueBNB), "bnb:usd", sdkmath.NewInt(BNB_CF), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("xyz", types.NewBorrowLimit(false, sdk.NewDec(1), tc.args.loanToValueBNB), "xyz:usd", sdkmath.NewInt(1), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - }, - sdk.NewDec(10), - ), types.DefaultAccumulationTimes, types.DefaultDeposits, types.DefaultBorrows, - types.DefaultTotalSupplied, types.DefaultTotalBorrowed, types.DefaultTotalReserves, - ) - - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "usdx:usd", BaseAsset: "usdx", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "busd:usd", BaseAsset: "busd", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "btcb:usd", BaseAsset: "btcb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "xyz:usd", BaseAsset: "xyz", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "usdx:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "busd:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: tc.args.priceKAVA, - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "btcb:usd", - OracleAddress: sdk.AccAddress{}, - Price: tc.args.priceBTCB, - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: tc.args.priceBNB, - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - - // Initialize test application - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}) - - // Mint coins to hard module account - bankKeeper := tApp.GetBankKeeper() - hardMaccCoins := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), - sdk.NewCoin("usdx", sdkmath.NewInt(200*USDX_CF)), sdk.NewCoin("busd", sdkmath.NewInt(100*BUSD_CF))) - err := bankKeeper.MintCoins(ctx, types.ModuleAccountName, hardMaccCoins) - suite.Require().NoError(err) - - keeper := tApp.GetHardKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - - // Run BeginBlocker once to transition MoneyMarkets - hard.BeginBlocker(suite.ctx, suite.keeper) - - err = suite.keeper.Deposit(suite.ctx, tc.args.borrower, tc.args.depositCoins) - suite.Require().NoError(err) - - // Execute user's previous borrows - err = suite.keeper.Borrow(suite.ctx, tc.args.borrower, tc.args.previousBorrowCoins) - if tc.args.previousBorrowCoins.IsZero() { - suite.Require().True(strings.Contains(err.Error(), "cannot borrow zero coins")) - } else { - suite.Require().NoError(err) - } - - // Now that our state is properly set up, execute the last borrow - err = suite.keeper.Borrow(suite.ctx, tc.args.borrower, tc.args.borrowCoins) - - if tc.errArgs.expectPass { - suite.Require().NoError(err) - - // Check borrower balance - acc := suite.getAccount(tc.args.borrower) - suite.Require().Equal(tc.args.expectedAccountBalance, suite.getAccountCoins(acc)) - - // Check module account balance - mAcc := suite.getModuleAccount(types.ModuleAccountName) - suite.Require().Equal(tc.args.expectedModAccountBalance, suite.getAccountCoins(mAcc)) - - // Check that borrow struct is in store - _, f := suite.keeper.GetBorrow(suite.ctx, tc.args.borrower) - suite.Require().True(f) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *KeeperTestSuite) TestValidateBorrow() { - blockDuration := time.Second * 3600 * 24 // long blocks to accumulate larger interest - - _, addrs := app.GeneratePrivKeyAddressPairs(5) - borrower := addrs[0] - initialBorrowerBalance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), - sdk.NewCoin("usdx", sdkmath.NewInt(1000*KAVA_CF)), - ) - - model := types.NewInterestRateModel(sdk.MustNewDecFromStr("1.0"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")) - - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - // Auth module genesis state - authGS := app.NewFundedGenStateWithSameCoins( - tApp.AppCodec(), - initialBorrowerBalance, - []sdk.AccAddress{borrower}, - ) - - // Hard module genesis state - hardGS := types.NewGenesisState( - types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("usdx", - types.NewBorrowLimit(false, sdk.NewDec(100000000*USDX_CF), sdk.MustNewDecFromStr("1")), // Borrow Limit - "usdx:usd", // Market ID - sdkmath.NewInt(USDX_CF), // Conversion Factor - model, // Interest Rate Model - sdk.MustNewDecFromStr("1.0"), // Reserve Factor (high) - sdk.MustNewDecFromStr("0.05")), // Keeper Reward Percent - types.NewMoneyMarket("ukava", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "kava:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - model, // Interest Rate Model - sdk.MustNewDecFromStr("1.0"), // Reserve Factor (high) - sdk.MustNewDecFromStr("0.05")), // Keeper Reward Percent - }, - sdk.NewDec(10), - ), - types.DefaultAccumulationTimes, - types.DefaultDeposits, - types.DefaultBorrows, - types.DefaultTotalSupplied, - types.DefaultTotalBorrowed, - types.DefaultTotalReserves, - ) - - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "usdx:usd", BaseAsset: "usdx", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "usdx:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - - // Initialize test application - tApp.InitializeFromGenesisStates( - authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}, - ) - - keeper := tApp.GetHardKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - - var err error - - // Run BeginBlocker once to transition MoneyMarkets - hard.BeginBlocker(suite.ctx, suite.keeper) - - // Setup borrower with some collateral to borrow against, and some reserve in the protocol. - depositCoins := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF)), - sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF)), - ) - err = suite.keeper.Deposit(suite.ctx, borrower, depositCoins) - suite.Require().NoError(err) - - initialBorrowCoins := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(70*KAVA_CF))) - err = suite.keeper.Borrow(suite.ctx, borrower, initialBorrowCoins) - suite.Require().NoError(err) - - runAtTime := suite.ctx.BlockTime().Add(blockDuration) - suite.ctx = suite.ctx.WithBlockTime(runAtTime) - hard.BeginBlocker(suite.ctx, suite.keeper) - - repayCoins := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))) // repay everything including accumulated interest - err = suite.keeper.Repay(suite.ctx, borrower, borrower, repayCoins) - suite.Require().NoError(err) - - // Get the total borrowable amount from the protocol, taking into account the reserves. - modAccBalance := suite.getAccountCoins(suite.getModuleAccountAtCtx(types.ModuleAccountName, suite.ctx)) - reserves, found := suite.keeper.GetTotalReserves(suite.ctx) - suite.Require().True(found) - availableToBorrow := modAccBalance.Sub(reserves...) - - // Test borrowing one over the available amount (try to borrow from the reserves) - err = suite.keeper.Borrow( - suite.ctx, - borrower, - sdk.NewCoins(sdk.NewCoin("ukava", availableToBorrow.AmountOf("ukava").Add(sdk.OneInt()))), - ) - suite.Require().Error(err) - - // Test borrowing exactly the limit - err = suite.keeper.Borrow( - suite.ctx, - borrower, - sdk.NewCoins(sdk.NewCoin("ukava", availableToBorrow.AmountOf("ukava"))), - ) - suite.Require().NoError(err) -} diff --git a/x/hard/keeper/deposit.go b/x/hard/keeper/deposit.go deleted file mode 100644 index 813ed7af..00000000 --- a/x/hard/keeper/deposit.go +++ /dev/null @@ -1,203 +0,0 @@ -package keeper - -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" - - "github.com/0glabs/0g-chain/x/hard/types" -) - -// Deposit deposit -func (k Keeper) Deposit(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error { - // Set any new denoms' global supply index to 1.0 - for _, coin := range coins { - _, foundInterestFactor := k.GetSupplyInterestFactor(ctx, coin.Denom) - if !foundInterestFactor { - _, foundMm := k.GetMoneyMarket(ctx, coin.Denom) - if foundMm { - k.SetSupplyInterestFactor(ctx, coin.Denom, sdk.OneDec()) - } - } - } - - // Call incentive hook - existingDeposit, hasExistingDeposit := k.GetDeposit(ctx, depositor) - if hasExistingDeposit { - k.BeforeDepositModified(ctx, existingDeposit) - } - - // Sync any outstanding interest - k.SyncSupplyInterest(ctx, depositor) - - err := k.ValidateDeposit(ctx, coins) - if err != nil { - return err - } - - err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, depositor, types.ModuleAccountName, coins) - if err != nil { - if errors.Is(err, sdkerrors.ErrInsufficientFunds) { - acc := k.accountKeeper.GetAccount(ctx, depositor) - accCoins := k.bankKeeper.SpendableCoins(ctx, acc.GetAddress()) - for _, coin := range coins { - _, isNegative := accCoins.SafeSub(coin) - if isNegative { - return errorsmod.Wrapf(types.ErrBorrowExceedsAvailableBalance, - "insufficient funds: the requested deposit amount of %s exceeds the total available account funds of %s%s", - coin, accCoins.AmountOf(coin.Denom), coin.Denom, - ) - } - } - } - } - if err != nil { - return err - } - - interestFactors := types.SupplyInterestFactors{} - currDeposit, foundDeposit := k.GetDeposit(ctx, depositor) - if foundDeposit { - interestFactors = currDeposit.Index - } - for _, coin := range coins { - interestFactorValue, foundValue := k.GetSupplyInterestFactor(ctx, coin.Denom) - if foundValue { - interestFactors = interestFactors.SetInterestFactor(coin.Denom, interestFactorValue) - } - } - - // Calculate new deposit amount - var amount sdk.Coins - if foundDeposit { - amount = currDeposit.Amount.Add(coins...) - } else { - amount = coins - } - // Update the depositer's amount and supply interest factors in the store - deposit := types.NewDeposit(depositor, amount, interestFactors) - - if deposit.Amount.Empty() { - k.DeleteDeposit(ctx, deposit) - } else { - k.SetDeposit(ctx, deposit) - } - - k.IncrementSuppliedCoins(ctx, coins) - if !foundDeposit { // User's first deposit - k.AfterDepositCreated(ctx, deposit) - } else { - k.AfterDepositModified(ctx, deposit) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeHardDeposit, - sdk.NewAttribute(sdk.AttributeKeyAmount, coins.String()), - sdk.NewAttribute(types.AttributeKeyDepositor, deposit.Depositor.String()), - ), - ) - - return nil -} - -// ValidateDeposit validates a deposit -func (k Keeper) ValidateDeposit(ctx sdk.Context, coins sdk.Coins) error { - for _, depCoin := range coins { - _, foundMm := k.GetMoneyMarket(ctx, depCoin.Denom) - if !foundMm { - return errorsmod.Wrapf(types.ErrInvalidDepositDenom, "money market denom %s not found", depCoin.Denom) - } - } - - return nil -} - -// GetTotalDeposited returns the total amount deposited for the input deposit type and deposit denom -func (k Keeper) GetTotalDeposited(ctx sdk.Context, depositDenom string) (total sdkmath.Int) { - macc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) - return k.bankKeeper.GetBalance(ctx, macc.GetAddress(), depositDenom).Amount -} - -// IncrementSuppliedCoins increments the total amount of supplied coins by the newCoins parameter -func (k Keeper) IncrementSuppliedCoins(ctx sdk.Context, newCoins sdk.Coins) { - suppliedCoins, found := k.GetSuppliedCoins(ctx) - if !found { - if !newCoins.Empty() { - k.SetSuppliedCoins(ctx, newCoins) - } - } else { - k.SetSuppliedCoins(ctx, suppliedCoins.Add(newCoins...)) - } -} - -// DecrementSuppliedCoins decrements the total amount of supplied coins by the coins parameter -func (k Keeper) DecrementSuppliedCoins(ctx sdk.Context, coins sdk.Coins) error { - suppliedCoins, found := k.GetSuppliedCoins(ctx) - if !found { - return errorsmod.Wrapf(types.ErrSuppliedCoinsNotFound, "cannot withdraw if no coins are deposited") - } - - updatedSuppliedCoins, isNegative := suppliedCoins.SafeSub(coins...) - if isNegative { - coinsToSubtract := sdk.NewCoins() - for _, coin := range coins { - if suppliedCoins.AmountOf(coin.Denom).LT(coin.Amount) { - if suppliedCoins.AmountOf(coin.Denom).GT(sdk.ZeroInt()) { - coinsToSubtract = coinsToSubtract.Add(sdk.NewCoin(coin.Denom, suppliedCoins.AmountOf(coin.Denom))) - } - } else { - coinsToSubtract = coinsToSubtract.Add(coin) - } - } - updatedSuppliedCoins = suppliedCoins.Sub(coinsToSubtract...) - } - - k.SetSuppliedCoins(ctx, updatedSuppliedCoins) - return nil -} - -// GetSyncedDeposit returns a deposit object containing current balances and indexes -func (k Keeper) GetSyncedDeposit(ctx sdk.Context, depositor sdk.AccAddress) (types.Deposit, bool) { - deposit, found := k.GetDeposit(ctx, depositor) - if !found { - return types.Deposit{}, false - } - - return k.loadSyncedDeposit(ctx, deposit), true -} - -// loadSyncedDeposit calculates a user's synced deposit, but does not update state -func (k Keeper) loadSyncedDeposit(ctx sdk.Context, deposit types.Deposit) types.Deposit { - totalNewInterest := sdk.Coins{} - newSupplyIndexes := types.SupplyInterestFactors{} - for _, coin := range deposit.Amount { - interestFactorValue, foundInterestFactorValue := k.GetSupplyInterestFactor(ctx, coin.Denom) - if foundInterestFactorValue { - // Locate the interest factor by coin denom in the user's list of interest factors - foundAtIndex := -1 - for i := range deposit.Index { - if deposit.Index[i].Denom == coin.Denom { - foundAtIndex = i - break - } - } - - // Calculate interest that will be paid to user for this asset - if foundAtIndex != -1 { - storedAmount := sdk.NewDecFromInt(deposit.Amount.AmountOf(coin.Denom)) - userLastInterestFactor := deposit.Index[foundAtIndex].Value - coinInterest := (storedAmount.Quo(userLastInterestFactor).Mul(interestFactorValue)).Sub(storedAmount) - totalNewInterest = totalNewInterest.Add(sdk.NewCoin(coin.Denom, coinInterest.TruncateInt())) - } - } - - supplyIndex := types.NewSupplyInterestFactor(coin.Denom, interestFactorValue) - newSupplyIndexes = append(newSupplyIndexes, supplyIndex) - } - - return types.NewDeposit(deposit.Depositor, deposit.Amount.Add(totalNewInterest...), newSupplyIndexes) -} diff --git a/x/hard/keeper/deposit_test.go b/x/hard/keeper/deposit_test.go deleted file mode 100644 index c3b15c00..00000000 --- a/x/hard/keeper/deposit_test.go +++ /dev/null @@ -1,344 +0,0 @@ -package keeper_test - -import ( - "strings" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/hard" - "github.com/0glabs/0g-chain/x/hard/types" - pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" -) - -func (suite *KeeperTestSuite) TestDeposit() { - type args struct { - depositor sdk.AccAddress - amount sdk.Coins - numberDeposits int - expectedAccountBalance sdk.Coins - expectedModAccountBalance sdk.Coins - expectedDepositCoins sdk.Coins - } - type errArgs struct { - expectPass bool - contains string - } - type depositTest struct { - name string - args args - errArgs errArgs - } - testCases := []depositTest{ - { - "valid", - args{ - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - numberDeposits: 1, - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(900)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - expectedDepositCoins: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid multi deposit", - args{ - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - numberDeposits: 2, - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(800)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - expectedDepositCoins: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "invalid deposit denom", - args{ - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - amount: sdk.NewCoins(sdk.NewCoin("fake", sdkmath.NewInt(100))), - numberDeposits: 1, - expectedAccountBalance: sdk.Coins{}, - expectedModAccountBalance: sdk.Coins{}, - expectedDepositCoins: sdk.Coins{}, - }, - errArgs{ - expectPass: false, - contains: "invalid deposit denom", - }, - }, - { - "insufficient funds", - args{ - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10000))), - numberDeposits: 1, - expectedAccountBalance: sdk.Coins{}, - expectedModAccountBalance: sdk.Coins{}, - expectedDepositCoins: sdk.Coins{}, - }, - errArgs{ - expectPass: false, - contains: "insufficient funds: the requested deposit amount", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - // create new app with one funded account - - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{ - sdk.NewCoins( - sdk.NewCoin("bnb", sdkmath.NewInt(1000)), - sdk.NewCoin("btcb", sdkmath.NewInt(1000)), - ), - }, - []sdk.AccAddress{tc.args.depositor}, - ) - loanToValue, _ := sdk.NewDecFromStr("0.6") - hardGS := types.NewGenesisState(types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("usdx", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "usdx:usd", sdkmath.NewInt(1000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("ukava", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "kava:usd", sdkmath.NewInt(1000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("bnb", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "bnb:usd", sdkmath.NewInt(1000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("btcb", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "btcb:usd", sdkmath.NewInt(1000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - }, - sdk.NewDec(10), - ), types.DefaultAccumulationTimes, types.DefaultDeposits, types.DefaultBorrows, - types.DefaultTotalSupplied, types.DefaultTotalBorrowed, types.DefaultTotalReserves, - ) - - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "usdx:usd", BaseAsset: "usdx", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "btcb:usd", BaseAsset: "btcb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "usdx:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "btcb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("100.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("10.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}, - ) - keeper := tApp.GetHardKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - - // Run BeginBlocker once to transition MoneyMarkets - hard.BeginBlocker(suite.ctx, suite.keeper) - - // run the test - var err error - for i := 0; i < tc.args.numberDeposits; i++ { - err = suite.keeper.Deposit(suite.ctx, tc.args.depositor, tc.args.amount) - } - - // verify results - if tc.errArgs.expectPass { - suite.Require().NoError(err) - acc := suite.getAccount(tc.args.depositor) - suite.Require().Equal(tc.args.expectedAccountBalance, suite.getAccountCoins(acc)) - mAcc := suite.getModuleAccount(types.ModuleAccountName) - suite.Require().Equal(tc.args.expectedModAccountBalance, suite.getAccountCoins(mAcc)) - dep, f := suite.keeper.GetDeposit(suite.ctx, tc.args.depositor) - suite.Require().True(f) - suite.Require().Equal(tc.args.expectedDepositCoins, dep.Amount) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *KeeperTestSuite) TestDecrementSuppliedCoins() { - type args struct { - suppliedInitial sdk.Coins - decrementCoins sdk.Coins - expectedSuppliedFinal sdk.Coins - } - type errArgs struct { - expectPass bool - contains string - } - type decrementTest struct { - name string - args args - errArgs errArgs - } - testCases := []decrementTest{ - { - "valid", - args{ - suppliedInitial: cs(c("bnb", 10000000000000), c("busd", 3000000000000), c("xrpb", 2500000000000)), - decrementCoins: cs(c("bnb", 5000000000000)), - expectedSuppliedFinal: cs(c("bnb", 5000000000000), c("busd", 3000000000000), c("xrpb", 2500000000000)), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid-negative", - args{ - suppliedInitial: cs(c("bnb", 10000000000000), c("busd", 3000000000000), c("xrpb", 2500000000000)), - decrementCoins: cs(c("bnb", 10000000000001)), - expectedSuppliedFinal: cs(c("busd", 3000000000000), c("xrpb", 2500000000000)), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid-multiple negative", - args{ - suppliedInitial: cs(c("bnb", 10000000000000), c("busd", 3000000000000), c("xrpb", 2500000000000)), - decrementCoins: cs(c("bnb", 10000000000001), c("busd", 5000000000000)), - expectedSuppliedFinal: cs(c("xrpb", 2500000000000)), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid-absent coin denom", - args{ - suppliedInitial: cs(c("bnb", 10000000000000), c("xrpb", 2500000000000)), - decrementCoins: cs(c("busd", 5)), - expectedSuppliedFinal: cs(c("bnb", 10000000000000), c("xrpb", 2500000000000)), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - loanToValue, _ := sdk.NewDecFromStr("0.6") - depositor := sdk.AccAddress(crypto.AddressHash([]byte("test"))) - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{tc.args.suppliedInitial}, - []sdk.AccAddress{depositor}, - ) - hardGS := types.NewGenesisState(types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("bnb", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "bnb:usd", sdkmath.NewInt(100000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("busd", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "busd:usd", sdkmath.NewInt(100000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("xrpb", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "xrpb:usd", sdkmath.NewInt(100000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - }, - sdk.MustNewDecFromStr("10"), - ), types.DefaultAccumulationTimes, types.DefaultDeposits, types.DefaultBorrows, - types.DefaultTotalSupplied, types.DefaultTotalBorrowed, types.DefaultTotalReserves, - ) - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "xrpb:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "busd:usd", BaseAsset: "btcb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "busd:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "xrpb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("200.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}, - ) - keeper := tApp.GetHardKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - - // Run BeginBlocker once to transition MoneyMarkets - hard.BeginBlocker(suite.ctx, suite.keeper) - - err := suite.keeper.Deposit(suite.ctx, depositor, tc.args.suppliedInitial) - suite.Require().NoError(err) - err = suite.keeper.DecrementSuppliedCoins(ctx, tc.args.decrementCoins) - suite.Require().NoError(err) - totalSuppliedActual, found := suite.keeper.GetSuppliedCoins(suite.ctx) - suite.Require().True(found) - suite.Require().Equal(totalSuppliedActual, tc.args.expectedSuppliedFinal) - }) - } -} - -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } diff --git a/x/hard/keeper/grpc_query.go b/x/hard/keeper/grpc_query.go deleted file mode 100644 index dab17cc4..00000000 --- a/x/hard/keeper/grpc_query.go +++ /dev/null @@ -1,546 +0,0 @@ -package keeper - -import ( - "context" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/client" - 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" - "google.golang.org/grpc/status" - - "github.com/0glabs/0g-chain/x/hard/types" -) - -type queryServer struct { - keeper Keeper - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper -} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(keeper Keeper, ak types.AccountKeeper, bk types.BankKeeper) types.QueryServer { - return &queryServer{ - keeper: keeper, - accountKeeper: ak, - bankKeeper: bk, - } -} - -var _ types.QueryServer = queryServer{} - -func (s queryServer) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - // Get params - params := s.keeper.GetParams(sdkCtx) - - return &types.QueryParamsResponse{ - Params: params, - }, nil -} - -func (s queryServer) Accounts(ctx context.Context, req *types.QueryAccountsRequest) (*types.QueryAccountsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - macc := s.accountKeeper.GetModuleAccount(sdkCtx, types.ModuleAccountName) - - accounts := []authtypes.ModuleAccount{ - *macc.(*authtypes.ModuleAccount), - } - - return &types.QueryAccountsResponse{ - Accounts: accounts, - }, nil -} - -func (s queryServer) Deposits(ctx context.Context, req *types.QueryDepositsRequest) (*types.QueryDepositsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - hasDenom := len(req.Denom) > 0 - hasOwner := len(req.Owner) > 0 - - var owner sdk.AccAddress - var err error - if hasOwner { - owner, err = sdk.AccAddressFromBech32(req.Owner) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - } - - var deposits types.Deposits - switch { - case hasOwner && hasDenom: - deposit, found := s.keeper.GetSyncedDeposit(sdkCtx, owner) - if found { - for _, coin := range deposit.Amount { - if coin.Denom == req.Denom { - deposits = append(deposits, deposit) - } - } - } - case hasOwner: - deposit, found := s.keeper.GetSyncedDeposit(sdkCtx, owner) - if found { - deposits = append(deposits, deposit) - } - case hasDenom: - s.keeper.IterateDeposits(sdkCtx, func(deposit types.Deposit) (stop bool) { - if deposit.Amount.AmountOf(req.Denom).IsPositive() { - deposits = append(deposits, deposit) - } - return false - }) - default: - s.keeper.IterateDeposits(sdkCtx, func(deposit types.Deposit) (stop bool) { - deposits = append(deposits, deposit) - return false - }) - } - - // If owner param was specified then deposits array already contains the user's synced deposit - if hasOwner { - return &types.QueryDepositsResponse{ - Deposits: deposits.ToResponse(), - Pagination: nil, - }, nil - } - - // Otherwise we need to simulate syncing of each deposit - var syncedDeposits types.Deposits - for _, deposit := range deposits { - syncedDeposit, _ := s.keeper.GetSyncedDeposit(sdkCtx, deposit.Depositor) - syncedDeposits = append(syncedDeposits, syncedDeposit) - } - - // TODO: Use more optimal FilteredPaginate to directly iterate over the store - // and not fetch everything. This currently also ignores certain fields in - // the pagination request like Key, CountTotal, Reverse. - page, limit, err := query.ParsePagination(req.Pagination) - if err != nil { - return nil, err - } - - start, end := client.Paginate(len(syncedDeposits), page, limit, 100) - if start < 0 || end < 0 { - syncedDeposits = types.Deposits{} - } else { - syncedDeposits = syncedDeposits[start:end] - } - - return &types.QueryDepositsResponse{ - Deposits: syncedDeposits.ToResponse(), - Pagination: nil, - }, nil -} - -func (s queryServer) UnsyncedDeposits(ctx context.Context, req *types.QueryUnsyncedDepositsRequest) (*types.QueryUnsyncedDepositsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - hasDenom := len(req.Denom) > 0 - hasOwner := len(req.Owner) > 0 - - var owner sdk.AccAddress - var err error - if hasOwner { - owner, err = sdk.AccAddressFromBech32(req.Owner) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - } - - var deposits types.Deposits - switch { - case hasOwner && hasDenom: - deposit, found := s.keeper.GetDeposit(sdkCtx, owner) - if found { - for _, coin := range deposit.Amount { - if coin.Denom == req.Denom { - deposits = append(deposits, deposit) - } - } - } - case hasOwner: - deposit, found := s.keeper.GetDeposit(sdkCtx, owner) - if found { - deposits = append(deposits, deposit) - } - case hasDenom: - s.keeper.IterateDeposits(sdkCtx, func(deposit types.Deposit) (stop bool) { - if deposit.Amount.AmountOf(req.Denom).IsPositive() { - deposits = append(deposits, deposit) - } - return false - }) - default: - s.keeper.IterateDeposits(sdkCtx, func(deposit types.Deposit) (stop bool) { - deposits = append(deposits, deposit) - return false - }) - } - - page, limit, err := query.ParsePagination(req.Pagination) - if err != nil { - return nil, err - } - - start, end := client.Paginate(len(deposits), page, limit, 100) - if start < 0 || end < 0 { - deposits = types.Deposits{} - } else { - deposits = deposits[start:end] - } - - return &types.QueryUnsyncedDepositsResponse{ - Deposits: deposits.ToResponse(), - Pagination: nil, - }, nil -} - -func (s queryServer) Borrows(ctx context.Context, req *types.QueryBorrowsRequest) (*types.QueryBorrowsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - hasDenom := len(req.Denom) > 0 - hasOwner := len(req.Owner) > 0 - - var owner sdk.AccAddress - var err error - if hasOwner { - owner, err = sdk.AccAddressFromBech32(req.Owner) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - } - - var borrows types.Borrows - switch { - case hasOwner && hasDenom: - borrow, found := s.keeper.GetSyncedBorrow(sdkCtx, owner) - if found { - for _, coin := range borrow.Amount { - if coin.Denom == req.Denom { - borrows = append(borrows, borrow) - } - } - } - case hasOwner: - borrow, found := s.keeper.GetSyncedBorrow(sdkCtx, owner) - if found { - borrows = append(borrows, borrow) - } - case hasDenom: - s.keeper.IterateBorrows(sdkCtx, func(borrow types.Borrow) (stop bool) { - if borrow.Amount.AmountOf(req.Denom).IsPositive() { - borrows = append(borrows, borrow) - } - return false - }) - default: - s.keeper.IterateBorrows(sdkCtx, func(borrow types.Borrow) (stop bool) { - borrows = append(borrows, borrow) - return false - }) - } - - // If owner param was specified then borrows array already contains the user's synced borrow - if hasOwner { - return &types.QueryBorrowsResponse{ - Borrows: borrows.ToResponse(), - Pagination: nil, - }, nil - } - - // Otherwise we need to simulate syncing of each borrow - var syncedBorrows types.Borrows - for _, borrow := range borrows { - syncedBorrow, _ := s.keeper.GetSyncedBorrow(sdkCtx, borrow.Borrower) - syncedBorrows = append(syncedBorrows, syncedBorrow) - } - - page, limit, err := query.ParsePagination(req.Pagination) - if err != nil { - return nil, err - } - - start, end := client.Paginate(len(syncedBorrows), page, limit, 100) - if start < 0 || end < 0 { - syncedBorrows = types.Borrows{} - } else { - syncedBorrows = syncedBorrows[start:end] - } - - return &types.QueryBorrowsResponse{ - Borrows: syncedBorrows.ToResponse(), - }, nil -} - -func (s queryServer) UnsyncedBorrows(ctx context.Context, req *types.QueryUnsyncedBorrowsRequest) (*types.QueryUnsyncedBorrowsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - hasDenom := len(req.Denom) > 0 - hasOwner := len(req.Owner) > 0 - - var owner sdk.AccAddress - var err error - if hasOwner { - owner, err = sdk.AccAddressFromBech32(req.Owner) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - } - - var borrows types.Borrows - switch { - case hasOwner && hasDenom: - borrow, found := s.keeper.GetBorrow(sdkCtx, owner) - if found { - for _, coin := range borrow.Amount { - if coin.Denom == req.Denom { - borrows = append(borrows, borrow) - } - } - } - case hasOwner: - borrow, found := s.keeper.GetBorrow(sdkCtx, owner) - if found { - borrows = append(borrows, borrow) - } - case hasDenom: - s.keeper.IterateBorrows(sdkCtx, func(borrow types.Borrow) (stop bool) { - if borrow.Amount.AmountOf(req.Denom).IsPositive() { - borrows = append(borrows, borrow) - } - return false - }) - default: - s.keeper.IterateBorrows(sdkCtx, func(borrow types.Borrow) (stop bool) { - borrows = append(borrows, borrow) - return false - }) - } - - page, limit, err := query.ParsePagination(req.Pagination) - if err != nil { - return nil, err - } - - start, end := client.Paginate(len(borrows), page, limit, 100) - if start < 0 || end < 0 { - borrows = types.Borrows{} - } else { - borrows = borrows[start:end] - } - - return &types.QueryUnsyncedBorrowsResponse{ - Borrows: borrows.ToResponse(), - Pagination: nil, - }, nil -} - -func (s queryServer) TotalBorrowed(ctx context.Context, req *types.QueryTotalBorrowedRequest) (*types.QueryTotalBorrowedResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - borrowedCoins, found := s.keeper.GetBorrowedCoins(sdkCtx) - if !found { - // Use empty coins instead of returning an error - borrowedCoins = sdk.NewCoins() - } - - // If user specified a denom only return coins of that denom type - if len(req.Denom) > 0 { - borrowedCoins = sdk.NewCoins(sdk.NewCoin(req.Denom, borrowedCoins.AmountOf(req.Denom))) - } - - return &types.QueryTotalBorrowedResponse{ - BorrowedCoins: borrowedCoins, - }, nil -} - -func (s queryServer) TotalDeposited(ctx context.Context, req *types.QueryTotalDepositedRequest) (*types.QueryTotalDepositedResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - suppliedCoins, found := s.keeper.GetSuppliedCoins(sdkCtx) - if !found { - // Use empty coins instead of returning an error - suppliedCoins = sdk.NewCoins() - } - - // If user specified a denom only return coins of that denom type - if len(req.Denom) > 0 { - suppliedCoins = sdk.NewCoins(sdk.NewCoin(req.Denom, suppliedCoins.AmountOf(req.Denom))) - } - - return &types.QueryTotalDepositedResponse{ - SuppliedCoins: suppliedCoins, - }, nil -} - -func (s queryServer) InterestRate(ctx context.Context, req *types.QueryInterestRateRequest) (*types.QueryInterestRateResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - var moneyMarketInterestRates types.MoneyMarketInterestRates - var moneyMarkets types.MoneyMarkets - if len(req.Denom) > 0 { - moneyMarket, found := s.keeper.GetMoneyMarket(sdkCtx, req.Denom) - if !found { - return nil, types.ErrMoneyMarketNotFound - } - moneyMarkets = append(moneyMarkets, moneyMarket) - } else { - moneyMarkets = s.keeper.GetAllMoneyMarkets(sdkCtx) - } - - // Calculate the borrow and supply APY interest rates for each money market - for _, moneyMarket := range moneyMarkets { - denom := moneyMarket.Denom - macc := s.accountKeeper.GetModuleAccount(sdkCtx, types.ModuleName) - cash := s.bankKeeper.GetBalance(sdkCtx, macc.GetAddress(), denom).Amount - - borrowed := sdk.NewCoin(denom, sdk.ZeroInt()) - borrowedCoins, foundBorrowedCoins := s.keeper.GetBorrowedCoins(sdkCtx) - if foundBorrowedCoins { - borrowed = sdk.NewCoin(denom, borrowedCoins.AmountOf(denom)) - } - - reserves, foundReserves := s.keeper.GetTotalReserves(sdkCtx) - if !foundReserves { - reserves = sdk.NewCoins() - } - - // CalculateBorrowRate calculates the current interest rate based on utilization (the fraction of supply that has ien borrowed) - borrowAPY, err := CalculateBorrowRate(moneyMarket.InterestRateModel, sdk.NewDecFromInt(cash), sdk.NewDecFromInt(borrowed.Amount), sdk.NewDecFromInt(reserves.AmountOf(denom))) - if err != nil { - return nil, err - } - - utilRatio := CalculateUtilizationRatio(sdk.NewDecFromInt(cash), sdk.NewDecFromInt(borrowed.Amount), sdk.NewDecFromInt(reserves.AmountOf(denom))) - fullSupplyAPY := borrowAPY.Mul(utilRatio) - realSupplyAPY := fullSupplyAPY.Mul(sdk.OneDec().Sub(moneyMarket.ReserveFactor)) - - moneyMarketInterestRate := types.MoneyMarketInterestRate{ - Denom: denom, - SupplyInterestRate: realSupplyAPY.String(), - BorrowInterestRate: borrowAPY.String(), - } - - moneyMarketInterestRates = append(moneyMarketInterestRates, moneyMarketInterestRate) - } - - return &types.QueryInterestRateResponse{ - InterestRates: moneyMarketInterestRates, - }, nil -} - -func (s queryServer) Reserves(ctx context.Context, req *types.QueryReservesRequest) (*types.QueryReservesResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - reserveCoins, found := s.keeper.GetTotalReserves(sdkCtx) - if !found { - reserveCoins = sdk.Coins{} - } - - // If user specified a denom only return coins of that denom type - if len(req.Denom) > 0 { - reserveCoins = sdk.NewCoins(sdk.NewCoin(req.Denom, reserveCoins.AmountOf(req.Denom))) - } - - return &types.QueryReservesResponse{ - Amount: reserveCoins, - }, nil -} - -func (s queryServer) InterestFactors(ctx context.Context, req *types.QueryInterestFactorsRequest) (*types.QueryInterestFactorsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - var interestFactors types.InterestFactors - if len(req.Denom) > 0 { - // Fetch supply/borrow interest factors for a single denom - interestFactor := types.InterestFactor{} - interestFactor.Denom = req.Denom - supplyInterestFactor, found := s.keeper.GetSupplyInterestFactor(sdkCtx, req.Denom) - if found { - interestFactor.SupplyInterestFactor = supplyInterestFactor.String() - } - borrowInterestFactor, found := s.keeper.GetBorrowInterestFactor(sdkCtx, req.Denom) - if found { - interestFactor.BorrowInterestFactor = borrowInterestFactor.String() - } - interestFactors = append(interestFactors, interestFactor) - } else { - interestFactorMap := make(map[string]types.InterestFactor) - // Populate mapping with supply interest factors - s.keeper.IterateSupplyInterestFactors(sdkCtx, func(denom string, factor sdk.Dec) (stop bool) { - interestFactor := types.InterestFactor{Denom: denom, SupplyInterestFactor: factor.String()} - interestFactorMap[denom] = interestFactor - return false - }) - // Populate mapping with borrow interest factors - s.keeper.IterateBorrowInterestFactors(sdkCtx, func(denom string, factor sdk.Dec) (stop bool) { - interestFactor, ok := interestFactorMap[denom] - if !ok { - newInterestFactor := types.InterestFactor{Denom: denom, BorrowInterestFactor: factor.String()} - interestFactorMap[denom] = newInterestFactor - } else { - interestFactor.BorrowInterestFactor = factor.String() - interestFactorMap[denom] = interestFactor - } - return false - }) - // Translate mapping to slice - for _, val := range interestFactorMap { - interestFactors = append(interestFactors, val) - } - } - - return &types.QueryInterestFactorsResponse{ - InterestFactors: interestFactors, - }, nil -} diff --git a/x/hard/keeper/grpc_query_test.go b/x/hard/keeper/grpc_query_test.go deleted file mode 100644 index aed93627..00000000 --- a/x/hard/keeper/grpc_query_test.go +++ /dev/null @@ -1,530 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/hard/keeper" - "github.com/0glabs/0g-chain/x/hard/types" - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" -) - -type grpcQueryTestSuite struct { - suite.Suite - - tApp app.TestApp - ctx sdk.Context - keeper keeper.Keeper - queryServer types.QueryServer - addrs []sdk.AccAddress -} - -func (suite *grpcQueryTestSuite) SetupTest() { - suite.tApp = app.NewTestApp() - _, addrs := app.GeneratePrivKeyAddressPairs(2) - - suite.addrs = addrs - - suite.ctx = suite.tApp.NewContext(true, tmprototypes.Header{}). - WithBlockTime(time.Now().UTC()) - suite.keeper = suite.tApp.GetHardKeeper() - suite.queryServer = keeper.NewQueryServerImpl(suite.keeper, suite.tApp.GetAccountKeeper(), suite.tApp.GetBankKeeper()) - - err := suite.tApp.FundModuleAccount( - suite.ctx, - types.ModuleAccountName, - cs( - c("usdx", 10000000000), - c("busd", 10000000000), - ), - ) - suite.Require().NoError(err) - - suite.tApp.InitializeFromGenesisStates( - NewPricefeedGenStateMulti(suite.tApp.AppCodec()), - NewHARDGenState(suite.tApp.AppCodec()), - app.NewFundedGenStateWithSameCoins( - suite.tApp.AppCodec(), - cs( - c("bnb", 10000000000), - c("busd", 20000000000), - ), - addrs, - ), - ) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryParams() { - res, err := suite.queryServer.Params(sdk.WrapSDKContext(suite.ctx), &types.QueryParamsRequest{}) - suite.Require().NoError(err) - - var expected types.GenesisState - defaultHARDState := NewHARDGenState(suite.tApp.AppCodec()) - suite.tApp.AppCodec().MustUnmarshalJSON(defaultHARDState[types.ModuleName], &expected) - - suite.Equal(expected.Params, res.Params, "params should equal test genesis state") -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryAccounts() { - res, err := suite.queryServer.Accounts(sdk.WrapSDKContext(suite.ctx), &types.QueryAccountsRequest{}) - suite.Require().NoError(err) - - ak := suite.tApp.GetAccountKeeper() - acc := ak.GetModuleAccount(suite.ctx, types.ModuleName) - - suite.Len(res.Accounts, 1) - suite.Equal(acc, &res.Accounts[0], "accounts should include module account") -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryDeposits_EmptyResponse() { - res, err := suite.queryServer.Deposits(sdk.WrapSDKContext(suite.ctx), &types.QueryDepositsRequest{}) - suite.Require().NoError(err) - suite.Require().Empty(res) -} - -func (suite *grpcQueryTestSuite) addDeposits() { - deposits := []struct { - Address sdk.AccAddress - Coins sdk.Coins - }{ - { - suite.addrs[0], - cs(c("bnb", 100000000)), - }, - { - suite.addrs[1], - cs(c("bnb", 20000000)), - }, - { - suite.addrs[0], - cs(c("busd", 20000000)), - }, - { - suite.addrs[0], - cs(c("busd", 8000000)), - }, - } - - for _, dep := range deposits { - suite.NotPanics(func() { - err := suite.keeper.Deposit(suite.ctx, dep.Address, dep.Coins) - suite.Require().NoError(err) - }) - } -} - -func (suite *grpcQueryTestSuite) addBorrows() { - borrows := []struct { - Address sdk.AccAddress - Coins sdk.Coins - }{ - { - suite.addrs[0], - cs(c("usdx", 10000000)), - }, - { - suite.addrs[1], - cs(c("usdx", 20000000)), - }, - { - suite.addrs[0], - cs(c("usdx", 40000000)), - }, - { - suite.addrs[0], - cs(c("busd", 80000000)), - }, - } - - for _, dep := range borrows { - suite.NotPanics(func() { - err := suite.keeper.Borrow(suite.ctx, dep.Address, dep.Coins) - suite.Require().NoErrorf(err, "borrow %s should not error", dep.Coins) - }) - } -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryDeposits() { - suite.addDeposits() - - tests := []struct { - giveName string - giveRequest *types.QueryDepositsRequest - wantDepositCounts int - shouldError bool - errorSubstr string - }{ - { - "empty query", - &types.QueryDepositsRequest{}, - 2, - false, - "", - }, - { - "owner", - &types.QueryDepositsRequest{ - Owner: suite.addrs[0].String(), - }, - // Excludes the second address - 1, - false, - "", - }, - { - "invalid owner", - &types.QueryDepositsRequest{ - Owner: "invalid address", - }, - // No deposits - 0, - true, - "decoding bech32 failed", - }, - { - "owner and denom", - &types.QueryDepositsRequest{ - Owner: suite.addrs[0].String(), - Denom: "bnb", - }, - // Only the first one - 1, - false, - "", - }, - { - "owner and invalid denom empty response", - &types.QueryDepositsRequest{ - Owner: suite.addrs[0].String(), - Denom: "invalid denom", - }, - 0, - false, - "", - }, - { - "denom", - &types.QueryDepositsRequest{ - Denom: "bnb", - }, - 2, - false, - "", - }, - } - - for _, tt := range tests { - suite.Run(tt.giveName, func() { - res, err := suite.queryServer.Deposits(sdk.WrapSDKContext(suite.ctx), tt.giveRequest) - - if tt.shouldError { - suite.Error(err) - suite.Contains(err.Error(), tt.errorSubstr) - } else { - suite.NoError(err) - suite.Equal(tt.wantDepositCounts, len(res.Deposits)) - } - }) - - // Unsynced deposits should be the same - suite.Run(tt.giveName+"_unsynced", func() { - res, err := suite.queryServer.UnsyncedDeposits(sdk.WrapSDKContext(suite.ctx), &types.QueryUnsyncedDepositsRequest{ - Denom: tt.giveRequest.Denom, - Owner: tt.giveRequest.Owner, - Pagination: tt.giveRequest.Pagination, - }) - - if tt.shouldError { - suite.Error(err) - suite.Contains(err.Error(), tt.errorSubstr) - } else { - suite.NoError(err) - suite.Equal(tt.wantDepositCounts, len(res.Deposits)) - } - }) - } -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryBorrows() { - suite.addDeposits() - suite.addBorrows() - - tests := []struct { - giveName string - giveRequest *types.QueryBorrowsRequest - wantDepositCounts int - shouldError bool - errorSubstr string - }{ - { - "empty query", - &types.QueryBorrowsRequest{}, - 2, - false, - "", - }, - { - "owner", - &types.QueryBorrowsRequest{ - Owner: suite.addrs[0].String(), - }, - // Excludes the second address - 1, - false, - "", - }, - { - "invalid owner", - &types.QueryBorrowsRequest{ - Owner: "invalid address", - }, - // No deposits - 0, - true, - "decoding bech32 failed", - }, - { - "owner and denom", - &types.QueryBorrowsRequest{ - Owner: suite.addrs[0].String(), - Denom: "usdx", - }, - // Only the first one - 1, - false, - "", - }, - { - "owner and invalid denom empty response", - &types.QueryBorrowsRequest{ - Owner: suite.addrs[0].String(), - Denom: "invalid denom", - }, - 0, - false, - "", - }, - { - "denom", - &types.QueryBorrowsRequest{ - Denom: "usdx", - }, - 2, - false, - "", - }, - } - - for _, tt := range tests { - suite.Run(tt.giveName, func() { - res, err := suite.queryServer.Borrows(sdk.WrapSDKContext(suite.ctx), tt.giveRequest) - - if tt.shouldError { - suite.Error(err) - suite.Contains(err.Error(), tt.errorSubstr) - } else { - suite.NoError(err) - suite.Equal(tt.wantDepositCounts, len(res.Borrows)) - } - }) - - // Unsynced deposits should be the same - suite.Run(tt.giveName+"_unsynced", func() { - res, err := suite.queryServer.UnsyncedBorrows(sdk.WrapSDKContext(suite.ctx), &types.QueryUnsyncedBorrowsRequest{ - Denom: tt.giveRequest.Denom, - Owner: tt.giveRequest.Owner, - Pagination: tt.giveRequest.Pagination, - }) - - if tt.shouldError { - suite.Error(err) - suite.Contains(err.Error(), tt.errorSubstr) - } else { - suite.NoError(err) - suite.Equal(tt.wantDepositCounts, len(res.Borrows)) - } - }) - } -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalDeposited() { - suite.addDeposits() - - totalDeposited, err := suite.queryServer.TotalDeposited(sdk.WrapSDKContext(suite.ctx), &types.QueryTotalDepositedRequest{}) - suite.Require().NoError(err) - - suite.Equal(&types.QueryTotalDepositedResponse{ - SuppliedCoins: cs( - c("bnb", 100000000+20000000), - c("busd", 20000000+8000000), - ), - }, totalDeposited) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalDeposited_Empty() { - totalDeposited, err := suite.queryServer.TotalDeposited(sdk.WrapSDKContext(suite.ctx), &types.QueryTotalDepositedRequest{}) - suite.Require().NoError(err) - - suite.Equal(&types.QueryTotalDepositedResponse{ - SuppliedCoins: cs(), - }, totalDeposited) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalDeposited_Denom_Empty() { - totalDeposited, err := suite.queryServer.TotalDeposited(sdk.WrapSDKContext(suite.ctx), &types.QueryTotalDepositedRequest{ - Denom: "bnb", - }) - suite.Require().NoError(err) - - suite.Equal(&types.QueryTotalDepositedResponse{ - SuppliedCoins: cs(), - }, totalDeposited) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalDeposited_Denom() { - suite.addDeposits() - - totalDeposited, err := suite.queryServer.TotalDeposited(sdk.WrapSDKContext(suite.ctx), &types.QueryTotalDepositedRequest{ - Denom: "bnb", - }) - suite.Require().NoError(err) - - suite.Equal(&types.QueryTotalDepositedResponse{ - SuppliedCoins: cs( - c("bnb", 100000000+20000000), - ), - }, totalDeposited) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalBorrowed() { - suite.addDeposits() - suite.addBorrows() - - totalDeposited, err := suite.queryServer.TotalBorrowed(sdk.WrapSDKContext(suite.ctx), &types.QueryTotalBorrowedRequest{}) - suite.Require().NoError(err) - - suite.Equal(&types.QueryTotalBorrowedResponse{ - BorrowedCoins: cs( - c("usdx", 10000000+20000000+40000000), - c("busd", 80000000), - ), - }, totalDeposited) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalBorrowed_denom() { - suite.addDeposits() - suite.addBorrows() - - totalDeposited, err := suite.queryServer.TotalBorrowed(sdk.WrapSDKContext(suite.ctx), &types.QueryTotalBorrowedRequest{ - Denom: "usdx", - }) - suite.Require().NoError(err) - - suite.Equal(&types.QueryTotalBorrowedResponse{ - BorrowedCoins: cs( - c("usdx", 10000000+20000000+40000000), - ), - }, totalDeposited) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryInterestRate() { - tests := []struct { - giveName string - giveDenom string - wantInterestRates types.MoneyMarketInterestRates - shouldError bool - }{ - { - "no denom", - "", - types.MoneyMarketInterestRates{ - { - Denom: "usdx", - SupplyInterestRate: "0.000000000000000000", - BorrowInterestRate: "0.050000000000000000", - }, - { - Denom: "bnb", - SupplyInterestRate: "0.000000000000000000", - BorrowInterestRate: "0.000000000000000000", - }, - { - Denom: "busd", - SupplyInterestRate: "0.000000000000000000", - BorrowInterestRate: "0.000000000000000000", - }, - }, - false, - }, - { - "denom", - "usdx", - types.MoneyMarketInterestRates{ - { - Denom: "usdx", - SupplyInterestRate: "0.000000000000000000", - BorrowInterestRate: "0.050000000000000000", - }, - }, - false, - }, - { - "invalid denom", - "bun", - types.MoneyMarketInterestRates{}, - true, - }, - } - - for _, tt := range tests { - suite.Run(tt.giveName, func() { - res, err := suite.queryServer.InterestRate(sdk.WrapSDKContext(suite.ctx), &types.QueryInterestRateRequest{ - Denom: tt.giveDenom, - }) - - if tt.shouldError { - suite.Require().Error(err) - } else { - suite.Require().NoError(err) - - suite.ElementsMatch(tt.wantInterestRates, res.InterestRates) - } - }) - } -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryInterestFactors() { - res, err := suite.queryServer.InterestFactors(sdk.WrapSDKContext(suite.ctx), &types.QueryInterestFactorsRequest{ - Denom: "usdx", - }) - suite.Require().NoError(err) - - suite.Equal(&types.QueryInterestFactorsResponse{ - InterestFactors: types.InterestFactors{ - { - Denom: "usdx", - BorrowInterestFactor: "1.000000000000000000", - SupplyInterestFactor: "1.000000000000000000", - }, - }, - }, res) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryReserves() { - suite.addDeposits() - suite.addBorrows() - - res, err := suite.queryServer.Reserves(sdk.WrapSDKContext(suite.ctx), &types.QueryReservesRequest{}) - suite.Require().NoError(err) - - suite.Equal(&types.QueryReservesResponse{ - Amount: sdk.Coins{}, - }, res) -} - -func TestGrpcQueryTestSuite(t *testing.T) { - suite.Run(t, new(grpcQueryTestSuite)) -} diff --git a/x/hard/keeper/hooks.go b/x/hard/keeper/hooks.go deleted file mode 100644 index 19975667..00000000 --- a/x/hard/keeper/hooks.go +++ /dev/null @@ -1,52 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/hard/types" -) - -// Implements StakingHooks interface -var _ types.HARDHooks = Keeper{} - -// AfterDepositCreated - call hook if registered -func (k Keeper) AfterDepositCreated(ctx sdk.Context, deposit types.Deposit) { - if k.hooks != nil { - k.hooks.AfterDepositCreated(ctx, deposit) - } -} - -// BeforeDepositModified - call hook if registered -func (k Keeper) BeforeDepositModified(ctx sdk.Context, deposit types.Deposit) { - if k.hooks != nil { - k.hooks.BeforeDepositModified(ctx, deposit) - } -} - -// AfterDepositModified - call hook if registered -func (k Keeper) AfterDepositModified(ctx sdk.Context, deposit types.Deposit) { - if k.hooks != nil { - k.hooks.AfterDepositModified(ctx, deposit) - } -} - -// AfterBorrowCreated - call hook if registered -func (k Keeper) AfterBorrowCreated(ctx sdk.Context, borrow types.Borrow) { - if k.hooks != nil { - k.hooks.AfterBorrowCreated(ctx, borrow) - } -} - -// BeforeBorrowModified - call hook if registered -func (k Keeper) BeforeBorrowModified(ctx sdk.Context, borrow types.Borrow) { - if k.hooks != nil { - k.hooks.BeforeBorrowModified(ctx, borrow) - } -} - -// AfterBorrowModified - call hook if registered -func (k Keeper) AfterBorrowModified(ctx sdk.Context, borrow types.Borrow) { - if k.hooks != nil { - k.hooks.AfterBorrowModified(ctx, borrow) - } -} diff --git a/x/hard/keeper/integration_test.go b/x/hard/keeper/integration_test.go deleted file mode 100644 index 99b8d681..00000000 --- a/x/hard/keeper/integration_test.go +++ /dev/null @@ -1,125 +0,0 @@ -package keeper_test - -import ( - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/hard/types" - pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" -) - -func NewHARDGenState(cdc codec.JSONCodec) app.GenesisState { - hardGenesis := types.GenesisState{ - Params: types.NewParams( - types.MoneyMarkets{ - types.MoneyMarket{ - Denom: "usdx", - BorrowLimit: types.BorrowLimit{ - HasMaxLimit: true, - MaximumLimit: sdk.MustNewDecFromStr("100000000000"), - LoanToValue: sdk.MustNewDecFromStr("1"), - }, - SpotMarketID: "usdx:usd", - ConversionFactor: sdkmath.NewInt(USDX_CF), - InterestRateModel: types.InterestRateModel{ - BaseRateAPY: sdk.MustNewDecFromStr("0.05"), - BaseMultiplier: sdk.MustNewDecFromStr("2"), - Kink: sdk.MustNewDecFromStr("0.8"), - JumpMultiplier: sdk.MustNewDecFromStr("10"), - }, - ReserveFactor: sdk.MustNewDecFromStr("0.05"), - KeeperRewardPercentage: sdk.ZeroDec(), - }, - types.MoneyMarket{ - Denom: "bnb", - BorrowLimit: types.BorrowLimit{ - HasMaxLimit: true, - MaximumLimit: sdk.MustNewDecFromStr("3000000000000"), - LoanToValue: sdk.MustNewDecFromStr("0.5"), - }, - SpotMarketID: "bnb:usd", - ConversionFactor: sdkmath.NewInt(USDX_CF), - InterestRateModel: types.InterestRateModel{ - BaseRateAPY: sdk.MustNewDecFromStr("0"), - BaseMultiplier: sdk.MustNewDecFromStr("0.05"), - Kink: sdk.MustNewDecFromStr("0.8"), - JumpMultiplier: sdk.MustNewDecFromStr("5.0"), - }, - ReserveFactor: sdk.MustNewDecFromStr("0.025"), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.02"), - }, - types.MoneyMarket{ - Denom: "busd", - BorrowLimit: types.BorrowLimit{ - HasMaxLimit: true, - MaximumLimit: sdk.MustNewDecFromStr("1000000000000000"), - LoanToValue: sdk.MustNewDecFromStr("0.5"), - }, - SpotMarketID: "busd:usd", - ConversionFactor: sdkmath.NewInt(100000000), - InterestRateModel: types.InterestRateModel{ - BaseRateAPY: sdk.MustNewDecFromStr("0"), - BaseMultiplier: sdk.MustNewDecFromStr("0.5"), - Kink: sdk.MustNewDecFromStr("0.8"), - JumpMultiplier: sdk.MustNewDecFromStr("5"), - }, - ReserveFactor: sdk.MustNewDecFromStr("0.025"), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.02"), - }, - }, - sdk.MustNewDecFromStr("10"), - ), - PreviousAccumulationTimes: types.GenesisAccumulationTimes{ - types.NewGenesisAccumulationTime( - "usdx", - time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - sdk.OneDec(), - sdk.OneDec(), - ), - }, - Deposits: types.DefaultDeposits, - Borrows: types.DefaultBorrows, - TotalSupplied: sdk.NewCoins(), - TotalBorrowed: sdk.NewCoins(), - TotalReserves: sdk.NewCoins(), - } - return app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&hardGenesis)} -} - -func NewPricefeedGenStateMulti(cdc codec.JSONCodec) app.GenesisState { - pfGenesis := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "usdx:usd", BaseAsset: "usdx", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "xrp:usd", BaseAsset: "xrp", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "busd:usd", BaseAsset: "busd", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "usdx:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.OneDec(), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("618.13"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "busd:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.OneDec(), - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - return app.GenesisState{pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pfGenesis)} -} diff --git a/x/hard/keeper/interest.go b/x/hard/keeper/interest.go deleted file mode 100644 index e1b4dd71..00000000 --- a/x/hard/keeper/interest.go +++ /dev/null @@ -1,317 +0,0 @@ -package keeper - -import ( - "math" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/hard/types" -) - -var ( - scalingFactor = 1e18 - secondsPerYear = 31536000 -) - -// ApplyInterestRateUpdates translates the current interest rate models from the params to the store, -// with each money market accruing interest. -func (k Keeper) ApplyInterestRateUpdates(ctx sdk.Context) { - denomSet := map[string]bool{} - - params := k.GetParams(ctx) - for _, mm := range params.MoneyMarkets { - // Set any new money markets in the store - moneyMarket, found := k.GetMoneyMarket(ctx, mm.Denom) - if !found { - moneyMarket = mm - k.SetMoneyMarket(ctx, mm.Denom, moneyMarket) - } - - // Accrue interest according to the current money markets in the store - err := k.AccrueInterest(ctx, mm.Denom) - if err != nil { - panic(err) - } - - // Update the interest rate in the store if the params have changed - if !moneyMarket.Equal(mm) { - k.SetMoneyMarket(ctx, mm.Denom, mm) - } - denomSet[mm.Denom] = true - } - - // Edge case: money markets removed from params that still exist in the store - k.IterateMoneyMarkets(ctx, func(denom string, i types.MoneyMarket) bool { - if !denomSet[denom] { - // Accrue interest according to current store money market - err := k.AccrueInterest(ctx, denom) - if err != nil { - panic(err) - } - - // Delete the money market from the store - k.DeleteMoneyMarket(ctx, denom) - } - return false - }) -} - -// AccrueInterest applies accrued interest to total borrows and reserves by calculating -// interest from the last checkpoint time and writing the updated values to the store. -func (k Keeper) AccrueInterest(ctx sdk.Context, denom string) error { - previousAccrualTime, found := k.GetPreviousAccrualTime(ctx, denom) - if !found { - k.SetPreviousAccrualTime(ctx, denom, ctx.BlockTime()) - return nil - } - - timeElapsed := int64(math.RoundToEven( - ctx.BlockTime().Sub(previousAccrualTime).Seconds(), - )) - if timeElapsed == 0 { - return nil - } - - // Get current protocol state and hold in memory as 'prior' - macc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleName) - cashPrior := k.bankKeeper.GetBalance(ctx, macc.GetAddress(), denom).Amount - - borrowedPrior := sdk.NewCoin(denom, sdk.ZeroInt()) - borrowedCoinsPrior, foundBorrowedCoinsPrior := k.GetBorrowedCoins(ctx) - if foundBorrowedCoinsPrior { - borrowedPrior = sdk.NewCoin(denom, borrowedCoinsPrior.AmountOf(denom)) - } - if borrowedPrior.IsZero() { - k.SetPreviousAccrualTime(ctx, denom, ctx.BlockTime()) - return nil - } - - reservesPrior, foundReservesPrior := k.GetTotalReserves(ctx) - if !foundReservesPrior { - newReservesPrior := sdk.NewCoins() - k.SetTotalReserves(ctx, newReservesPrior) - reservesPrior = newReservesPrior - } - - borrowInterestFactorPrior, foundBorrowInterestFactorPrior := k.GetBorrowInterestFactor(ctx, denom) - if !foundBorrowInterestFactorPrior { - newBorrowInterestFactorPrior := sdk.MustNewDecFromStr("1.0") - k.SetBorrowInterestFactor(ctx, denom, newBorrowInterestFactorPrior) - borrowInterestFactorPrior = newBorrowInterestFactorPrior - } - - supplyInterestFactorPrior, foundSupplyInterestFactorPrior := k.GetSupplyInterestFactor(ctx, denom) - if !foundSupplyInterestFactorPrior { - newSupplyInterestFactorPrior := sdk.MustNewDecFromStr("1.0") - k.SetSupplyInterestFactor(ctx, denom, newSupplyInterestFactorPrior) - supplyInterestFactorPrior = newSupplyInterestFactorPrior - } - - // Fetch money market from the store - mm, found := k.GetMoneyMarket(ctx, denom) - if !found { - return errorsmod.Wrapf(types.ErrMoneyMarketNotFound, "%s", denom) - } - - // GetBorrowRate calculates the current interest rate based on utilization (the fraction of supply that has been borrowed) - borrowRateApy, err := CalculateBorrowRate(mm.InterestRateModel, sdk.NewDecFromInt(cashPrior), sdk.NewDecFromInt(borrowedPrior.Amount), sdk.NewDecFromInt(reservesPrior.AmountOf(denom))) - if err != nil { - return err - } - - // Convert from APY to SPY, expressed as (1 + borrow rate) - borrowRateSpy, err := APYToSPY(sdk.OneDec().Add(borrowRateApy)) - if err != nil { - return err - } - - // Calculate borrow interest factor and update - borrowInterestFactor := CalculateBorrowInterestFactor(borrowRateSpy, sdkmath.NewInt(timeElapsed)) - interestBorrowAccumulated := (borrowInterestFactor.Mul(sdk.NewDecFromInt(borrowedPrior.Amount)).TruncateInt()).Sub(borrowedPrior.Amount) - - if interestBorrowAccumulated.IsZero() && borrowRateApy.IsPositive() { - // don't accumulate if borrow interest is rounding to zero - return nil - } - - totalBorrowInterestAccumulated := sdk.NewCoins(sdk.NewCoin(denom, interestBorrowAccumulated)) - reservesNew := sdk.NewDecFromInt(interestBorrowAccumulated).Mul(mm.ReserveFactor).TruncateInt() - borrowInterestFactorNew := borrowInterestFactorPrior.Mul(borrowInterestFactor) - k.SetBorrowInterestFactor(ctx, denom, borrowInterestFactorNew) - - // Calculate supply interest factor and update - supplyInterestNew := interestBorrowAccumulated.Sub(reservesNew) - supplyInterestFactor := CalculateSupplyInterestFactor(sdk.NewDecFromInt(supplyInterestNew), sdk.NewDecFromInt(cashPrior), sdk.NewDecFromInt(borrowedPrior.Amount), sdk.NewDecFromInt(reservesPrior.AmountOf(denom))) - supplyInterestFactorNew := supplyInterestFactorPrior.Mul(supplyInterestFactor) - k.SetSupplyInterestFactor(ctx, denom, supplyInterestFactorNew) - - // Update accural keys in store - k.IncrementBorrowedCoins(ctx, totalBorrowInterestAccumulated) - k.IncrementSuppliedCoins(ctx, sdk.NewCoins(sdk.NewCoin(denom, supplyInterestNew))) - k.SetTotalReserves(ctx, reservesPrior.Add(sdk.NewCoin(denom, reservesNew))) - k.SetPreviousAccrualTime(ctx, denom, ctx.BlockTime()) - - return nil -} - -// CalculateBorrowRate calculates the borrow rate, which is the current APY expressed as a decimal -// based on the current utilization. -func CalculateBorrowRate(model types.InterestRateModel, cash, borrows, reserves sdk.Dec) (sdk.Dec, error) { - utilRatio := CalculateUtilizationRatio(cash, borrows, reserves) - - // Calculate normal borrow rate (under kink) - if utilRatio.LTE(model.Kink) { - return utilRatio.Mul(model.BaseMultiplier).Add(model.BaseRateAPY), nil - } - - // Calculate jump borrow rate (over kink) - normalRate := model.Kink.Mul(model.BaseMultiplier).Add(model.BaseRateAPY) - excessUtil := utilRatio.Sub(model.Kink) - return excessUtil.Mul(model.JumpMultiplier).Add(normalRate), nil -} - -// CalculateUtilizationRatio calculates an asset's current utilization rate -func CalculateUtilizationRatio(cash, borrows, reserves sdk.Dec) sdk.Dec { - // Utilization rate is 0 when there are no borrows - if borrows.Equal(sdk.ZeroDec()) { - return sdk.ZeroDec() - } - - totalSupply := cash.Add(borrows).Sub(reserves) - if totalSupply.IsNegative() { - return sdk.OneDec() - } - - return sdk.MinDec(sdk.OneDec(), borrows.Quo(totalSupply)) -} - -// CalculateBorrowInterestFactor 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 CalculateBorrowInterestFactor(perSecondInterestRate sdk.Dec, secondsElapsed sdkmath.Int) sdk.Dec { - scalingFactorUint := sdk.NewUint(uint64(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()) - // Convert seconds elapsed to uint (*not scaled*) - secondsElapsedUint := sdkmath.NewUintFromBigInt(secondsElapsed.BigInt()) - // Calculate the interest factor as a uint scaled by 1e18 - interestFactorMantissa := sdkmath.RelativePow(interestMantissa, secondsElapsedUint, scalingFactorUint) - - // Convert interest factor to an unscaled sdk.Dec - return sdk.NewDecFromBigInt(interestFactorMantissa.BigInt()).QuoInt(scalingFactorInt) -} - -// CalculateSupplyInterestFactor calculates the supply interest factor, which is the percentage of borrow interest -// that flows to each unit of supply, i.e. at 50% utilization and 0% reserve factor, a 5% borrow interest will -// correspond to a 2.5% supply interest. -func CalculateSupplyInterestFactor(newInterest, cash, borrows, reserves sdk.Dec) sdk.Dec { - totalSupply := cash.Add(borrows).Sub(reserves) - if totalSupply.IsZero() { - return sdk.OneDec() - } - return (newInterest.Quo(totalSupply)).Add(sdk.OneDec()) -} - -// SyncBorrowInterest updates the user's owed interest on newly borrowed coins to the latest global state -func (k Keeper) SyncBorrowInterest(ctx sdk.Context, addr sdk.AccAddress) { - totalNewInterest := sdk.Coins{} - - // Update user's borrow interest factor list for each asset in the 'coins' array. - // We use a list of BorrowInterestFactors here because Amino doesn't support marshaling maps. - borrow, found := k.GetBorrow(ctx, addr) - if !found { - return - } - for _, coin := range borrow.Amount { - // Locate the borrow interest factor item by coin denom in the user's list of borrow indexes - foundAtIndex := -1 - for i := range borrow.Index { - if borrow.Index[i].Denom == coin.Denom { - foundAtIndex = i - break - } - } - - interestFactorValue, _ := k.GetBorrowInterestFactor(ctx, coin.Denom) - if foundAtIndex == -1 { // First time user has borrowed this denom - borrow.Index = append(borrow.Index, types.NewBorrowInterestFactor(coin.Denom, interestFactorValue)) - } else { // User has an existing borrow index for this denom - // Calculate interest owed by user since asset's last borrow index update - storedAmount := sdk.NewDecFromInt(borrow.Amount.AmountOf(coin.Denom)) - userLastInterestFactor := borrow.Index[foundAtIndex].Value - interest := (storedAmount.Quo(userLastInterestFactor).Mul(interestFactorValue)).Sub(storedAmount) - totalNewInterest = totalNewInterest.Add(sdk.NewCoin(coin.Denom, interest.TruncateInt())) - // We're synced up, so update user's borrow index value to match the current global borrow index value - borrow.Index[foundAtIndex].Value = interestFactorValue - } - } - // Add all pending interest to user's borrow - borrow.Amount = borrow.Amount.Add(totalNewInterest...) - - // Update user's borrow in the store - k.SetBorrow(ctx, borrow) -} - -// SyncSupplyInterest updates the user's earned interest on supplied coins based on the latest global state -func (k Keeper) SyncSupplyInterest(ctx sdk.Context, addr sdk.AccAddress) { - totalNewInterest := sdk.Coins{} - - // Update user's supply index list for each asset in the 'coins' array. - // We use a list of SupplyInterestFactors here because Amino doesn't support marshaling maps. - deposit, found := k.GetDeposit(ctx, addr) - if !found { - return - } - - for _, coin := range deposit.Amount { - // Locate the deposit index item by coin denom in the user's list of deposit indexes - foundAtIndex := -1 - for i := range deposit.Index { - if deposit.Index[i].Denom == coin.Denom { - foundAtIndex = i - break - } - } - - interestFactorValue, _ := k.GetSupplyInterestFactor(ctx, coin.Denom) - if foundAtIndex == -1 { // First time user has supplied this denom - deposit.Index = append(deposit.Index, types.NewSupplyInterestFactor(coin.Denom, interestFactorValue)) - } else { // User has an existing supply index for this denom - // Calculate interest earned by user since asset's last deposit index update - storedAmount := sdk.NewDecFromInt(deposit.Amount.AmountOf(coin.Denom)) - userLastInterestFactor := deposit.Index[foundAtIndex].Value - interest := (storedAmount.Mul(interestFactorValue).Quo(userLastInterestFactor)).Sub(storedAmount) - if interest.TruncateInt().GT(sdk.ZeroInt()) { - totalNewInterest = totalNewInterest.Add(sdk.NewCoin(coin.Denom, interest.TruncateInt())) - } - // We're synced up, so update user's deposit index value to match the current global deposit index value - deposit.Index[foundAtIndex].Value = interestFactorValue - } - } - // Add all pending interest to user's deposit - deposit.Amount = deposit.Amount.Add(totalNewInterest...) - - // Update user's deposit in the store - k.SetDeposit(ctx, deposit) -} - -// APYToSPY converts the input annual interest rate. For example, 10% apy would be passed as 1.10. -// SPY = Per second compounded interest rate is how cosmos mathematically represents APY. -func APYToSPY(apy sdk.Dec) (sdk.Dec, error) { - // Note: any APY 179 or greater will cause an out-of-bounds error - root, err := apy.ApproxRoot(uint64(secondsPerYear)) - if err != nil { - return sdk.ZeroDec(), err - } - return root, nil -} - -// SPYToEstimatedAPY converts the internal per second compounded interest rate into an estimated annual -// interest rate. The returned value is an estimate and should not be used for financial calculations. -func SPYToEstimatedAPY(apy sdk.Dec) sdk.Dec { - return apy.Power(uint64(secondsPerYear)) -} diff --git a/x/hard/keeper/interest_test.go b/x/hard/keeper/interest_test.go deleted file mode 100644 index 5078cf6c..00000000 --- a/x/hard/keeper/interest_test.go +++ /dev/null @@ -1,1440 +0,0 @@ -package keeper_test - -import ( - "strconv" - "testing" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/hard" - "github.com/0glabs/0g-chain/x/hard/keeper" - "github.com/0glabs/0g-chain/x/hard/types" - pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" -) - -type InterestTestSuite struct { - suite.Suite -} - -func (suite *InterestTestSuite) TestCalculateUtilizationRatio() { - type args struct { - cash sdk.Dec - borrows sdk.Dec - reserves sdk.Dec - expectedValue sdk.Dec - } - - type test struct { - name string - args args - } - - testCases := []test{ - { - "normal", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("5000"), - reserves: sdk.MustNewDecFromStr("100"), - expectedValue: sdk.MustNewDecFromStr("0.847457627118644068"), - }, - }, - { - "high util ratio", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("250000"), - reserves: sdk.MustNewDecFromStr("100"), - expectedValue: sdk.MustNewDecFromStr("0.996412913511359107"), - }, - }, - { - "very high util ratio", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("250000000000"), - reserves: sdk.MustNewDecFromStr("100"), - expectedValue: sdk.MustNewDecFromStr("0.999999996400000013"), - }, - }, - { - "low util ratio", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("50"), - reserves: sdk.MustNewDecFromStr("100"), - expectedValue: sdk.MustNewDecFromStr("0.052631578947368421"), - }, - }, - { - "very low util ratio", - args{ - cash: sdk.MustNewDecFromStr("10000000"), - borrows: sdk.MustNewDecFromStr("50"), - reserves: sdk.MustNewDecFromStr("100"), - expectedValue: sdk.MustNewDecFromStr("0.000005000025000125"), - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - utilRatio := keeper.CalculateUtilizationRatio(tc.args.cash, tc.args.borrows, tc.args.reserves) - suite.Require().Equal(tc.args.expectedValue, utilRatio) - }) - } -} - -func (suite *InterestTestSuite) TestCalculateBorrowRate() { - type args struct { - cash sdk.Dec - borrows sdk.Dec - reserves sdk.Dec - model types.InterestRateModel - expectedValue sdk.Dec - } - - type test struct { - name string - args args - } - - // Normal model has: - // - BaseRateAPY: 0.0 - // - BaseMultiplier: 0.1 - // - Kink: 0.8 - // - JumpMultiplier: 0.5 - normalModel := types.NewInterestRateModel(sdk.MustNewDecFromStr("0"), sdk.MustNewDecFromStr("0.1"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("0.5")) - - testCases := []test{ - { - "normal no jump", - args{ - cash: sdk.MustNewDecFromStr("5000"), - borrows: sdk.MustNewDecFromStr("1000"), - reserves: sdk.MustNewDecFromStr("1000"), - model: normalModel, - expectedValue: sdk.MustNewDecFromStr("0.020000000000000000"), - }, - }, - { - "normal with jump", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("5000"), - reserves: sdk.MustNewDecFromStr("100"), - model: normalModel, - expectedValue: sdk.MustNewDecFromStr("0.103728813559322034"), - }, - }, - { - "high cash", - args{ - cash: sdk.MustNewDecFromStr("10000000"), - borrows: sdk.MustNewDecFromStr("5000"), - reserves: sdk.MustNewDecFromStr("100"), - model: normalModel, - expectedValue: sdk.MustNewDecFromStr("0.000049975511999120"), - }, - }, - { - "high borrows", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("5000000000000"), - reserves: sdk.MustNewDecFromStr("100"), - model: normalModel, - expectedValue: sdk.MustNewDecFromStr("0.179999999910000000"), - }, - }, - { - "high reserves", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("5000"), - reserves: sdk.MustNewDecFromStr("1000000000000"), - model: normalModel, - expectedValue: sdk.MustNewDecFromStr("0.180000000000000000"), - }, - }, - { - "random numbers", - args{ - cash: sdk.MustNewDecFromStr("125"), - borrows: sdk.MustNewDecFromStr("11"), - reserves: sdk.MustNewDecFromStr("82"), - model: normalModel, - expectedValue: sdk.MustNewDecFromStr("0.020370370370370370"), - }, - }, - { - "increased base multiplier", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("5000"), - reserves: sdk.MustNewDecFromStr("100"), - model: types.NewInterestRateModel(sdk.MustNewDecFromStr("0"), sdk.MustNewDecFromStr("0.5"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("1.0")), - expectedValue: sdk.MustNewDecFromStr("0.447457627118644068"), - }, - }, - { - "decreased kink", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("5000"), - reserves: sdk.MustNewDecFromStr("100"), - model: types.NewInterestRateModel(sdk.MustNewDecFromStr("0"), sdk.MustNewDecFromStr("0.5"), sdk.MustNewDecFromStr("0.1"), sdk.MustNewDecFromStr("1.0")), - expectedValue: sdk.MustNewDecFromStr("0.797457627118644068"), - }, - }, - { - "zero model returns zero", - args{ - cash: sdk.MustNewDecFromStr("1000"), - borrows: sdk.MustNewDecFromStr("5000"), - reserves: sdk.MustNewDecFromStr("100"), - model: types.NewInterestRateModel( - sdk.MustNewDecFromStr("0.0"), - sdk.MustNewDecFromStr("0.0"), - sdk.MustNewDecFromStr("0.8"), - sdk.MustNewDecFromStr("0.0"), - ), - expectedValue: sdk.MustNewDecFromStr("0.0"), - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - borrowRate, err := keeper.CalculateBorrowRate(tc.args.model, tc.args.cash, tc.args.borrows, tc.args.reserves) - suite.Require().NoError(err) - suite.Require().Equal(tc.args.expectedValue, borrowRate) - }) - } -} - -func (suite *InterestTestSuite) TestCalculateBorrowInterestFactor() { - type args struct { - perSecondInterestRate sdk.Dec - timeElapsed sdkmath.Int - expectedValue sdk.Dec - } - - type test struct { - name string - args args - } - - oneYearInSeconds := int64(31536000) - - testCases := []test{ - { - "1 year", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("1.191463614477847370"), - }, - }, - { - "10 year", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds * 10), - expectedValue: sdk.MustNewDecFromStr("5.765113233897391189"), - }, - }, - { - "1 month", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds / 12), - expectedValue: sdk.MustNewDecFromStr("1.014705619075717373"), - }, - }, - { - "1 day", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds / 365), - expectedValue: sdk.MustNewDecFromStr("1.000480067194057924"), - }, - }, - { - "1 year: low interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000000555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("1.017656545925063632"), - }, - }, - { - "1 year, lower interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000000055"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("1.001735985079841390"), - }, - }, - { - "1 year, lowest interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000000005"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("1.000157692432076670"), - }, - }, - { - "1 year: high interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000055555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("5.766022095987868825"), - }, - }, - { - "1 year: higher interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000000555555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("40628388.864535408465693310"), - }, - }, - { - "1 year: highest interest rate", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("1.000001555555"), - timeElapsed: sdkmath.NewInt(oneYearInSeconds), - expectedValue: sdk.MustNewDecFromStr("2017093013158200407564.613502861572552603"), - }, - }, - { - "largest per second interest rate with practical elapsed time", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("18.445"), // Begins to panic at ~18.45 (1845%/second interest rate) - timeElapsed: sdkmath.NewInt(30), // Assume a 30 second period, longer than any expected individual block - expectedValue: sdk.MustNewDecFromStr("94702138679846565921082258202543002089.215969366091911769"), - }, - }, - { - "supports calculated values greater than 1.84x10^19", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("18.5"), // Old uint64 conversion would panic at ~18.45 (1845%/second interest rate) - timeElapsed: sdkmath.NewInt(30), // Assume a 30 second period, longer than any expected individual block - expectedValue: sdk.MustNewDecFromStr("103550416986452240450480615551792302106.072205164469778538"), - }, - }, - { - "largest per second interest rate before sdk.Uint overflows 256 bytes", - args{ - perSecondInterestRate: sdk.MustNewDecFromStr("23.3"), // 23.4 overflows bit length 256 by 1 byte - timeElapsed: sdkmath.NewInt(30), // Assume a 30 second period, longer than any expected individual block - expectedValue: sdk.MustNewDecFromStr("104876366068119517411103023062013348034546.437155815200037999"), - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - interestFactor := keeper.CalculateBorrowInterestFactor(tc.args.perSecondInterestRate, tc.args.timeElapsed) - suite.Require().Equal(tc.args.expectedValue, interestFactor) - }) - } -} - -func (suite *InterestTestSuite) TestCalculateSupplyInterestFactor() { - type args struct { - newInterest sdk.Dec - cash sdk.Dec - borrows sdk.Dec - reserves sdk.Dec - reserveFactor sdk.Dec - expectedValue sdk.Dec - } - - type test struct { - name string - args args - } - - testCases := []test{ - { - "low new interest", - args{ - newInterest: sdk.MustNewDecFromStr("1"), - cash: sdk.MustNewDecFromStr("100.0"), - borrows: sdk.MustNewDecFromStr("1000.0"), - reserves: sdk.MustNewDecFromStr("10.0"), - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedValue: sdk.MustNewDecFromStr("1.000917431192660550"), - }, - }, - { - "medium new interest", - args{ - newInterest: sdk.MustNewDecFromStr("5"), - cash: sdk.MustNewDecFromStr("100.0"), - borrows: sdk.MustNewDecFromStr("1000.0"), - reserves: sdk.MustNewDecFromStr("10.0"), - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedValue: sdk.MustNewDecFromStr("1.004587155963302752"), - }, - }, - { - "high new interest", - args{ - newInterest: sdk.MustNewDecFromStr("10"), - cash: sdk.MustNewDecFromStr("100.0"), - borrows: sdk.MustNewDecFromStr("1000.0"), - reserves: sdk.MustNewDecFromStr("10.0"), - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedValue: sdk.MustNewDecFromStr("1.009174311926605505"), - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - interestFactor := keeper.CalculateSupplyInterestFactor(tc.args.newInterest, - tc.args.cash, tc.args.borrows, tc.args.reserves) - suite.Require().Equal(tc.args.expectedValue, interestFactor) - }) - } -} - -func (suite *InterestTestSuite) TestAPYToSPY() { - type args struct { - apy sdk.Dec - expectedValue sdk.Dec - } - - type test struct { - name string - args args - expectError bool - } - - testCases := []test{ - { - "lowest apy", - args{ - apy: sdk.MustNewDecFromStr("0.005"), - expectedValue: sdk.MustNewDecFromStr("0.999999831991472557"), - }, - false, - }, - { - "lower apy", - args{ - apy: sdk.MustNewDecFromStr("0.05"), - expectedValue: sdk.MustNewDecFromStr("0.999999905005957279"), - }, - false, - }, - { - "medium-low apy", - args{ - apy: sdk.MustNewDecFromStr("0.5"), - expectedValue: sdk.MustNewDecFromStr("0.999999978020447332"), - }, - false, - }, - { - "5% apy", - args{ - apy: sdk.MustNewDecFromStr("1.05"), - expectedValue: sdk.MustNewDecFromStr("1.000000001547125958"), - }, - false, - }, - { - "25% apy", - args{ - apy: sdk.MustNewDecFromStr("1.25"), - expectedValue: sdk.MustNewDecFromStr("1.000000007075835620"), - }, - false, - }, - { - "medium-high apy", - args{ - apy: sdk.MustNewDecFromStr("5"), - expectedValue: sdk.MustNewDecFromStr("1.000000051034942717"), - }, - false, - }, - { - "high apy", - args{ - apy: sdk.MustNewDecFromStr("50"), - expectedValue: sdk.MustNewDecFromStr("1.000000124049443433"), - }, - false, - }, - { - "highest apy", - args{ - apy: sdk.MustNewDecFromStr("177"), - expectedValue: sdk.MustNewDecFromStr("1.000000164134644767"), - }, - false, - }, - { - "out of bounds error after 178", - args{ - apy: sdk.MustNewDecFromStr("179"), - expectedValue: sdk.ZeroDec(), - }, - true, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - spy, err := keeper.APYToSPY(tc.args.apy) - if tc.expectError { - suite.Require().Error(err) - } else { - suite.Require().NoError(err) - suite.Require().Equal(tc.args.expectedValue, spy) - } - }) - } -} - -func (suite *InterestTestSuite) TestSPYToEstimatedAPY() { - type args struct { - spy sdk.Dec - expectedAPY float64 - acceptableRange float64 - } - - type test struct { - name string - args args - } - - testCases := []test{ - { - "lowest apy", - args{ - spy: sdk.MustNewDecFromStr("0.999999831991472557"), - expectedAPY: 0.005, // Returned value: 0.004999999888241291 - acceptableRange: 0.00001, // +/- 1/10000th of a precent - }, - }, - { - "lower apy", - args{ - spy: sdk.MustNewDecFromStr("0.999999905005957279"), - expectedAPY: 0.05, // Returned value: 0.05000000074505806 - acceptableRange: 0.00001, // +/- 1/10000th of a precent - }, - }, - { - "medium-low apy", - args{ - spy: sdk.MustNewDecFromStr("0.999999978020447332"), - expectedAPY: 0.5, // Returned value: 0.5 - acceptableRange: 0.00001, // +/- 1/10000th of a precent - }, - }, - { - "medium-high apy", - args{ - spy: sdk.MustNewDecFromStr("1.000000051034942717"), - expectedAPY: 5, // Returned value: 5 - acceptableRange: 0.00001, // +/- 1/10000th of a precent - }, - }, - { - "high apy", - args{ - spy: sdk.MustNewDecFromStr("1.000000124049443433"), - expectedAPY: 50, // Returned value: 50 - acceptableRange: 0.00001, // +/- 1/10000th of a precent - }, - }, - { - "highest apy", - args{ - spy: sdk.MustNewDecFromStr("1.000000146028999310"), - expectedAPY: 100, // 100 - acceptableRange: 0.00001, // +/- 1/10000th of a precent - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - // From SPY calculate APY and parse result from sdk.Dec to float64 - calculatedAPY := keeper.SPYToEstimatedAPY(tc.args.spy) - calculatedAPYFloat, err := strconv.ParseFloat(calculatedAPY.String(), 32) - suite.Require().NoError(err) - - // Check that the calculated value is within an acceptable percentage range - suite.Require().InEpsilon(tc.args.expectedAPY, calculatedAPYFloat, tc.args.acceptableRange) - }) - } -} - -type ExpectedBorrowInterest struct { - elapsedTime int64 - shouldBorrow bool - borrowCoin sdk.Coin -} - -func (suite *KeeperTestSuite) TestBorrowInterest() { - type args struct { - user sdk.AccAddress - initialBorrowerCoins sdk.Coins - initialModuleCoins sdk.Coins - borrowCoinDenom string - borrowCoins sdk.Coins - interestRateModel types.InterestRateModel - reserveFactor sdk.Dec - expectedInterestSnaphots []ExpectedBorrowInterest - } - - type errArgs struct { - expectPass bool - contains string - } - - type interestTest struct { - name string - args args - errArgs errArgs - } - - normalModel := types.NewInterestRateModel(sdk.MustNewDecFromStr("0"), sdk.MustNewDecFromStr("0.1"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("0.5")) - - oneDayInSeconds := int64(86400) - oneWeekInSeconds := int64(604800) - oneMonthInSeconds := int64(2592000) - oneYearInSeconds := int64(31536000) - - testCases := []interestTest{ - { - "one day", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - borrowCoinDenom: "ukava", - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedBorrowInterest{ - { - elapsedTime: oneDayInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "one week", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - borrowCoinDenom: "ukava", - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedBorrowInterest{ - { - elapsedTime: oneWeekInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "one month", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - borrowCoinDenom: "ukava", - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedBorrowInterest{ - { - elapsedTime: oneMonthInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "one year", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - borrowCoinDenom: "ukava", - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedBorrowInterest{ - { - elapsedTime: oneYearInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "0 reserve factor", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - borrowCoinDenom: "ukava", - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0"), - expectedInterestSnaphots: []ExpectedBorrowInterest{ - { - elapsedTime: oneYearInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "borrow during snapshot", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - borrowCoinDenom: "ukava", - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedBorrowInterest{ - { - elapsedTime: oneYearInSeconds, - shouldBorrow: true, - borrowCoin: sdk.NewCoin("ukava", sdkmath.NewInt(1*KAVA_CF)), - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "multiple snapshots", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - borrowCoinDenom: "ukava", - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedBorrowInterest{ - { - elapsedTime: oneMonthInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - { - elapsedTime: oneMonthInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "varied snapshots", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - borrowCoinDenom: "ukava", - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedBorrowInterest{ - { - elapsedTime: oneDayInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - { - elapsedTime: oneWeekInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - { - elapsedTime: oneMonthInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - { - elapsedTime: oneYearInSeconds, - shouldBorrow: false, - borrowCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - // Auth module genesis state - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{tc.args.initialBorrowerCoins}, - []sdk.AccAddress{tc.args.user}, - ) - - // Hard module genesis state - hardGS := types.NewGenesisState(types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("ukava", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "kava:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - tc.args.interestRateModel, // Interest Rate Model - tc.args.reserveFactor, // Reserve Factor - sdk.ZeroDec()), // Keeper Reward Percentage - }, - sdk.NewDec(10), - ), types.DefaultAccumulationTimes, types.DefaultDeposits, types.DefaultBorrows, - types.DefaultTotalSupplied, types.DefaultTotalBorrowed, types.DefaultTotalReserves, - ) - - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - }, - } - - // Initialize test application - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}) - - // Mint coins to Hard module account - bankKeeper := tApp.GetBankKeeper() - err := bankKeeper.MintCoins(ctx, types.ModuleAccountName, tc.args.initialModuleCoins) - suite.Require().NoError(err) - - suite.app = tApp - suite.ctx = ctx - suite.keeper = tApp.GetHardKeeper() - - // Run begin blocker and store initial block time - hard.BeginBlocker(suite.ctx, suite.keeper) - - // Deposit 2x as many coins for each coin we intend to borrow - depositCoins := sdk.NewCoins() - for _, borrowCoin := range tc.args.borrowCoins { - depositCoins = depositCoins.Add(sdk.NewCoin(borrowCoin.Denom, borrowCoin.Amount.Mul(sdkmath.NewInt(2)))) - } - err = suite.keeper.Deposit(suite.ctx, tc.args.user, depositCoins) - suite.Require().NoError(err) - - // Borrow coins - err = suite.keeper.Borrow(suite.ctx, tc.args.user, tc.args.borrowCoins) - suite.Require().NoError(err) - - // Check that the initial module-level borrow balance is correct and store it - initialBorrowedCoins, _ := suite.keeper.GetBorrowedCoins(suite.ctx) - suite.Require().Equal(tc.args.borrowCoins, initialBorrowedCoins) - - // Check interest levels for each snapshot - prevCtx := suite.ctx - for _, snapshot := range tc.args.expectedInterestSnaphots { - // ---------------------------- Calculate expected interest ---------------------------- - // 1. Get cash, borrows, reserves, and borrow index - cashPrior := suite.getAccountCoins(suite.getModuleAccountAtCtx(types.ModuleName, prevCtx)).AmountOf(tc.args.borrowCoinDenom) - - borrowCoinsPrior, borrowCoinsPriorFound := suite.keeper.GetBorrowedCoins(prevCtx) - suite.Require().True(borrowCoinsPriorFound) - borrowCoinPriorAmount := borrowCoinsPrior.AmountOf(tc.args.borrowCoinDenom) - - reservesPrior, foundReservesPrior := suite.keeper.GetTotalReserves(prevCtx) - if !foundReservesPrior { - reservesPrior = sdk.NewCoins(sdk.NewCoin(tc.args.borrowCoinDenom, sdk.ZeroInt())) - } - - interestFactorPrior, foundInterestFactorPrior := suite.keeper.GetBorrowInterestFactor(prevCtx, tc.args.borrowCoinDenom) - suite.Require().True(foundInterestFactorPrior) - - // 2. Calculate expected interest owed - borrowRateApy, err := keeper.CalculateBorrowRate(tc.args.interestRateModel, sdk.NewDecFromInt(cashPrior), sdk.NewDecFromInt(borrowCoinPriorAmount), sdk.NewDecFromInt(reservesPrior.AmountOf(tc.args.borrowCoinDenom))) - suite.Require().NoError(err) - - // Convert from APY to SPY, expressed as (1 + borrow rate) - borrowRateSpy, err := keeper.APYToSPY(sdk.OneDec().Add(borrowRateApy)) - suite.Require().NoError(err) - - interestFactor := keeper.CalculateBorrowInterestFactor(borrowRateSpy, sdkmath.NewInt(snapshot.elapsedTime)) - expectedInterest := (interestFactor.Mul(sdk.NewDecFromInt(borrowCoinPriorAmount)).TruncateInt()).Sub(borrowCoinPriorAmount) - expectedReserves := reservesPrior.Add(sdk.NewCoin(tc.args.borrowCoinDenom, sdk.NewDecFromInt(expectedInterest).Mul(tc.args.reserveFactor).TruncateInt())) - expectedInterestFactor := interestFactorPrior.Mul(interestFactor) - // ------------------------------------------------------------------------------------- - - // Set up snapshot chain context and run begin blocker - runAtTime := prevCtx.BlockTime().Add(time.Duration(int64(time.Second) * snapshot.elapsedTime)) - snapshotCtx := prevCtx.WithBlockTime(runAtTime) - hard.BeginBlocker(snapshotCtx, suite.keeper) - - // Check that the total amount of borrowed coins has increased by expected interest amount - expectedBorrowedCoins := borrowCoinsPrior.AmountOf(tc.args.borrowCoinDenom).Add(expectedInterest) - currBorrowedCoins, _ := suite.keeper.GetBorrowedCoins(snapshotCtx) - suite.Require().Equal(expectedBorrowedCoins, currBorrowedCoins.AmountOf(tc.args.borrowCoinDenom)) - - // Check that the total reserves have changed as expected - currTotalReserves, _ := suite.keeper.GetTotalReserves(snapshotCtx) - suite.Require().True(expectedReserves.IsEqual(currTotalReserves)) - - // Check that the borrow index has increased as expected - currIndexPrior, _ := suite.keeper.GetBorrowInterestFactor(snapshotCtx, tc.args.borrowCoinDenom) - suite.Require().Equal(expectedInterestFactor, currIndexPrior) - - // After borrowing again user's borrow balance should have any outstanding interest applied - if snapshot.shouldBorrow { - borrowCoinsBefore, _ := suite.keeper.GetBorrow(snapshotCtx, tc.args.user) - expectedInterestCoins := sdk.NewCoin(tc.args.borrowCoinDenom, expectedInterest) - expectedBorrowCoinsAfter := borrowCoinsBefore.Amount.Add(snapshot.borrowCoin).Add(expectedInterestCoins) - - err = suite.keeper.Borrow(snapshotCtx, tc.args.user, sdk.NewCoins(snapshot.borrowCoin)) - suite.Require().NoError(err) - - borrowCoinsAfter, _ := suite.keeper.GetBorrow(snapshotCtx, tc.args.user) - suite.Require().Equal(expectedBorrowCoinsAfter, borrowCoinsAfter.Amount) - } - // Update previous context to this snapshot's context, segmenting time periods between snapshots - prevCtx = snapshotCtx - } - }) - } -} - -type ExpectedSupplyInterest struct { - elapsedTime int64 - shouldSupply bool - supplyCoin sdk.Coin -} - -func (suite *KeeperTestSuite) TestSupplyInterest() { - type args struct { - user sdk.AccAddress - initialBorrowerCoins sdk.Coins - initialModuleCoins sdk.Coins - depositCoins sdk.Coins - coinDenoms []string - borrowCoins sdk.Coins - interestRateModel types.InterestRateModel - reserveFactor sdk.Dec - expectedInterestSnaphots []ExpectedSupplyInterest - } - - type errArgs struct { - expectPass bool - contains string - } - - type interestTest struct { - name string - args args - errArgs errArgs - } - - normalModel := types.NewInterestRateModel(sdk.MustNewDecFromStr("0"), sdk.MustNewDecFromStr("0.1"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("0.5")) - - oneDayInSeconds := int64(86400) - oneWeekInSeconds := int64(604800) - oneMonthInSeconds := int64(2592000) - oneYearInSeconds := int64(31536000) - - testCases := []interestTest{ - { - "one day", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - coinDenoms: []string{"ukava"}, - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedSupplyInterest{ - { - elapsedTime: oneDayInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "one week", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - coinDenoms: []string{"ukava"}, - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedSupplyInterest{ - { - elapsedTime: oneWeekInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "one month", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - coinDenoms: []string{"ukava"}, - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedSupplyInterest{ - { - elapsedTime: oneMonthInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "one year", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - coinDenoms: []string{"ukava"}, - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedSupplyInterest{ - { - elapsedTime: oneYearInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "supply/borrow multiple coins", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(100*BNB_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(100*BNB_CF))), - coinDenoms: []string{"ukava"}, - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(20*BNB_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedSupplyInterest{ - { - elapsedTime: oneMonthInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "supply during snapshot", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - coinDenoms: []string{"ukava"}, - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedSupplyInterest{ - { - elapsedTime: oneMonthInSeconds, - shouldSupply: true, - supplyCoin: sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF)), - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "multiple snapshots", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - coinDenoms: []string{"ukava"}, - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(80*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedSupplyInterest{ - { - elapsedTime: oneMonthInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - { - elapsedTime: oneMonthInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - { - elapsedTime: oneMonthInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "varied snapshots", - args{ - user: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - coinDenoms: []string{"ukava"}, - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - interestRateModel: normalModel, - reserveFactor: sdk.MustNewDecFromStr("0.05"), - expectedInterestSnaphots: []ExpectedSupplyInterest{ - { - elapsedTime: oneMonthInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - { - elapsedTime: oneDayInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - { - elapsedTime: oneYearInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - { - elapsedTime: oneWeekInSeconds, - shouldSupply: false, - supplyCoin: sdk.Coin{}, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - // Auth module genesis state - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{tc.args.initialBorrowerCoins}, - []sdk.AccAddress{tc.args.user}, - ) - - // Hard module genesis state - hardGS := types.NewGenesisState(types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("ukava", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "kava:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - tc.args.interestRateModel, // Interest Rate Model - tc.args.reserveFactor, // Reserve Factor - sdk.ZeroDec()), // Keeper Reward Percentage - types.NewMoneyMarket("bnb", - types.NewBorrowLimit(false, sdk.NewDec(100000000*BNB_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "bnb:usd", // Market ID - sdkmath.NewInt(BNB_CF), // Conversion Factor - tc.args.interestRateModel, // Interest Rate Model - tc.args.reserveFactor, // Reserve Factor - sdk.ZeroDec()), // Keeper Reward Percentage - }, - sdk.NewDec(10), - ), types.DefaultAccumulationTimes, types.DefaultDeposits, types.DefaultBorrows, - types.DefaultTotalSupplied, types.DefaultTotalBorrowed, types.DefaultTotalReserves, - ) - - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("20.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - }, - } - - // Initialize test application - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}) - - // Mint coins to Hard module account - bankKeeper := tApp.GetBankKeeper() - err := bankKeeper.MintCoins(ctx, types.ModuleAccountName, tc.args.initialModuleCoins) - suite.Require().NoError(err) - - suite.app = tApp - suite.ctx = ctx - suite.keeper = tApp.GetHardKeeper() - suite.keeper.SetSuppliedCoins(ctx, tc.args.initialModuleCoins) - - // Run begin blocker - hard.BeginBlocker(suite.ctx, suite.keeper) - - // // Deposit coins - err = suite.keeper.Deposit(suite.ctx, tc.args.user, tc.args.depositCoins) - suite.Require().NoError(err) - - // Borrow coins - err = suite.keeper.Borrow(suite.ctx, tc.args.user, tc.args.borrowCoins) - suite.Require().NoError(err) - - // Check interest levels for each snapshot - prevCtx := suite.ctx - for _, snapshot := range tc.args.expectedInterestSnaphots { - for _, coinDenom := range tc.args.coinDenoms { - // ---------------------------- Calculate expected supply interest ---------------------------- - // 1. Get cash, borrows, reserves, and borrow index - cashPrior := suite.getAccountCoins(suite.getModuleAccountAtCtx(types.ModuleName, prevCtx)).AmountOf(coinDenom) - - var borrowCoinPriorAmount sdkmath.Int - borrowCoinsPrior, borrowCoinsPriorFound := suite.keeper.GetBorrowedCoins(prevCtx) - suite.Require().True(borrowCoinsPriorFound) - borrowCoinPriorAmount = borrowCoinsPrior.AmountOf(coinDenom) - - var supplyCoinPriorAmount sdkmath.Int - supplyCoinsPrior, supplyCoinsPriorFound := suite.keeper.GetSuppliedCoins(prevCtx) - suite.Require().True(supplyCoinsPriorFound) - supplyCoinPriorAmount = supplyCoinsPrior.AmountOf(coinDenom) - - reservesPrior, foundReservesPrior := suite.keeper.GetTotalReserves(prevCtx) - if !foundReservesPrior { - reservesPrior = sdk.NewCoins(sdk.NewCoin(coinDenom, sdk.ZeroInt())) - } - - borrowInterestFactorPrior, foundBorrowInterestFactorPrior := suite.keeper.GetBorrowInterestFactor(prevCtx, coinDenom) - suite.Require().True(foundBorrowInterestFactorPrior) - - supplyInterestFactorPrior, foundSupplyInterestFactorPrior := suite.keeper.GetSupplyInterestFactor(prevCtx, coinDenom) - suite.Require().True(foundSupplyInterestFactorPrior) - - // 2. Calculate expected borrow interest owed - borrowRateApy, err := keeper.CalculateBorrowRate(tc.args.interestRateModel, sdk.NewDecFromInt(cashPrior), sdk.NewDecFromInt(borrowCoinPriorAmount), sdk.NewDecFromInt(reservesPrior.AmountOf(coinDenom))) - suite.Require().NoError(err) - - // Convert from APY to SPY, expressed as (1 + borrow rate) - borrowRateSpy, err := keeper.APYToSPY(sdk.OneDec().Add(borrowRateApy)) - suite.Require().NoError(err) - - newBorrowInterestFactor := keeper.CalculateBorrowInterestFactor(borrowRateSpy, sdkmath.NewInt(snapshot.elapsedTime)) - expectedBorrowInterest := (newBorrowInterestFactor.Mul(sdk.NewDecFromInt(borrowCoinPriorAmount)).TruncateInt()).Sub(borrowCoinPriorAmount) - expectedReserves := reservesPrior.Add(sdk.NewCoin(coinDenom, sdk.NewDecFromInt(expectedBorrowInterest).Mul(tc.args.reserveFactor).TruncateInt())).Sub(reservesPrior...) - expectedTotalReserves := expectedReserves.Add(reservesPrior...) - - expectedBorrowInterestFactor := borrowInterestFactorPrior.Mul(newBorrowInterestFactor) - expectedSupplyInterest := expectedBorrowInterest.Sub(expectedReserves.AmountOf(coinDenom)) - - newSupplyInterestFactor := keeper.CalculateSupplyInterestFactor(sdk.NewDecFromInt(expectedSupplyInterest), sdk.NewDecFromInt(cashPrior), sdk.NewDecFromInt(borrowCoinPriorAmount), sdk.NewDecFromInt(reservesPrior.AmountOf(coinDenom))) - expectedSupplyInterestFactor := supplyInterestFactorPrior.Mul(newSupplyInterestFactor) - // ------------------------------------------------------------------------------------- - - // Set up snapshot chain context and run begin blocker - runAtTime := prevCtx.BlockTime().Add(time.Duration(int64(time.Second) * snapshot.elapsedTime)) - snapshotCtx := prevCtx.WithBlockTime(runAtTime) - hard.BeginBlocker(snapshotCtx, suite.keeper) - - borrowInterestFactor, _ := suite.keeper.GetBorrowInterestFactor(ctx, coinDenom) - suite.Require().Equal(expectedBorrowInterestFactor, borrowInterestFactor) - suite.Require().Equal(expectedBorrowInterest, expectedSupplyInterest.Add(expectedReserves.AmountOf(coinDenom))) - - // Check that the total amount of borrowed coins has increased by expected borrow interest amount - borrowCoinsPost, _ := suite.keeper.GetBorrowedCoins(snapshotCtx) - borrowCoinPostAmount := borrowCoinsPost.AmountOf(coinDenom) - suite.Require().Equal(borrowCoinPostAmount, borrowCoinPriorAmount.Add(expectedBorrowInterest)) - - // Check that the total amount of supplied coins has increased by expected supply interest amount - supplyCoinsPost, _ := suite.keeper.GetSuppliedCoins(prevCtx) - supplyCoinPostAmount := supplyCoinsPost.AmountOf(coinDenom) - suite.Require().Equal(supplyCoinPostAmount, supplyCoinPriorAmount.Add(expectedSupplyInterest)) - - // Check current total reserves - totalReserves, _ := suite.keeper.GetTotalReserves(snapshotCtx) - suite.Require().Equal( - sdk.NewCoin(coinDenom, expectedTotalReserves.AmountOf(coinDenom)), - sdk.NewCoin(coinDenom, totalReserves.AmountOf(coinDenom)), - ) - - // Check that the supply index has increased as expected - currSupplyIndexPrior, _ := suite.keeper.GetSupplyInterestFactor(snapshotCtx, coinDenom) - suite.Require().Equal(expectedSupplyInterestFactor, currSupplyIndexPrior) - - // // Check that the borrow index has increased as expected - currBorrowIndexPrior, _ := suite.keeper.GetBorrowInterestFactor(snapshotCtx, coinDenom) - suite.Require().Equal(expectedBorrowInterestFactor, currBorrowIndexPrior) - - // After supplying again user's supplied balance should have owed supply interest applied - if snapshot.shouldSupply { - // Calculate percentage of supply interest profits owed to user - userSupplyBefore, _ := suite.keeper.GetDeposit(snapshotCtx, tc.args.user) - userSupplyCoinAmount := userSupplyBefore.Amount.AmountOf(coinDenom) - userPercentOfTotalSupplied := sdk.NewDecFromInt(userSupplyCoinAmount).Quo(sdk.NewDecFromInt(supplyCoinPriorAmount)) - userExpectedSupplyInterestCoin := sdk.NewCoin(coinDenom, userPercentOfTotalSupplied.MulInt(expectedSupplyInterest).TruncateInt()) - - // Supplying syncs user's owed supply and borrow interest - err = suite.keeper.Deposit(snapshotCtx, tc.args.user, sdk.NewCoins(snapshot.supplyCoin)) - suite.Require().NoError(err) - - // Fetch user's new borrow and supply balance post-interaction - userSupplyAfter, _ := suite.keeper.GetDeposit(snapshotCtx, tc.args.user) - - // Confirm that user's supply index for the denom has increased as expected - var userSupplyAfterIndexFactor sdk.Dec - for _, indexFactor := range userSupplyAfter.Index { - if indexFactor.Denom == coinDenom { - userSupplyAfterIndexFactor = indexFactor.Value - } - } - suite.Require().Equal(userSupplyAfterIndexFactor, currSupplyIndexPrior) - - // Check user's supplied amount increased by supply interest owed + the newly supplied coins - expectedSupplyCoinsAfter := userSupplyBefore.Amount.Add(snapshot.supplyCoin).Add(userExpectedSupplyInterestCoin) - suite.Require().Equal(expectedSupplyCoinsAfter, userSupplyAfter.Amount) - } - prevCtx = snapshotCtx - } - } - }) - } -} - -func TestInterestTestSuite(t *testing.T) { - suite.Run(t, new(InterestTestSuite)) -} diff --git a/x/hard/keeper/keeper.go b/x/hard/keeper/keeper.go deleted file mode 100644 index 1a974c56..00000000 --- a/x/hard/keeper/keeper.go +++ /dev/null @@ -1,366 +0,0 @@ -package keeper - -import ( - "time" - - "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" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - - "github.com/0glabs/0g-chain/x/hard/types" -) - -// Keeper keeper for the hard module -type Keeper struct { - key storetypes.StoreKey - cdc codec.Codec - paramSubspace paramtypes.Subspace - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - pricefeedKeeper types.PricefeedKeeper - auctionKeeper types.AuctionKeeper - hooks types.HARDHooks -} - -// NewKeeper creates a new keeper -func NewKeeper(cdc codec.Codec, key storetypes.StoreKey, paramstore paramtypes.Subspace, - ak types.AccountKeeper, bk types.BankKeeper, - pfk types.PricefeedKeeper, auk types.AuctionKeeper, -) Keeper { - if !paramstore.HasKeyTable() { - paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) - } - - return Keeper{ - key: key, - cdc: cdc, - paramSubspace: paramstore, - accountKeeper: ak, - bankKeeper: bk, - pricefeedKeeper: pfk, - auctionKeeper: auk, - hooks: nil, - } -} - -// SetHooks adds hooks to the keeper. -func (k *Keeper) SetHooks(hooks types.HARDHooks) *Keeper { - if k.hooks != nil { - panic("cannot set hard hooks twice") - } - k.hooks = hooks - return k -} - -// GetDeposit returns a deposit from the store for a particular depositor address, deposit denom -func (k Keeper) GetDeposit(ctx sdk.Context, depositor sdk.AccAddress) (types.Deposit, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositsKeyPrefix) - bz := store.Get(depositor.Bytes()) - if len(bz) == 0 { - return types.Deposit{}, false - } - var deposit types.Deposit - k.cdc.MustUnmarshal(bz, &deposit) - return deposit, true -} - -// SetDeposit sets the input deposit in the store, prefixed by the deposit type, deposit denom, and depositor address, in that order -func (k Keeper) SetDeposit(ctx sdk.Context, deposit types.Deposit) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositsKeyPrefix) - bz := k.cdc.MustMarshal(&deposit) - store.Set(deposit.Depositor.Bytes(), bz) -} - -// DeleteDeposit deletes a deposit from the store -func (k Keeper) DeleteDeposit(ctx sdk.Context, deposit types.Deposit) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositsKeyPrefix) - store.Delete(deposit.Depositor.Bytes()) -} - -// IterateDeposits iterates over all deposit objects in the store and performs a callback function -func (k Keeper) IterateDeposits(ctx sdk.Context, cb func(deposit types.Deposit) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositsKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var deposit types.Deposit - k.cdc.MustUnmarshal(iterator.Value(), &deposit) - if cb(deposit) { - break - } - } -} - -// GetDepositsByUser gets all deposits for an individual user -func (k Keeper) GetDepositsByUser(ctx sdk.Context, user sdk.AccAddress) []types.Deposit { - var deposits []types.Deposit - k.IterateDeposits(ctx, func(deposit types.Deposit) (stop bool) { - if deposit.Depositor.Equals(user) { - deposits = append(deposits, deposit) - } - return false - }) - return deposits -} - -// GetBorrow returns a Borrow from the store for a particular borrower address and borrow denom -func (k Keeper) GetBorrow(ctx sdk.Context, borrower sdk.AccAddress) (types.Borrow, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.BorrowsKeyPrefix) - bz := store.Get(borrower) - if len(bz) == 0 { - return types.Borrow{}, false - } - var borrow types.Borrow - k.cdc.MustUnmarshal(bz, &borrow) - return borrow, true -} - -// SetBorrow sets the input borrow in the store, prefixed by the borrower address and borrow denom -func (k Keeper) SetBorrow(ctx sdk.Context, borrow types.Borrow) { - store := prefix.NewStore(ctx.KVStore(k.key), types.BorrowsKeyPrefix) - bz := k.cdc.MustMarshal(&borrow) - store.Set(borrow.Borrower, bz) -} - -// DeleteBorrow deletes a borrow from the store -func (k Keeper) DeleteBorrow(ctx sdk.Context, borrow types.Borrow) { - store := prefix.NewStore(ctx.KVStore(k.key), types.BorrowsKeyPrefix) - store.Delete(borrow.Borrower) -} - -// IterateBorrows iterates over all borrow objects in the store and performs a callback function -func (k Keeper) IterateBorrows(ctx sdk.Context, cb func(borrow types.Borrow) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.BorrowsKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var borrow types.Borrow - k.cdc.MustUnmarshal(iterator.Value(), &borrow) - if cb(borrow) { - break - } - } -} - -// SetBorrowedCoins sets the total amount of coins currently borrowed in the store -func (k Keeper) SetBorrowedCoins(ctx sdk.Context, borrowedCoins sdk.Coins) { - store := prefix.NewStore(ctx.KVStore(k.key), types.BorrowedCoinsPrefix) - if borrowedCoins.Empty() { - store.Set(types.BorrowedCoinsPrefix, []byte{}) - } else { - bz := k.cdc.MustMarshal(&types.CoinsProto{ - Coins: borrowedCoins, - }) - store.Set(types.BorrowedCoinsPrefix, bz) - } -} - -// GetBorrowedCoins returns an sdk.Coins object from the store representing all currently borrowed coins -func (k Keeper) GetBorrowedCoins(ctx sdk.Context) (sdk.Coins, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.BorrowedCoinsPrefix) - bz := store.Get(types.BorrowedCoinsPrefix) - if len(bz) == 0 { - return sdk.Coins{}, false - } - var borrowed types.CoinsProto - k.cdc.MustUnmarshal(bz, &borrowed) - return borrowed.Coins, true -} - -// SetSuppliedCoins sets the total amount of coins currently supplied in the store -func (k Keeper) SetSuppliedCoins(ctx sdk.Context, suppliedCoins sdk.Coins) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SuppliedCoinsPrefix) - if suppliedCoins.Empty() { - store.Set(types.SuppliedCoinsPrefix, []byte{}) - } else { - bz := k.cdc.MustMarshal(&types.CoinsProto{ - Coins: suppliedCoins, - }) - store.Set(types.SuppliedCoinsPrefix, bz) - } -} - -// GetSuppliedCoins returns an sdk.Coins object from the store representing all currently supplied coins -func (k Keeper) GetSuppliedCoins(ctx sdk.Context) (sdk.Coins, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SuppliedCoinsPrefix) - bz := store.Get(types.SuppliedCoinsPrefix) - if len(bz) == 0 { - return sdk.Coins{}, false - } - var supplied types.CoinsProto - k.cdc.MustUnmarshal(bz, &supplied) - return supplied.Coins, true -} - -// GetMoneyMarket returns a money market from the store for a denom -func (k Keeper) GetMoneyMarket(ctx sdk.Context, denom string) (types.MoneyMarket, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.MoneyMarketsPrefix) - bz := store.Get([]byte(denom)) - if len(bz) == 0 { - return types.MoneyMarket{}, false - } - var moneyMarket types.MoneyMarket - k.cdc.MustUnmarshal(bz, &moneyMarket) - return moneyMarket, true -} - -// SetMoneyMarket sets a money market in the store for a denom -func (k Keeper) SetMoneyMarket(ctx sdk.Context, denom string, moneyMarket types.MoneyMarket) { - store := prefix.NewStore(ctx.KVStore(k.key), types.MoneyMarketsPrefix) - bz := k.cdc.MustMarshal(&moneyMarket) - store.Set([]byte(denom), bz) -} - -// DeleteMoneyMarket deletes a money market from the store -func (k Keeper) DeleteMoneyMarket(ctx sdk.Context, denom string) { - store := prefix.NewStore(ctx.KVStore(k.key), types.MoneyMarketsPrefix) - store.Delete([]byte(denom)) -} - -// IterateMoneyMarkets iterates over all money markets objects in the store and performs a callback function -// -// that returns both the money market and the key (denom) it's stored under -func (k Keeper) IterateMoneyMarkets(ctx sdk.Context, cb func(denom string, moneyMarket types.MoneyMarket) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.MoneyMarketsPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var moneyMarket types.MoneyMarket - k.cdc.MustUnmarshal(iterator.Value(), &moneyMarket) - if cb(string(iterator.Key()), moneyMarket) { - break - } - } -} - -// GetAllMoneyMarkets returns all money markets from the store -func (k Keeper) GetAllMoneyMarkets(ctx sdk.Context) (moneyMarkets types.MoneyMarkets) { - k.IterateMoneyMarkets(ctx, func(denom string, moneyMarket types.MoneyMarket) bool { - moneyMarkets = append(moneyMarkets, moneyMarket) - return false - }) - return -} - -// GetPreviousAccrualTime returns the last time an individual market accrued interest -func (k Keeper) GetPreviousAccrualTime(ctx sdk.Context, denom string) (time.Time, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousAccrualTimePrefix) - bz := store.Get([]byte(denom)) - if len(bz) == 0 { - return time.Time{}, false - } - - var previousAccrualTime time.Time - if err := previousAccrualTime.UnmarshalBinary(bz); err != nil { - panic(err) - } - return previousAccrualTime, true -} - -// SetPreviousAccrualTime sets the most recent accrual time for a particular market -func (k Keeper) SetPreviousAccrualTime(ctx sdk.Context, denom string, previousAccrualTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousAccrualTimePrefix) - bz, err := previousAccrualTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set([]byte(denom), bz) -} - -// SetTotalReserves sets the total reserves for an individual market -func (k Keeper) SetTotalReserves(ctx sdk.Context, coins sdk.Coins) { - store := prefix.NewStore(ctx.KVStore(k.key), types.TotalReservesPrefix) - if coins.Empty() { - store.Set(types.TotalReservesPrefix, []byte{}) - return - } - - bz := k.cdc.MustMarshal(&types.CoinsProto{ - Coins: coins, - }) - store.Set(types.TotalReservesPrefix, bz) -} - -// GetTotalReserves returns the total reserves for an individual market -func (k Keeper) GetTotalReserves(ctx sdk.Context) (sdk.Coins, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.TotalReservesPrefix) - bz := store.Get(types.TotalReservesPrefix) - if len(bz) == 0 { - return sdk.Coins{}, false - } - - var totalReserves types.CoinsProto - k.cdc.MustUnmarshal(bz, &totalReserves) - return totalReserves.Coins, true -} - -// GetBorrowInterestFactor returns the current borrow interest factor for an individual market -func (k Keeper) GetBorrowInterestFactor(ctx sdk.Context, denom string) (sdk.Dec, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.BorrowInterestFactorPrefix) - bz := store.Get([]byte(denom)) - if len(bz) == 0 { - return sdk.ZeroDec(), false - } - var borrowInterestFactor sdk.DecProto - k.cdc.MustUnmarshal(bz, &borrowInterestFactor) - return borrowInterestFactor.Dec, true -} - -// SetBorrowInterestFactor sets the current borrow interest factor for an individual market -func (k Keeper) SetBorrowInterestFactor(ctx sdk.Context, denom string, borrowInterestFactor sdk.Dec) { - store := prefix.NewStore(ctx.KVStore(k.key), types.BorrowInterestFactorPrefix) - bz := k.cdc.MustMarshal(&sdk.DecProto{Dec: borrowInterestFactor}) - store.Set([]byte(denom), bz) -} - -// IterateBorrowInterestFactors iterates over all borrow interest factors in the store and returns -// both the borrow interest factor and the key (denom) it's stored under -func (k Keeper) IterateBorrowInterestFactors(ctx sdk.Context, cb func(denom string, factor sdk.Dec) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.BorrowInterestFactorPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var factor sdk.DecProto - k.cdc.MustUnmarshal(iterator.Value(), &factor) - if cb(string(iterator.Key()), factor.Dec) { - break - } - } -} - -// GetSupplyInterestFactor returns the current supply interest factor for an individual market -func (k Keeper) GetSupplyInterestFactor(ctx sdk.Context, denom string) (sdk.Dec, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SupplyInterestFactorPrefix) - bz := store.Get([]byte(denom)) - if len(bz) == 0 { - return sdk.ZeroDec(), false - } - var supplyInterestFactor sdk.DecProto - k.cdc.MustUnmarshal(bz, &supplyInterestFactor) - return supplyInterestFactor.Dec, true -} - -// SetSupplyInterestFactor sets the current supply interest factor for an individual market -func (k Keeper) SetSupplyInterestFactor(ctx sdk.Context, denom string, supplyInterestFactor sdk.Dec) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SupplyInterestFactorPrefix) - bz := k.cdc.MustMarshal(&sdk.DecProto{Dec: supplyInterestFactor}) - store.Set([]byte(denom), bz) -} - -// IterateSupplyInterestFactors iterates over all supply interest factors in the store and returns -// both the supply interest factor and the key (denom) it's stored under -func (k Keeper) IterateSupplyInterestFactors(ctx sdk.Context, cb func(denom string, factor sdk.Dec) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SupplyInterestFactorPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var factor sdk.DecProto - - k.cdc.MustUnmarshal(iterator.Value(), &factor) - if cb(string(iterator.Key()), factor.Dec) { - break - } - } -} diff --git a/x/hard/keeper/keeper_test.go b/x/hard/keeper/keeper_test.go deleted file mode 100644 index dc4621b1..00000000 --- a/x/hard/keeper/keeper_test.go +++ /dev/null @@ -1,235 +0,0 @@ -package keeper_test - -import ( - "fmt" - "strconv" - "testing" - - sdkmath "cosmossdk.io/math" - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - "github.com/0glabs/0g-chain/app" - auctionkeeper "github.com/0glabs/0g-chain/x/auction/keeper" - "github.com/0glabs/0g-chain/x/hard/keeper" - "github.com/0glabs/0g-chain/x/hard/types" -) - -// Test suite used for all keeper tests -type KeeperTestSuite struct { - suite.Suite - keeper keeper.Keeper - auctionKeeper auctionkeeper.Keeper - app app.TestApp - ctx sdk.Context - addrs []sdk.AccAddress -} - -// The default state used by each test -func (suite *KeeperTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - tApp.InitializeFromGenesisStates() - _, addrs := app.GeneratePrivKeyAddressPairs(1) - keeper := tApp.GetHardKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - suite.addrs = addrs -} - -func (suite *KeeperTestSuite) TestGetSetDeleteDeposit() { - addr := suite.addrs[0] - dep := types.NewDeposit( - addr, - sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - types.SupplyInterestFactors{types.NewSupplyInterestFactor("bnb", sdk.MustNewDecFromStr("1.12"))}, - ) - - _, f := suite.keeper.GetDeposit(suite.ctx, addr) - suite.Require().False(f) - - suite.keeper.SetDeposit(suite.ctx, dep) - - storedDeposit, f := suite.keeper.GetDeposit(suite.ctx, addr) - suite.Require().True(f) - suite.Require().Equal(dep, storedDeposit) - - suite.Require().NotPanics(func() { suite.keeper.DeleteDeposit(suite.ctx, dep) }) - - _, f = suite.keeper.GetDeposit(suite.ctx, addr) - suite.Require().False(f) -} - -func (suite *KeeperTestSuite) TestIterateDeposits() { - var deposits types.Deposits - for i := 0; i < 5; i++ { - dep := types.NewDeposit( - sdk.AccAddress("test"+fmt.Sprint(i)), - sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - types.SupplyInterestFactors{types.NewSupplyInterestFactor("bnb", sdk.MustNewDecFromStr("1.12"))}, - ) - deposits = append(deposits, dep) - suite.keeper.SetDeposit(suite.ctx, dep) - } - var storedDeposits types.Deposits - suite.keeper.IterateDeposits(suite.ctx, func(d types.Deposit) bool { - storedDeposits = append(storedDeposits, d) - return false - }) - suite.Require().Equal(deposits, storedDeposits) -} - -func (suite *KeeperTestSuite) TestGetSetDeleteBorrow() { - addr := suite.addrs[0] - - borrow := types.NewBorrow( - addr, - sdk.NewCoins(sdk.NewInt64Coin("bnb", 1e9)), - types.BorrowInterestFactors{types.NewBorrowInterestFactor("bnb", sdk.MustNewDecFromStr("1.12"))}, - ) - - _, f := suite.keeper.GetBorrow(suite.ctx, addr) - suite.Require().False(f) - - suite.keeper.SetBorrow(suite.ctx, borrow) - - storedBorrow, f := suite.keeper.GetBorrow(suite.ctx, addr) - suite.Require().True(f) - suite.Require().Equal(borrow, storedBorrow) - - suite.Require().NotPanics(func() { suite.keeper.DeleteBorrow(suite.ctx, borrow) }) - - _, f = suite.keeper.GetBorrow(suite.ctx, addr) - suite.Require().False(f) -} - -func (suite *KeeperTestSuite) TestIterateBorrows() { - var borrows types.Borrows - for i := 0; i < 5; i++ { - borrow := types.NewBorrow( - sdk.AccAddress("test"+fmt.Sprint(i)), - sdk.NewCoins(sdk.NewInt64Coin("bnb", 1e9)), - types.BorrowInterestFactors{types.NewBorrowInterestFactor("bnb", sdk.MustNewDecFromStr("1.12"))}, - ) - borrows = append(borrows, borrow) - suite.keeper.SetBorrow(suite.ctx, borrow) - } - var storedBorrows types.Borrows - suite.keeper.IterateBorrows(suite.ctx, func(b types.Borrow) bool { - storedBorrows = append(storedBorrows, b) - return false - }) - suite.Require().Equal(borrows, storedBorrows) -} - -func (suite *KeeperTestSuite) TestGetSetDeleteInterestRateModel() { - denom := "test" - model := types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")) - borrowLimit := types.NewBorrowLimit(false, sdk.MustNewDecFromStr("0.2"), sdk.MustNewDecFromStr("0.5")) - moneyMarket := types.NewMoneyMarket(denom, borrowLimit, denom+":usd", sdkmath.NewInt(1000000), model, sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()) - - _, f := suite.keeper.GetMoneyMarket(suite.ctx, denom) - suite.Require().False(f) - - suite.keeper.SetMoneyMarket(suite.ctx, denom, moneyMarket) - - testMoneyMarket, f := suite.keeper.GetMoneyMarket(suite.ctx, denom) - suite.Require().True(f) - suite.Require().Equal(moneyMarket, testMoneyMarket) - - suite.Require().NotPanics(func() { suite.keeper.DeleteMoneyMarket(suite.ctx, denom) }) - - _, f = suite.keeper.GetMoneyMarket(suite.ctx, denom) - suite.Require().False(f) -} - -func (suite *KeeperTestSuite) TestIterateInterestRateModels() { - testDenom := "test" - var setMMs types.MoneyMarkets - var setDenoms []string - for i := 0; i < 5; i++ { - // Initialize a new money market - denom := testDenom + strconv.Itoa(i) - model := types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")) - borrowLimit := types.NewBorrowLimit(false, sdk.MustNewDecFromStr("0.2"), sdk.MustNewDecFromStr("0.5")) - moneyMarket := types.NewMoneyMarket(denom, borrowLimit, denom+":usd", sdkmath.NewInt(1000000), model, sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()) - - // Store money market in the module's store - suite.Require().NotPanics(func() { suite.keeper.SetMoneyMarket(suite.ctx, denom, moneyMarket) }) - - // Save the denom and model - setDenoms = append(setDenoms, denom) - setMMs = append(setMMs, moneyMarket) - } - - var seenMMs types.MoneyMarkets - var seenDenoms []string - suite.keeper.IterateMoneyMarkets(suite.ctx, func(denom string, i types.MoneyMarket) bool { - seenDenoms = append(seenDenoms, denom) - seenMMs = append(seenMMs, i) - return false - }) - - suite.Require().Equal(setMMs, seenMMs) - suite.Require().Equal(setDenoms, seenDenoms) -} - -func (suite *KeeperTestSuite) TestGetSetBorrowedCoins() { - suite.keeper.SetBorrowedCoins(suite.ctx, sdk.Coins{c("ukava", 123)}) - - coins, found := suite.keeper.GetBorrowedCoins(suite.ctx) - suite.Require().True(found) - suite.Require().Len(coins, 1) - suite.Require().Equal(coins, cs(c("ukava", 123))) -} - -func (suite *KeeperTestSuite) TestGetSetBorrowedCoins_Empty() { - coins, found := suite.keeper.GetBorrowedCoins(suite.ctx) - suite.Require().False(found) - suite.Require().Empty(coins) - - // None set and setting empty coins should both be the same - suite.keeper.SetBorrowedCoins(suite.ctx, sdk.Coins{}) - - coins, found = suite.keeper.GetBorrowedCoins(suite.ctx) - suite.Require().False(found) - suite.Require().Empty(coins) -} - -func (suite *KeeperTestSuite) getAccountCoins(acc authtypes.AccountI) sdk.Coins { - bk := suite.app.GetBankKeeper() - return bk.GetAllBalances(suite.ctx, acc.GetAddress()) -} - -func (suite *KeeperTestSuite) getAccount(addr sdk.AccAddress) authtypes.AccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetAccount(suite.ctx, addr) -} - -func (suite *KeeperTestSuite) getAccountAtCtx(addr sdk.AccAddress, ctx sdk.Context) authtypes.AccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetAccount(ctx, addr) -} - -func (suite *KeeperTestSuite) getModuleAccount(name string) authtypes.ModuleAccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetModuleAccount(suite.ctx, name) -} - -func (suite *KeeperTestSuite) getModuleAccountAtCtx(name string, ctx sdk.Context) authtypes.ModuleAccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetModuleAccount(ctx, name) -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} diff --git a/x/hard/keeper/liquidation.go b/x/hard/keeper/liquidation.go deleted file mode 100644 index decf5c7d..00000000 --- a/x/hard/keeper/liquidation.go +++ /dev/null @@ -1,428 +0,0 @@ -package keeper - -import ( - "sort" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/hard/types" -) - -// LiqData holds liquidation-related data -type LiqData struct { - price sdk.Dec - ltv sdk.Dec - conversionFactor sdkmath.Int -} - -// AttemptKeeperLiquidation enables a keeper to liquidate an individual borrower's position -func (k Keeper) AttemptKeeperLiquidation(ctx sdk.Context, keeper sdk.AccAddress, borrower sdk.AccAddress) error { - deposit, found := k.GetDeposit(ctx, borrower) - if !found { - return types.ErrDepositNotFound - } - - borrow, found := k.GetBorrow(ctx, borrower) - if !found { - return types.ErrBorrowNotFound - } - - // Call incentive hooks - k.BeforeDepositModified(ctx, deposit) - k.BeforeBorrowModified(ctx, borrow) - - k.SyncBorrowInterest(ctx, borrower) - k.SyncSupplyInterest(ctx, borrower) - - deposit, found = k.GetDeposit(ctx, borrower) - if !found { - return types.ErrDepositNotFound - } - - borrow, found = k.GetBorrow(ctx, borrower) - if !found { - return types.ErrBorrowNotFound - } - - isWithinRange, err := k.IsWithinValidLtvRange(ctx, deposit, borrow) - if err != nil { - return err - } - if isWithinRange { - return errorsmod.Wrapf(types.ErrBorrowNotLiquidatable, "position is within valid LTV range") - } - - // Sending coins to auction module with keeper address getting % of the profits - borrowDenoms := getDenoms(borrow.Amount) - depositDenoms := getDenoms(deposit.Amount) - err = k.SeizeDeposits(ctx, keeper, deposit, borrow, depositDenoms, borrowDenoms) - if err != nil { - return err - } - - deposit.Amount = sdk.NewCoins() - k.DeleteDeposit(ctx, deposit) - k.AfterDepositModified(ctx, deposit) - - borrow.Amount = sdk.NewCoins() - k.DeleteBorrow(ctx, borrow) - k.AfterBorrowModified(ctx, borrow) - return nil -} - -// SeizeDeposits seizes a list of deposits and sends them to auction -func (k Keeper) SeizeDeposits(ctx sdk.Context, keeper sdk.AccAddress, deposit types.Deposit, - borrow types.Borrow, dDenoms, bDenoms []string, -) error { - liqMap, err := k.LoadLiquidationData(ctx, deposit, borrow) - if err != nil { - return err - } - - // Seize % of every deposit and send to the keeper - keeperRewardCoins := sdk.Coins{} - for _, depCoin := range deposit.Amount { - mm, _ := k.GetMoneyMarket(ctx, depCoin.Denom) - keeperReward := mm.KeeperRewardPercentage.MulInt(depCoin.Amount).TruncateInt() - if keeperReward.GT(sdk.ZeroInt()) { - // Send keeper their reward - keeperCoin := sdk.NewCoin(depCoin.Denom, keeperReward) - keeperRewardCoins = append(keeperRewardCoins, keeperCoin) - } - } - if !keeperRewardCoins.Empty() { - if err := k.DecrementSuppliedCoins(ctx, keeperRewardCoins); err != nil { - return err - } - if err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, keeper, keeperRewardCoins); err != nil { - return err - } - } - - // All deposit amounts not given to keeper as rewards are eligible to be auctioned off - aucDeposits := deposit.Amount.Sub(keeperRewardCoins...) - - // Build valuation map to hold deposit coin USD valuations - depositCoinValues := types.NewValuationMap() - for _, deposit := range aucDeposits { - dData := liqMap[deposit.Denom] - dCoinUsdValue := sdk.NewDecFromInt(deposit.Amount).Quo(sdk.NewDecFromInt(dData.conversionFactor)).Mul(dData.price) - depositCoinValues.Increment(deposit.Denom, dCoinUsdValue) - } - - // Build valuation map to hold borrow coin USD valuations - borrowCoinValues := types.NewValuationMap() - for _, bCoin := range borrow.Amount { - bData := liqMap[bCoin.Denom] - bCoinUsdValue := sdk.NewDecFromInt(bCoin.Amount).Quo(sdk.NewDecFromInt(bData.conversionFactor)).Mul(bData.price) - borrowCoinValues.Increment(bCoin.Denom, bCoinUsdValue) - } - - // Loan-to-Value ratio after sending keeper their reward - depositUsdValue := depositCoinValues.Sum() - if depositUsdValue.IsZero() { - // Deposit value can be zero if params.KeeperRewardPercent is 1.0, or all deposit asset prices are zero. - // In this case the full deposit will be sent to the keeper and no auctions started. - return nil - } - ltv := borrowCoinValues.Sum().Quo(depositUsdValue) - - liquidatedCoins, err := k.StartAuctions(ctx, deposit.Depositor, borrow.Amount, aucDeposits, depositCoinValues, borrowCoinValues, ltv, liqMap) - // If some coins were liquidated and sent to auction prior to error, still need to emit liquidation event - if !liquidatedCoins.Empty() { - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeHardLiquidation, - sdk.NewAttribute(types.AttributeKeyLiquidatedOwner, deposit.Depositor.String()), - sdk.NewAttribute(types.AttributeKeyLiquidatedCoins, liquidatedCoins.String()), - sdk.NewAttribute(types.AttributeKeyKeeper, keeper.String()), - sdk.NewAttribute(types.AttributeKeyKeeperRewardCoins, keeperRewardCoins.String()), - ), - ) - } - // Returns nil if there's no error - return err -} - -// StartAuctions attempts to start auctions for seized assets -func (k Keeper) StartAuctions(ctx sdk.Context, borrower sdk.AccAddress, borrows, deposits sdk.Coins, - depositCoinValues, borrowCoinValues types.ValuationMap, ltv sdk.Dec, liqMap map[string]LiqData, -) (sdk.Coins, error) { - // Sort keys to ensure deterministic behavior - bKeys := borrowCoinValues.GetSortedKeys() - dKeys := depositCoinValues.GetSortedKeys() - - // Set up auction constants - returnAddrs := []sdk.AccAddress{borrower} - weights := []sdkmath.Int{sdkmath.NewInt(100)} - debt := sdk.NewCoin("debt", sdk.ZeroInt()) - - macc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) - maccCoins := k.bankKeeper.SpendableCoins(ctx, macc.GetAddress()) - - var liquidatedCoins sdk.Coins - for _, bKey := range bKeys { - bValue := borrowCoinValues.Get(bKey) - maxLotSize := bValue.Quo(ltv) - - for _, dKey := range dKeys { - dValue := depositCoinValues.Get(dKey) - if maxLotSize.Equal(sdk.ZeroDec()) { - break // exit out of the loop if we have cleared the full amount - } - - if dValue.GTE(maxLotSize) { // We can start an auction for the whole borrow amount] - bid := sdk.NewCoin(bKey, borrows.AmountOf(bKey)) - - lotSize := maxLotSize.MulInt(liqMap[dKey].conversionFactor).Quo(liqMap[dKey].price) - if lotSize.TruncateInt().Equal(sdk.ZeroInt()) { - continue - } - lot := sdk.NewCoin(dKey, lotSize.TruncateInt()) - - insufficientLotFunds := false - if lot.Amount.GT(maccCoins.AmountOf(dKey)) { - insufficientLotFunds = true - lot = sdk.NewCoin(lot.Denom, maccCoins.AmountOf(dKey)) - } - - // Sanity check that we can deliver coins to the liquidator account - if deposits.AmountOf(dKey).LT(lot.Amount) { - return liquidatedCoins, types.ErrInsufficientCoins - } - - // Start auction: bid = full borrow amount, lot = maxLotSize - _, err := k.auctionKeeper.StartCollateralAuction(ctx, types.ModuleAccountName, lot, bid, returnAddrs, weights, debt) - if err != nil { - return liquidatedCoins, err - } - // Decrement supplied coins and decrement borrowed coins optimistically - err = k.DecrementSuppliedCoins(ctx, sdk.Coins{lot}) - if err != nil { - return liquidatedCoins, err - } - err = k.DecrementBorrowedCoins(ctx, sdk.Coins{bid}) - if err != nil { - return liquidatedCoins, err - } - - // Add lot to liquidated coins - liquidatedCoins = liquidatedCoins.Add(lot) - - // Update USD valuation maps - borrowCoinValues.SetZero(bKey) - depositCoinValues.Decrement(dKey, maxLotSize) - // Update deposits, borrows - borrows = borrows.Sub(bid) - if insufficientLotFunds { - deposits = deposits.Sub(sdk.NewCoin(dKey, deposits.AmountOf(dKey))) - } else { - deposits = deposits.Sub(lot) - } - // Update max lot size - maxLotSize = sdk.ZeroDec() - } else { // We can only start an auction for the partial borrow amount - maxBid := dValue.Mul(ltv) - bidSize := maxBid.MulInt(liqMap[bKey].conversionFactor).Quo(liqMap[bKey].price) - bid := sdk.NewCoin(bKey, bidSize.TruncateInt()) - lot := sdk.NewCoin(dKey, deposits.AmountOf(dKey)) - - if bid.Amount.Equal(sdk.ZeroInt()) || lot.Amount.Equal(sdk.ZeroInt()) { - continue - } - - insufficientLotFunds := false - if lot.Amount.GT(maccCoins.AmountOf(dKey)) { - insufficientLotFunds = true - lot = sdk.NewCoin(lot.Denom, maccCoins.AmountOf(dKey)) - } - - // Sanity check that we can deliver coins to the liquidator account - if deposits.AmountOf(dKey).LT(lot.Amount) { - return liquidatedCoins, types.ErrInsufficientCoins - } - - // Start auction: bid = maxBid, lot = whole deposit amount - _, err := k.auctionKeeper.StartCollateralAuction(ctx, types.ModuleAccountName, lot, bid, returnAddrs, weights, debt) - if err != nil { - return liquidatedCoins, err - } - // Decrement supplied coins and decrement borrowed coins optimistically - err = k.DecrementSuppliedCoins(ctx, sdk.Coins{lot}) - if err != nil { - return liquidatedCoins, err - } - err = k.DecrementBorrowedCoins(ctx, sdk.Coins{bid}) - if err != nil { - return liquidatedCoins, err - } - - // Add lot to liquidated coins - liquidatedCoins = liquidatedCoins.Add(lot) - - // Update variables to account for partial auction - borrowCoinValues.Decrement(bKey, maxBid) - depositCoinValues.SetZero(dKey) - - borrows = borrows.Sub(bid) - if insufficientLotFunds { - deposits = deposits.Sub(sdk.NewCoin(dKey, deposits.AmountOf(dKey))) - } else { - deposits = deposits.Sub(lot) - } - - // Update max lot size - maxLotSize = borrowCoinValues.Get(bKey).Quo(ltv) - } - } - } - - // Send any remaining deposit back to the original borrower - for _, dKey := range dKeys { - remaining := deposits.AmountOf(dKey) - if remaining.GT(sdk.ZeroInt()) { - returnCoin := sdk.NewCoins(sdk.NewCoin(dKey, remaining)) - err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, borrower, returnCoin) - if err != nil { - return liquidatedCoins, err - } - } - } - - return liquidatedCoins, nil -} - -// IsWithinValidLtvRange compares a borrow and deposit to see if it's within a valid LTV range at current prices -func (k Keeper) IsWithinValidLtvRange(ctx sdk.Context, deposit types.Deposit, borrow types.Borrow) (bool, error) { - liqMap, err := k.LoadLiquidationData(ctx, deposit, borrow) - if err != nil { - return false, err - } - - totalBorrowableUSDAmount := sdk.ZeroDec() - for _, depCoin := range deposit.Amount { - lData := liqMap[depCoin.Denom] - usdValue := sdk.NewDecFromInt(depCoin.Amount).Quo(sdk.NewDecFromInt(lData.conversionFactor)).Mul(lData.price) - borrowableUSDAmountForDeposit := usdValue.Mul(lData.ltv) - totalBorrowableUSDAmount = totalBorrowableUSDAmount.Add(borrowableUSDAmountForDeposit) - } - - totalBorrowedUSDAmount := sdk.ZeroDec() - for _, coin := range borrow.Amount { - lData := liqMap[coin.Denom] - usdValue := sdk.NewDecFromInt(coin.Amount).Quo(sdk.NewDecFromInt(lData.conversionFactor)).Mul(lData.price) - totalBorrowedUSDAmount = totalBorrowedUSDAmount.Add(usdValue) - } - - // Check if the user's has borrowed more than they're allowed to - if totalBorrowedUSDAmount.GT(totalBorrowableUSDAmount) { - return false, nil - } - - return true, nil -} - -// GetStoreLTV calculates the user's current LTV based on their deposits/borrows in the store -// and does not include any outsanding interest. -func (k Keeper) GetStoreLTV(ctx sdk.Context, addr sdk.AccAddress) (sdk.Dec, error) { - // Fetch deposits and parse coin denoms - deposit, found := k.GetDeposit(ctx, addr) - if !found { - return sdk.ZeroDec(), nil - } - - // Fetch borrow balances and parse coin denoms - borrow, found := k.GetBorrow(ctx, addr) - if !found { - return sdk.ZeroDec(), nil - } - - return k.CalculateLtv(ctx, deposit, borrow) -} - -// CalculateLtv calculates the potential LTV given a user's deposits and borrows. -// The boolean returned indicates if the LTV should be added to the store's LTV index. -func (k Keeper) CalculateLtv(ctx sdk.Context, deposit types.Deposit, borrow types.Borrow) (sdk.Dec, error) { - // Load required liquidation data for every deposit/borrow denom - liqMap, err := k.LoadLiquidationData(ctx, deposit, borrow) - if err != nil { - return sdk.ZeroDec(), nil - } - - // Build valuation map to hold deposit coin USD valuations - depositCoinValues := types.NewValuationMap() - for _, depCoin := range deposit.Amount { - dData := liqMap[depCoin.Denom] - dCoinUsdValue := sdk.NewDecFromInt(depCoin.Amount).Quo(sdk.NewDecFromInt(dData.conversionFactor)).Mul(dData.price) - depositCoinValues.Increment(depCoin.Denom, dCoinUsdValue) - } - - // Build valuation map to hold borrow coin USD valuations - borrowCoinValues := types.NewValuationMap() - for _, bCoin := range borrow.Amount { - bData := liqMap[bCoin.Denom] - bCoinUsdValue := sdk.NewDecFromInt(bCoin.Amount).Quo(sdk.NewDecFromInt(bData.conversionFactor)).Mul(bData.price) - borrowCoinValues.Increment(bCoin.Denom, bCoinUsdValue) - } - - // User doesn't have any deposits, catch divide by 0 error - sumDeposits := depositCoinValues.Sum() - if sumDeposits.Equal(sdk.ZeroDec()) { - return sdk.ZeroDec(), nil - } - - // Loan-to-Value ratio - return borrowCoinValues.Sum().Quo(sumDeposits), nil -} - -// LoadLiquidationData returns liquidation data, deposit, borrow -func (k Keeper) LoadLiquidationData(ctx sdk.Context, deposit types.Deposit, borrow types.Borrow) (map[string]LiqData, error) { - liqMap := make(map[string]LiqData) - - borrowDenoms := getDenoms(borrow.Amount) - depositDenoms := getDenoms(deposit.Amount) - denoms := removeDuplicates(borrowDenoms, depositDenoms) - - // Load required liquidation data for every deposit/borrow denom - for _, denom := range denoms { - mm, found := k.GetMoneyMarket(ctx, denom) - if !found { - return liqMap, errorsmod.Wrapf(types.ErrMarketNotFound, "no market found for denom %s", denom) - } - - priceData, err := k.pricefeedKeeper.GetCurrentPrice(ctx, mm.SpotMarketID) - if err != nil { - return liqMap, err - } - - liqMap[denom] = LiqData{priceData.Price, mm.BorrowLimit.LoanToValue, mm.ConversionFactor} - } - - return liqMap, nil -} - -func getDenoms(coins sdk.Coins) []string { - denoms := []string{} - for _, coin := range coins { - denoms = append(denoms, coin.Denom) - } - return denoms -} - -func removeDuplicates(one []string, two []string) []string { - check := make(map[string]int) - fullList := append(one, two...) - - res := []string{} - for _, val := range fullList { - check[val] = 1 - } - - for key := range check { - res = append(res, key) - } - sort.Strings(res) - return res -} diff --git a/x/hard/keeper/liquidation_test.go b/x/hard/keeper/liquidation_test.go deleted file mode 100644 index 36a2c012..00000000 --- a/x/hard/keeper/liquidation_test.go +++ /dev/null @@ -1,765 +0,0 @@ -package keeper_test - -import ( - "strings" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/app" - auctiontypes "github.com/0glabs/0g-chain/x/auction/types" - "github.com/0glabs/0g-chain/x/hard" - "github.com/0glabs/0g-chain/x/hard/types" - pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" -) - -func (suite *KeeperTestSuite) TestKeeperLiquidation() { - type args struct { - borrower sdk.AccAddress - keeper sdk.AccAddress - keeperRewardPercent sdk.Dec - initialModuleCoins sdk.Coins - initialBorrowerCoins sdk.Coins - initialKeeperCoins sdk.Coins - depositCoins []sdk.Coin - borrowCoins sdk.Coins - liquidateAfter time.Duration - expectedTotalSuppliedCoins sdk.Coins - expectedTotalBorrowedCoins sdk.Coins - expectedKeeperCoins sdk.Coins // coins keeper address should have after successfully liquidating position - expectedBorrowerCoins sdk.Coins // additional coins (if any) the borrower address should have after successfully liquidating position - expectedAuctions []auctiontypes.Auction // the auctions we should expect to find have been started - } - - type errArgs struct { - expectPass bool - contains string - } - - type liqTest struct { - name string - args args - errArgs errArgs - } - - // Set up test constants - model := types.NewInterestRateModel(sdk.MustNewDecFromStr("0"), sdk.MustNewDecFromStr("0.1"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("0.5")) - reserveFactor := sdk.MustNewDecFromStr("0.05") - oneMonthDur := time.Second * 30 * 24 * 3600 - borrower := sdk.AccAddress(crypto.AddressHash([]byte("testborrower"))) - keeper := sdk.AccAddress(crypto.AddressHash([]byte("testkeeper"))) - - // Set up auction constants - layout := "2006-01-02T15:04:05.000Z" - endTimeStr := "9000-01-01T00:00:00.000Z" - endTime, _ := time.Parse(layout, endTimeStr) - - lotReturns, _ := auctiontypes.NewWeightedAddresses([]sdk.AccAddress{borrower}, []sdkmath.Int{sdkmath.NewInt(100)}) - - testCases := []liqTest{ - { - "valid: keeper liquidates borrow", - args{ - borrower: borrower, - keeper: keeper, - keeperRewardPercent: sdk.MustNewDecFromStr("0.05"), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10*KAVA_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(8*KAVA_CF))), - liquidateAfter: oneMonthDur, - expectedTotalSuppliedCoins: sdk.NewCoins(sdk.NewInt64Coin("ukava", 100004118)), - expectedTotalBorrowedCoins: nil, - expectedKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100500020))), - expectedBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(98000001))), // initial - deposit + borrow + liquidation leftovers - expectedAuctions: []auctiontypes.Auction{ - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 1, - Initiator: "hard", - Lot: sdk.NewInt64Coin("ukava", 9500390), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("ukava", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("ukava", 8004766), - LotReturns: lotReturns, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid: 0% keeper rewards", - args{ - borrower: borrower, - keeper: keeper, - keeperRewardPercent: sdk.MustNewDecFromStr("0.0"), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10*KAVA_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(8*KAVA_CF))), - liquidateAfter: oneMonthDur, - expectedTotalSuppliedCoins: sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_004_117)), - expectedTotalBorrowedCoins: sdk.NewCoins(sdk.NewInt64Coin("ukava", 1)), - expectedKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - expectedBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(98*KAVA_CF))), // initial - deposit + borrow + liquidation leftovers - expectedAuctions: []auctiontypes.Auction{ - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 1, - Initiator: "hard", - Lot: sdk.NewInt64Coin("ukava", 10000411), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("ukava", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("ukava", 8004765), - LotReturns: lotReturns, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid: 100% keeper reward", - args{ - borrower: borrower, - keeper: keeper, - keeperRewardPercent: sdk.MustNewDecFromStr("1.0"), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10*KAVA_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(8*KAVA_CF))), - liquidateAfter: oneMonthDur, - expectedTotalSuppliedCoins: sdk.NewCoins(sdk.NewInt64Coin("ukava", 100_004_117)), - expectedTotalBorrowedCoins: sdk.NewCoins(sdk.NewInt64Coin("ukava", 8_004_766)), - expectedKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(110_000_411))), - expectedBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(98*KAVA_CF))), // initial - deposit + borrow + liquidation leftovers - expectedAuctions: nil, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid: single deposit, multiple borrows", - args{ - borrower: borrower, - keeper: keeper, - keeperRewardPercent: sdk.MustNewDecFromStr("0.05"), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdc", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(1000*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(1000*BTCB_CF))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), // $100 * 0.8 = $80 borrowable - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdc", sdkmath.NewInt(20*KAVA_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(10*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(2*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(0.2*BTCB_CF))), // $20+$20+$20 = $80 borrowed - liquidateAfter: oneMonthDur, - expectedTotalSuppliedCoins: sdk.NewCoins( - sdk.NewInt64Coin("ukava", 1000000710), - sdk.NewInt64Coin("usdc", 1000003120), - sdk.NewInt64Coin("bnb", 100000003123), - sdk.NewInt64Coin("btc", 100000000031), - ), - expectedTotalBorrowedCoins: nil, - expectedKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(102500001))), - expectedBorrowerCoins: sdk.NewCoins(sdk.NewCoin("usdc", sdkmath.NewInt(20*KAVA_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(60000002)), sdk.NewCoin("bnb", sdkmath.NewInt(2*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(0.2*BTCB_CF))), // initial - deposit + borrow + liquidation leftovers - expectedAuctions: []auctiontypes.Auction{ - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 1, - Initiator: "hard", - Lot: sdk.NewInt64Coin("ukava", 11874430), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("bnb", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("bnb", 200003287), - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 2, - Initiator: "hard", - Lot: sdk.NewInt64Coin("ukava", 11874254), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("btc", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("btc", 20000032), - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 3, - Initiator: "hard", - Lot: sdk.NewInt64Coin("ukava", 11875163), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("ukava", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("ukava", 10000782), - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 4, - Initiator: "hard", - Lot: sdk.NewInt64Coin("ukava", 11876185), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("usdc", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("usdc", 20003284), - LotReturns: lotReturns, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid: multiple deposits, single borrow", - args{ - borrower: borrower, - keeper: keeper, - keeperRewardPercent: sdk.MustNewDecFromStr("0.05"), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(100*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(100*BTCB_CF))), - initialKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(10*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(1*BTCB_CF))), // $100 + $100 + $100 = $300 * 0.8 = $240 borrowable // $100 * 0.8 = $80 borrowable - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(120*KAVA_CF))), // $240 borrowed - liquidateAfter: oneMonthDur, - expectedTotalSuppliedCoins: sdk.NewCoins( - sdk.NewInt64Coin("ukava", 1000101456), - ), - expectedTotalBorrowedCoins: nil, - expectedKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(102500253)), sdk.NewCoin("bnb", sdkmath.NewInt(0.5*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(0.05*BTCB_CF))), // 5% of each seized coin + initial balances - expectedBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(170.000001*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(90*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(99*BTCB_CF))), - expectedAuctions: []auctiontypes.Auction{ - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 1, - Initiator: "hard", - Lot: sdk.NewInt64Coin("bnb", 950000000), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("ukava", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("ukava", 40036023), - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 2, - Initiator: "hard", - Lot: sdk.NewInt64Coin("btc", 95000000), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("ukava", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("ukava", 40036023), - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 3, - Initiator: "hard", - Lot: sdk.NewInt64Coin("ukava", 47504818), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("ukava", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("ukava", 40040087), - LotReturns: lotReturns, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid: multiple stablecoin deposits, multiple variable coin borrows", - // Auctions: total lot value = $285 ($300 of deposits - $15 keeper reward), total max bid value = $270 - args{ - borrower: borrower, - keeper: keeper, - keeperRewardPercent: sdk.MustNewDecFromStr("0.05"), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(1000*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(1000*BTCB_CF))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("usdc", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("usdt", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(100*KAVA_CF))), - initialKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("usdc", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("usdt", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(100*KAVA_CF))), // $100 + $100 + $100 = $300 * 0.9 = $270 borrowable - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(35*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(10*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(1*BTCB_CF))), // $270 borrowed - liquidateAfter: oneMonthDur, - expectedTotalSuppliedCoins: sdk.NewCoins( - sdk.NewInt64Coin("bnb", 100000078047), - sdk.NewInt64Coin("btc", 100000000780), - sdk.NewInt64Coin("ukava", 1000009550), - sdk.NewInt64Coin("usdx", 1), - ), - expectedTotalBorrowedCoins: nil, - expectedKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("usdc", sdkmath.NewInt(5*KAVA_CF)), sdk.NewCoin("usdt", sdkmath.NewInt(5*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(5*KAVA_CF))), // 5% of each seized coin + initial balances - expectedBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(135*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(10*BNB_CF)), sdk.NewCoin("btc", sdkmath.NewInt(1*BTCB_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(0.000001*KAVA_CF))), - expectedAuctions: []auctiontypes.Auction{ - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 1, - Initiator: "hard", - Lot: sdk.NewInt64Coin("usdc", 95000000), // $95.00 - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("bnb", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("bnb", 900097134), // $90.00 - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 2, - Initiator: "hard", - Lot: sdk.NewInt64Coin("usdt", 10552835), // $10.55 - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("bnb", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("bnb", 99985020), // $10.00 - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 3, - Initiator: "hard", - Lot: sdk.NewInt64Coin("usdt", 84447165), // $84.45 - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("btc", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("btc", 80011211), // $80.01 - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 4, - Initiator: "hard", - Lot: sdk.NewInt64Coin("usdx", 21097866), // $21.10 - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("btc", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("btc", 19989610), // $19.99 - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 5, - Initiator: "hard", - Lot: sdk.NewInt64Coin("usdx", 73902133), //$73.90 - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("ukava", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("ukava", 35010052), // $70.02 - LotReturns: lotReturns, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid: multiple stablecoin deposits, multiple stablecoin borrows", - args{ - borrower: borrower, - keeper: keeper, - keeperRewardPercent: sdk.MustNewDecFromStr("0.05"), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdt", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("dai", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdc", sdkmath.NewInt(1000*KAVA_CF))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdt", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("dai", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdc", sdkmath.NewInt(1000*KAVA_CF))), - initialKeeperCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdt", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("dai", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdc", sdkmath.NewInt(1000*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("dai", sdkmath.NewInt(350*KAVA_CF)), sdk.NewCoin("usdc", sdkmath.NewInt(200*KAVA_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdt", sdkmath.NewInt(250*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(245*KAVA_CF))), - liquidateAfter: oneMonthDur, - expectedTotalSuppliedCoins: sdk.NewCoins( - sdk.NewInt64Coin("dai", 1000000000), - sdk.NewInt64Coin("usdc", 1000000001), - sdk.NewInt64Coin("usdt", 1000482503), - sdk.NewInt64Coin("usdx", 1000463500), - ), - expectedTotalBorrowedCoins: nil, - expectedKeeperCoins: sdk.NewCoins(sdk.NewCoin("dai", sdkmath.NewInt(1017.50*KAVA_CF)), sdk.NewCoin("usdt", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdc", sdkmath.NewInt(1010*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*KAVA_CF))), - expectedBorrowerCoins: sdk.NewCoins(sdk.NewCoin("dai", sdkmath.NewInt(650*KAVA_CF)), sdk.NewCoin("usdc", sdkmath.NewInt(800000001)), sdk.NewCoin("usdt", sdkmath.NewInt(1250*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1245*KAVA_CF))), - expectedAuctions: []auctiontypes.Auction{ - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 1, - Initiator: "hard", - Lot: sdk.NewInt64Coin("dai", 263894126), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("usdt", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("usdt", 250507897), - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 2, - Initiator: "hard", - Lot: sdk.NewInt64Coin("dai", 68605874), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("usdx", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("usdx", 65125788), - LotReturns: lotReturns, - }, - &auctiontypes.CollateralAuction{ - BaseAuction: auctiontypes.BaseAuction{ - ID: 3, - Initiator: "hard", - Lot: sdk.NewInt64Coin("usdc", 189999999), - Bidder: sdk.AccAddress(nil), - Bid: sdk.NewInt64Coin("usdx", 0), - HasReceivedBids: false, - EndTime: endTime, - MaxEndTime: endTime, - }, - CorrespondingDebt: sdk.NewInt64Coin("debt", 0), - MaxBid: sdk.NewInt64Coin("usdx", 180362106), - LotReturns: lotReturns, - }, - }, - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "invalid: borrow not liquidatable", - args{ - borrower: borrower, - keeper: keeper, - keeperRewardPercent: sdk.MustNewDecFromStr("0.05"), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20*KAVA_CF))), // Deposit 20 KAVA - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(5*KAVA_CF))), // Borrow 5 KAVA - liquidateAfter: oneMonthDur, - expectedTotalSuppliedCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(120001624))), - expectedTotalBorrowedCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(5001709))), - expectedKeeperCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100.5*KAVA_CF))), - expectedBorrowerCoins: sdk.NewCoins(), - expectedAuctions: []auctiontypes.Auction{}, - }, - errArgs{ - expectPass: false, - contains: "borrow not liquidatable", - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC)}) - - // account which will deposit "initial module account coins" - depositor := sdk.AccAddress(crypto.AddressHash([]byte("testdepositor"))) - - // Auth module genesis state - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{ - tc.args.initialBorrowerCoins, - tc.args.initialKeeperCoins, - tc.args.initialModuleCoins, - }, - []sdk.AccAddress{ - tc.args.borrower, - tc.args.keeper, - depositor, - }, - ) - - // Hard module genesis state - hardGS := types.NewGenesisState(types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("usdx", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.9")), // Borrow Limit - "usdx:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - model, // Interest Rate Model - reserveFactor, // Reserve Factor - tc.args.keeperRewardPercent), // Keeper Reward Percent - types.NewMoneyMarket("usdt", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.9")), // Borrow Limit - "usdt:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - model, // Interest Rate Model - reserveFactor, // Reserve Factor - tc.args.keeperRewardPercent), // Keeper Reward Percent - types.NewMoneyMarket("usdc", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.9")), // Borrow Limit - "usdc:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - model, // Interest Rate Model - reserveFactor, // Reserve Factor - tc.args.keeperRewardPercent), // Keeper Reward Percent - types.NewMoneyMarket("dai", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.9")), // Borrow Limit - "dai:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - model, // Interest Rate Model - reserveFactor, // Reserve Factor - tc.args.keeperRewardPercent), // Keeper Reward Percent - types.NewMoneyMarket("ukava", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "kava:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - model, // Interest Rate Model - reserveFactor, // Reserve Factor - tc.args.keeperRewardPercent), // Keeper Reward Percent - types.NewMoneyMarket("bnb", - types.NewBorrowLimit(false, sdk.NewDec(100000000*BNB_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "bnb:usd", // Market ID - sdkmath.NewInt(BNB_CF), // Conversion Factor - model, // Interest Rate Model - reserveFactor, // Reserve Factor - tc.args.keeperRewardPercent), // Keeper Reward Percent - types.NewMoneyMarket("btc", - types.NewBorrowLimit(false, sdk.NewDec(100000000*BTCB_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "btc:usd", // Market ID - sdkmath.NewInt(BTCB_CF), // Conversion Factor - model, // Interest Rate Model - reserveFactor, // Reserve Factor - tc.args.keeperRewardPercent), // Keeper Reward Percent - }, - sdk.NewDec(10), - ), types.DefaultAccumulationTimes, types.DefaultDeposits, types.DefaultBorrows, - types.DefaultTotalSupplied, types.DefaultTotalBorrowed, types.DefaultTotalReserves, - ) - - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "usdx:usd", BaseAsset: "usdx", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "usdt:usd", BaseAsset: "usdt", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "usdc:usd", BaseAsset: "usdc", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "dai:usd", BaseAsset: "dai", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "btc:usd", BaseAsset: "btc", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "usdx:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "usdt:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "usdc:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "dai:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("10.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "btc:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("100.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - }, - } - - // Initialize test application - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}) - - keeper := tApp.GetHardKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - suite.auctionKeeper = tApp.GetAuctionKeeper() - - var err error - - // Run begin blocker to set up state - hard.BeginBlocker(suite.ctx, suite.keeper) - - // Deposit initial module account coins - err = suite.keeper.Deposit(suite.ctx, depositor, tc.args.initialModuleCoins) - suite.Require().NoError(err) - - // Deposit coins - err = suite.keeper.Deposit(suite.ctx, tc.args.borrower, tc.args.depositCoins) - suite.Require().NoError(err) - - // Borrow coins - err = suite.keeper.Borrow(suite.ctx, tc.args.borrower, tc.args.borrowCoins) - suite.Require().NoError(err) - - // Set up liquidation chain context and run begin blocker - runAtTime := suite.ctx.BlockTime().Add(tc.args.liquidateAfter) - liqCtx := suite.ctx.WithBlockTime(runAtTime) - hard.BeginBlocker(liqCtx, suite.keeper) - - // Check borrow exists before liquidation - _, foundBorrowBefore := suite.keeper.GetBorrow(liqCtx, tc.args.borrower) - suite.Require().True(foundBorrowBefore) - // Check that the user's deposit exists before liquidation - _, foundDepositBefore := suite.keeper.GetDeposit(liqCtx, tc.args.borrower) - suite.Require().True(foundDepositBefore) - - // Fetch supplied and borrowed coins pre-liquidation - suppliedCoinsPre, foundSuppliedCoinsPre := suite.keeper.GetSuppliedCoins(liqCtx) - suite.Require().True(foundSuppliedCoinsPre) - borrowedCoinsPre, foundBorrowedCoinsPre := suite.keeper.GetBorrowedCoins(liqCtx) - suite.Require().True(foundBorrowedCoinsPre) - - // Attempt to liquidate - err = suite.keeper.AttemptKeeperLiquidation(liqCtx, tc.args.keeper, tc.args.borrower) - if tc.errArgs.expectPass { - suite.Require().NoError(err) - - // Check borrow does not exist after liquidation - _, foundBorrowAfter := suite.keeper.GetBorrow(liqCtx, tc.args.borrower) - suite.Require().False(foundBorrowAfter) - // Check deposits do not exist after liquidation - _, foundDepositAfter := suite.keeper.GetDeposit(liqCtx, tc.args.borrower) - suite.Require().False(foundDepositAfter) - - // Check that the keeper's balance increased by reward % of all the borrowed coins - accKeeper := suite.getAccountAtCtx(tc.args.keeper, liqCtx) - suite.Require().Equal(tc.args.expectedKeeperCoins, suite.getAccountCoins(accKeeper)) - - // Check that borrower's balance contains the expected coins - accBorrower := suite.getAccountAtCtx(tc.args.borrower, liqCtx) - suite.Require().Equal(tc.args.expectedBorrowerCoins, suite.getAccountCoins(accBorrower)) - - // Check that the expected auctions have been created - auctions := suite.auctionKeeper.GetAllAuctions(liqCtx) - suite.Require().Equal(tc.args.expectedAuctions, auctions) - - // Check that supplied and borrowed coins have been updated post-liquidation - suppliedCoinsPost, _ := suite.keeper.GetSuppliedCoins(liqCtx) - suite.Require().Equal(tc.args.expectedTotalSuppliedCoins, suppliedCoinsPost) - borrowedCoinsPost, _ := suite.keeper.GetBorrowedCoins(liqCtx) - suite.Require().True(tc.args.expectedTotalBorrowedCoins.IsEqual(borrowedCoinsPost)) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - - // Check that the user's borrow exists - _, foundBorrowAfter := suite.keeper.GetBorrow(liqCtx, tc.args.borrower) - suite.Require().True(foundBorrowAfter) - // Check that the user's deposits exist - _, foundDepositAfter := suite.keeper.GetDeposit(liqCtx, tc.args.borrower) - suite.Require().True(foundDepositAfter) - - // Check that no auctions have been created - auctions := suite.auctionKeeper.GetAllAuctions(liqCtx) - suite.Require().True(len(auctions) == 0) - - // Check that supplied and borrowed coins have not been updated post-liquidation - suite.Require().Equal(tc.args.expectedTotalSuppliedCoins, suppliedCoinsPre) - suite.Require().True(tc.args.expectedTotalBorrowedCoins.IsEqual(borrowedCoinsPre)) - } - }) - } -} diff --git a/x/hard/keeper/msg_server.go b/x/hard/keeper/msg_server.go deleted file mode 100644 index 65c07970..00000000 --- a/x/hard/keeper/msg_server.go +++ /dev/null @@ -1,146 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/hard/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the hard MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -func (k msgServer) Deposit(goCtx context.Context, msg *types.MsgDeposit) (*types.MsgDepositResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - - err = k.keeper.Deposit(ctx, depositor, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Depositor), - ), - ) - return &types.MsgDepositResponse{}, nil -} - -func (k msgServer) Withdraw(goCtx context.Context, msg *types.MsgWithdraw) (*types.MsgWithdrawResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - - err = k.keeper.Withdraw(ctx, depositor, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Depositor), - ), - ) - return &types.MsgWithdrawResponse{}, nil -} - -func (k msgServer) Borrow(goCtx context.Context, msg *types.MsgBorrow) (*types.MsgBorrowResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - borrower, err := sdk.AccAddressFromBech32(msg.Borrower) - if err != nil { - return nil, err - } - - err = k.keeper.Borrow(ctx, borrower, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Borrower), - ), - ) - return &types.MsgBorrowResponse{}, nil -} - -func (k msgServer) Repay(goCtx context.Context, msg *types.MsgRepay) (*types.MsgRepayResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - owner, err := sdk.AccAddressFromBech32(msg.Owner) - if err != nil { - return nil, err - } - - err = k.keeper.Repay(ctx, sender, owner, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - ), - ) - return &types.MsgRepayResponse{}, nil -} - -func (k msgServer) Liquidate(goCtx context.Context, msg *types.MsgLiquidate) (*types.MsgLiquidateResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - keeper, err := sdk.AccAddressFromBech32(msg.Keeper) - if err != nil { - return nil, err - } - - borrower, err := sdk.AccAddressFromBech32(msg.Borrower) - if err != nil { - return nil, err - } - - err = k.keeper.AttemptKeeperLiquidation(ctx, keeper, borrower) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Keeper), - ), - ) - return &types.MsgLiquidateResponse{}, nil -} diff --git a/x/hard/keeper/params.go b/x/hard/keeper/params.go deleted file mode 100644 index bcf0eddb..00000000 --- a/x/hard/keeper/params.go +++ /dev/null @@ -1,25 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/hard/types" -) - -// GetParams returns the params from the store -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - var p types.Params - k.paramSubspace.GetParamSet(ctx, &p) - return p -} - -// SetParams sets params on the store -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSubspace.SetParamSet(ctx, ¶ms) -} - -// GetMinimumBorrowUSDValue returns the minimum borrow USD value -func (k Keeper) GetMinimumBorrowUSDValue(ctx sdk.Context) sdk.Dec { - params := k.GetParams(ctx) - return params.MinimumBorrowUSDValue -} diff --git a/x/hard/keeper/repay.go b/x/hard/keeper/repay.go deleted file mode 100644 index 50ab5ae9..00000000 --- a/x/hard/keeper/repay.go +++ /dev/null @@ -1,170 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/hard/types" -) - -// Repay borrowed funds -func (k Keeper) Repay(ctx sdk.Context, sender, owner sdk.AccAddress, coins sdk.Coins) error { - // Check borrow exists here to avoid duplicating store read in ValidateRepay - borrow, found := k.GetBorrow(ctx, owner) - if !found { - return types.ErrBorrowNotFound - } - // Call incentive hook - k.BeforeBorrowModified(ctx, borrow) - - // Sync borrow interest so loan is up-to-date - k.SyncBorrowInterest(ctx, owner) - - // Refresh borrow after syncing interest - borrow, _ = k.GetBorrow(ctx, owner) - - // cap the repayment by what's available to repay (the borrow amount) - payment, err := k.CalculatePaymentAmount(borrow.Amount, coins) - if err != nil { - return err - } - // Validate that sender holds coins for repayment - err = k.ValidateRepay(ctx, sender, owner, payment) - if err != nil { - return err - } - - // Sends coins from user to Hard module account - err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleAccountName, payment) - if err != nil { - return err - } - - // If any coin denoms have been completely repaid reset the denom's borrow index factor - for _, coin := range payment { - if coin.Amount.Equal(borrow.Amount.AmountOf(coin.Denom)) { - borrowIndex, removed := borrow.Index.RemoveInterestFactor(coin.Denom) - if !removed { - return errorsmod.Wrapf(types.ErrInvalidIndexFactorDenom, "%s", coin.Denom) - } - borrow.Index = borrowIndex - } - } - - // Update user's borrow in store - borrow.Amount = borrow.Amount.Sub(payment...) - - if borrow.Amount.Empty() { - k.DeleteBorrow(ctx, borrow) - } else { - k.SetBorrow(ctx, borrow) - } - - // Update total borrowed amount - err = k.DecrementBorrowedCoins(ctx, payment) - if err != nil { - return err - } - - // Call incentive hook - k.AfterBorrowModified(ctx, borrow) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeHardRepay, - sdk.NewAttribute(types.AttributeKeySender, sender.String()), - sdk.NewAttribute(types.AttributeKeyOwner, owner.String()), - sdk.NewAttribute(types.AttributeKeyRepayCoins, payment.String()), - ), - ) - - return nil -} - -// ValidateRepay validates a requested loan repay -func (k Keeper) ValidateRepay(ctx sdk.Context, sender, owner sdk.AccAddress, coins sdk.Coins) error { - assetPriceCache := map[string]sdk.Dec{} - - // Get the total USD value of user's existing borrows - existingBorrowUSDValue := sdk.ZeroDec() - existingBorrow, found := k.GetBorrow(ctx, owner) - if found { - for _, coin := range existingBorrow.Amount { - moneyMarket, found := k.GetMoneyMarket(ctx, coin.Denom) - if !found { - return errorsmod.Wrapf(types.ErrMarketNotFound, "no money market found for denom %s", coin.Denom) - } - - assetPrice, ok := assetPriceCache[coin.Denom] - if !ok { // Fetch current asset price and store in local cache - assetPriceInfo, err := k.pricefeedKeeper.GetCurrentPrice(ctx, moneyMarket.SpotMarketID) - if err != nil { - return errorsmod.Wrapf(types.ErrPriceNotFound, "no price found for market %s", moneyMarket.SpotMarketID) - } - assetPriceCache[coin.Denom] = assetPriceInfo.Price - assetPrice = assetPriceInfo.Price - } - - // Calculate this borrow coin's USD value and add it to the total previous borrowed USD value - coinUSDValue := sdk.NewDecFromInt(coin.Amount).Quo(sdk.NewDecFromInt(moneyMarket.ConversionFactor)).Mul(assetPrice) - existingBorrowUSDValue = existingBorrowUSDValue.Add(coinUSDValue) - } - } - - senderCoins := k.bankKeeper.SpendableCoins(ctx, sender) - repayTotalUSDValue := sdk.ZeroDec() - for _, repayCoin := range coins { - // Check that sender holds enough tokens to make the proposed payment - if senderCoins.AmountOf(repayCoin.Denom).LT(repayCoin.Amount) { - return errorsmod.Wrapf(types.ErrInsufficientBalanceForRepay, "account can only repay up to %s%s", senderCoins.AmountOf(repayCoin.Denom), repayCoin.Denom) - } - - moneyMarket, found := k.GetMoneyMarket(ctx, repayCoin.Denom) - if !found { - return errorsmod.Wrapf(types.ErrMarketNotFound, "no money market found for denom %s", repayCoin.Denom) - } - - // Calculate this coin's USD value and add it to the repay's total USD value - assetPrice, ok := assetPriceCache[repayCoin.Denom] - if !ok { // Fetch current asset price and store in local cache - assetPriceInfo, err := k.pricefeedKeeper.GetCurrentPrice(ctx, moneyMarket.SpotMarketID) - if err != nil { - return errorsmod.Wrapf(types.ErrPriceNotFound, "no price found for market %s", moneyMarket.SpotMarketID) - } - assetPriceCache[repayCoin.Denom] = assetPriceInfo.Price - assetPrice = assetPriceInfo.Price - } - coinUSDValue := sdk.NewDecFromInt(repayCoin.Amount).Quo(sdk.NewDecFromInt(moneyMarket.ConversionFactor)).Mul(assetPrice) - repayTotalUSDValue = repayTotalUSDValue.Add(coinUSDValue) - } - - // If the proposed repayment would results in a borrowed USD value below the minimum borrow USD value, reject it. - // User can overpay their loan to close it out, but underpaying by such a margin that the USD value is in an - // invalid range is not allowed - // Unless the user is fully repaying their loan - proposedBorrowNewUSDValue := existingBorrowUSDValue.Sub(repayTotalUSDValue) - isFullRepayment := coins.IsEqual(existingBorrow.Amount) - if proposedBorrowNewUSDValue.LT(k.GetMinimumBorrowUSDValue(ctx)) && !isFullRepayment { - return errorsmod.Wrapf(types.ErrBelowMinimumBorrowValue, "the proposed borrow's USD value $%s is below the minimum borrow limit $%s", proposedBorrowNewUSDValue, k.GetMinimumBorrowUSDValue(ctx)) - } - - return nil -} - -// CalculatePaymentAmount prevents overpayment when repaying borrowed coins -func (k Keeper) CalculatePaymentAmount(owed sdk.Coins, payment sdk.Coins) (sdk.Coins, error) { - repayment := sdk.Coins{} - - if !payment.DenomsSubsetOf(owed) { - return repayment, types.ErrInvalidRepaymentDenom - } - - for _, coin := range payment { - if coin.Amount.GT(owed.AmountOf(coin.Denom)) { - repayment = append(repayment, sdk.NewCoin(coin.Denom, owed.AmountOf(coin.Denom))) - } else { - repayment = append(repayment, coin) - } - } - return repayment, nil -} diff --git a/x/hard/keeper/repay_test.go b/x/hard/keeper/repay_test.go deleted file mode 100644 index aeae916a..00000000 --- a/x/hard/keeper/repay_test.go +++ /dev/null @@ -1,366 +0,0 @@ -package keeper_test - -import ( - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/hard" - "github.com/0glabs/0g-chain/x/hard/types" - pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" -) - -func (suite *KeeperTestSuite) TestRepay() { - type args struct { - borrower sdk.AccAddress - repayer sdk.AccAddress - initialBorrowerCoins sdk.Coins - initialRepayerCoins sdk.Coins - initialModuleCoins sdk.Coins - depositCoins []sdk.Coin - borrowCoins sdk.Coins - repayCoins sdk.Coins - } - - type errArgs struct { - expectPass bool - expectDelete bool - contains string - } - - type borrowTest struct { - name string - args args - errArgs errArgs - } - - model := types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")) - - testCases := []borrowTest{ - { - "valid: partial repay", - args{ - borrower: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - repayer: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialRepayerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*USDX_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - repayCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10*KAVA_CF))), - }, - errArgs{ - expectPass: true, - expectDelete: false, - contains: "", - }, - }, - { - "valid: partial repay by non borrower", - args{ - borrower: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - repayer: sdk.AccAddress(crypto.AddressHash([]byte("repayer"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialRepayerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*USDX_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - repayCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10*KAVA_CF))), - }, - errArgs{ - expectPass: true, - expectDelete: false, - contains: "", - }, - }, - { - "valid: repay in full", - args{ - borrower: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - repayer: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialRepayerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*USDX_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - repayCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - }, - errArgs{ - expectPass: true, - expectDelete: true, - contains: "", - }, - }, - { - "valid: overpayment is adjusted", - args{ - borrower: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - repayer: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialRepayerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*USDX_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(80*KAVA_CF))), // Deposit less so user still has some KAVA - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - repayCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(60*KAVA_CF))), // Exceeds borrowed coins but not user's balance - }, - errArgs{ - expectPass: true, - expectDelete: true, - contains: "", - }, - }, - { - "invalid: attempt to repay non-supplied coin", - args{ - borrower: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - repayer: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialRepayerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*USDX_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - repayCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10*KAVA_CF)), sdk.NewCoin("bnb", sdkmath.NewInt(10*KAVA_CF))), - }, - errArgs{ - expectPass: false, - expectDelete: false, - contains: "no coins of this type borrowed", - }, - }, - { - "invalid: insufficient balance for repay", - args{ - borrower: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - repayer: sdk.AccAddress(crypto.AddressHash([]byte("repayer"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialRepayerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(49*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*USDX_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), - repayCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(50*KAVA_CF))), // Exceeds repayer's balance, but not borrow amount - }, - errArgs{ - expectPass: false, - expectDelete: false, - contains: "account can only repay up to 49000000ukava", - }, - }, - { - "invalid: repaying a single coin type results in borrow position below the minimum USD value", - args{ - borrower: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - repayer: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF))), - initialRepayerCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*USDX_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(50*USDX_CF))), - repayCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(45*USDX_CF))), - }, - errArgs{ - expectPass: false, - expectDelete: false, - contains: "proposed borrow's USD value $5.000000000000000000 is below the minimum borrow limit", - }, - }, - { - "invalid: repaying multiple coin types results in borrow position below the minimum USD value", - args{ - borrower: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - repayer: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF))), - initialRepayerCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*USDX_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(50*USDX_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(10*KAVA_CF))), // (50*$1)+(10*$2) = $70 - repayCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(45*USDX_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(8*KAVA_CF))), // (45*$1)+(8*$2) = $61 - }, - errArgs{ - expectPass: false, - expectDelete: false, - contains: "proposed borrow's USD value $9.000000000000000000 is below the minimum borrow limit", - }, - }, - { - "invalid: overpaying multiple coin types results in borrow position below the minimum USD value", - args{ - borrower: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - repayer: sdk.AccAddress(crypto.AddressHash([]byte("borrower"))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF))), - initialRepayerCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(1000*USDX_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100*USDX_CF))), - borrowCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(50*USDX_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(10*KAVA_CF))), // (50*$1)+(10*$2) = $70 - repayCoins: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(500*USDX_CF)), sdk.NewCoin("ukava", sdkmath.NewInt(8*KAVA_CF))), // (500*$1)+(8*$2) = $516, or capping to borrowed amount, (50*$1)+(8*$2) = $66 - }, - errArgs{ - expectPass: false, - expectDelete: false, - contains: "proposed borrow's USD value $4.000000000000000000 is below the minimum borrow limit", - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - // Auth module genesis state - addrs, coinses := uniqueAddressCoins( - []sdk.AccAddress{tc.args.borrower, tc.args.repayer}, - []sdk.Coins{tc.args.initialBorrowerCoins, tc.args.initialRepayerCoins}, - ) - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - coinses, - addrs, - ) - - // Hard module genesis state - hardGS := types.NewGenesisState(types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("usdx", - types.NewBorrowLimit(false, sdk.NewDec(100000000*USDX_CF), sdk.MustNewDecFromStr("1")), // Borrow Limit - "usdx:usd", // Market ID - sdkmath.NewInt(USDX_CF), // Conversion Factor - model, // Interest Rate Model - sdk.MustNewDecFromStr("0.05"), // Reserve Factor - sdk.MustNewDecFromStr("0.05")), // Keeper Reward Percent - types.NewMoneyMarket("ukava", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "kava:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - model, // Interest Rate Model - sdk.MustNewDecFromStr("0.05"), // Reserve Factor - sdk.MustNewDecFromStr("0.05")), // Keeper Reward Percent - }, - sdk.NewDec(10), - ), types.DefaultAccumulationTimes, types.DefaultDeposits, types.DefaultBorrows, - types.DefaultTotalSupplied, types.DefaultTotalBorrowed, types.DefaultTotalReserves, - ) - - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "usdx:usd", BaseAsset: "usdx", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "usdx:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(1 * time.Hour), - }, - }, - } - - // Initialize test application - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}, - ) - - // Mint coins to Hard module account - bankKeeper := tApp.GetBankKeeper() - err := bankKeeper.MintCoins(ctx, types.ModuleAccountName, tc.args.initialModuleCoins) - suite.Require().NoError(err) - - suite.app = tApp - suite.ctx = ctx - suite.keeper = tApp.GetHardKeeper() - - // Run BeginBlocker once to transition MoneyMarkets - hard.BeginBlocker(suite.ctx, suite.keeper) - - // Deposit coins to hard - err = suite.keeper.Deposit(suite.ctx, tc.args.borrower, tc.args.depositCoins) - suite.Require().NoError(err) - - // Borrow coins from hard - err = suite.keeper.Borrow(suite.ctx, tc.args.borrower, tc.args.borrowCoins) - suite.Require().NoError(err) - - repayerAcc := suite.getAccount(tc.args.repayer) - previousRepayerCoins := bankKeeper.GetAllBalances(suite.ctx, repayerAcc.GetAddress()) - - err = suite.keeper.Repay(suite.ctx, tc.args.repayer, tc.args.borrower, tc.args.repayCoins) - if tc.errArgs.expectPass { - suite.Require().NoError(err) - // If we overpaid expect an adjustment - repaymentCoins, err := suite.keeper.CalculatePaymentAmount(tc.args.borrowCoins, tc.args.repayCoins) - suite.Require().NoError(err) - - // Check repayer balance - expectedRepayerCoins := previousRepayerCoins.Sub(repaymentCoins...) - acc := suite.getAccount(tc.args.repayer) - // use IsEqual for sdk.Coins{nil} vs sdk.Coins{} - suite.Require().True(expectedRepayerCoins.IsEqual(bankKeeper.GetAllBalances(suite.ctx, acc.GetAddress()))) - - // Check module account balance - expectedModuleCoins := tc.args.initialModuleCoins.Add(tc.args.depositCoins...).Sub(tc.args.borrowCoins...).Add(repaymentCoins...) - mAcc := suite.getModuleAccount(types.ModuleAccountName) - suite.Require().Equal(expectedModuleCoins, bankKeeper.GetAllBalances(suite.ctx, mAcc.GetAddress())) - - // Check user's borrow object - borrow, foundBorrow := suite.keeper.GetBorrow(suite.ctx, tc.args.borrower) - expectedBorrowCoins := tc.args.borrowCoins.Sub(repaymentCoins...) - - if tc.errArgs.expectDelete { - suite.Require().False(foundBorrow) - } else { - suite.Require().True(foundBorrow) - suite.Require().Equal(expectedBorrowCoins, borrow.Amount) - } - } else { - suite.Require().Error(err) - suite.Require().Contains(err.Error(), tc.errArgs.contains) - - // Check repayer balance (no repay coins) - acc := suite.getAccount(tc.args.repayer) - suite.Require().Equal(previousRepayerCoins, bankKeeper.GetAllBalances(suite.ctx, acc.GetAddress())) - - // Check module account balance (no repay coins) - expectedModuleCoins := tc.args.initialModuleCoins.Add(tc.args.depositCoins...).Sub(tc.args.borrowCoins...) - mAcc := suite.getModuleAccount(types.ModuleAccountName) - suite.Require().Equal(expectedModuleCoins, bankKeeper.GetAllBalances(suite.ctx, mAcc.GetAddress())) - - // Check user's borrow object (no repay coins) - borrow, foundBorrow := suite.keeper.GetBorrow(suite.ctx, tc.args.borrower) - suite.Require().True(foundBorrow) - suite.Require().Equal(tc.args.borrowCoins, borrow.Amount) - } - }) - } -} - -// uniqueAddressCoins removes duplicate addresses, and the corresponding elements in a list of coins. -func uniqueAddressCoins(addresses []sdk.AccAddress, coinses []sdk.Coins) ([]sdk.AccAddress, []sdk.Coins) { - uniqueAddresses := []sdk.AccAddress{} - filteredCoins := []sdk.Coins{} - - addrMap := map[string]bool{} - for i, a := range addresses { - if !addrMap[a.String()] { - uniqueAddresses = append(uniqueAddresses, a) - filteredCoins = append(filteredCoins, coinses[i]) - } - addrMap[a.String()] = true - } - return uniqueAddresses, filteredCoins -} diff --git a/x/hard/keeper/withdraw.go b/x/hard/keeper/withdraw.go deleted file mode 100644 index 46b9b411..00000000 --- a/x/hard/keeper/withdraw.go +++ /dev/null @@ -1,109 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/hard/types" -) - -// Withdraw returns some or all of a deposit back to original depositor -func (k Keeper) Withdraw(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error { - // Call incentive hooks - existingDeposit, found := k.GetDeposit(ctx, depositor) - if !found { - return errorsmod.Wrapf(types.ErrDepositNotFound, "no deposit found for %s", depositor) - } - k.BeforeDepositModified(ctx, existingDeposit) - - existingBorrow, hasExistingBorrow := k.GetBorrow(ctx, depositor) - if hasExistingBorrow { - k.BeforeBorrowModified(ctx, existingBorrow) - } - - // Sync interest - k.SyncBorrowInterest(ctx, depositor) - k.SyncSupplyInterest(ctx, depositor) - - // Refresh Deposit after syncing interest - deposit, _ := k.GetDeposit(ctx, depositor) - - amount, err := k.CalculateWithdrawAmount(deposit.Amount, coins) - if err != nil { - return err - } - - borrow, found := k.GetBorrow(ctx, depositor) - if !found { - borrow = types.Borrow{} - } - - proposedDeposit := types.NewDeposit(deposit.Depositor, deposit.Amount.Sub(amount...), types.SupplyInterestFactors{}) - valid, err := k.IsWithinValidLtvRange(ctx, proposedDeposit, borrow) - if err != nil { - return err - } - if !valid { - return errorsmod.Wrapf(types.ErrInvalidWithdrawAmount, "proposed withdraw outside loan-to-value range") - } - - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, depositor, amount) - if err != nil { - return err - } - - // If any coin denoms have been completely withdrawn reset the denom's supply index factor - for _, coin := range deposit.Amount { - if !sdk.NewCoins(coin).DenomsSubsetOf(proposedDeposit.Amount) { - depositIndex, removed := deposit.Index.RemoveInterestFactor(coin.Denom) - if !removed { - return errorsmod.Wrapf(types.ErrInvalidIndexFactorDenom, "%s", coin.Denom) - } - deposit.Index = depositIndex - } - } - - deposit.Amount = deposit.Amount.Sub(amount...) - if deposit.Amount.Empty() { - k.DeleteDeposit(ctx, deposit) - } else { - k.SetDeposit(ctx, deposit) - } - - // Update total supplied amount - err = k.DecrementSuppliedCoins(ctx, amount) - if err != nil { - return err - } - - // Call incentive hook - k.AfterDepositModified(ctx, deposit) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeHardWithdrawal, - sdk.NewAttribute(sdk.AttributeKeyAmount, amount.String()), - sdk.NewAttribute(types.AttributeKeyDepositor, depositor.String()), - ), - ) - return nil -} - -// CalculateWithdrawAmount enables full withdraw of deposited coins by adjusting withdraw amount -// to equal total deposit amount if the requested withdraw amount > current deposit amount -func (k Keeper) CalculateWithdrawAmount(available sdk.Coins, request sdk.Coins) (sdk.Coins, error) { - result := sdk.Coins{} - - if !request.DenomsSubsetOf(available) { - return result, types.ErrInvalidWithdrawDenom - } - - for _, coin := range request { - if coin.Amount.GT(available.AmountOf(coin.Denom)) { - result = append(result, sdk.NewCoin(coin.Denom, available.AmountOf(coin.Denom))) - } else { - result = append(result, coin) - } - } - return result, nil -} diff --git a/x/hard/keeper/withdraw_test.go b/x/hard/keeper/withdraw_test.go deleted file mode 100644 index 9c860357..00000000 --- a/x/hard/keeper/withdraw_test.go +++ /dev/null @@ -1,380 +0,0 @@ -package keeper_test - -import ( - "strings" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/hard" - "github.com/0glabs/0g-chain/x/hard/types" - pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" -) - -func (suite *KeeperTestSuite) TestWithdraw() { - type args struct { - depositor sdk.AccAddress - initialModAccountBalance sdk.Coins - depositAmount sdk.Coins - withdrawAmount sdk.Coins - createDeposit bool - expectedAccountBalance sdk.Coins - expectedModAccountBalance sdk.Coins - finalDepositAmount sdk.Coins - } - type errArgs struct { - expectPass bool - expectDelete bool - contains string - } - type withdrawTest struct { - name string - args args - errArgs errArgs - } - testCases := []withdrawTest{ - { - "valid: partial withdraw", - args{ - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialModAccountBalance: sdk.Coins(nil), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - withdrawAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - createDeposit: true, - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(900)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - finalDepositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - }, - errArgs{ - expectPass: true, - expectDelete: false, - contains: "", - }, - }, - { - "valid: full withdraw", - args{ - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialModAccountBalance: sdk.Coins(nil), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - withdrawAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - createDeposit: true, - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.Coins(nil), - finalDepositAmount: sdk.Coins{}, - }, - errArgs{ - expectPass: true, - expectDelete: true, - contains: "", - }, - }, - { - "valid: withdraw exceeds deposit but is adjusted to match max deposit", - args{ - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialModAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - withdrawAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(300))), - createDeposit: true, - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000))), - finalDepositAmount: sdk.Coins{}, - }, - errArgs{ - expectPass: true, - expectDelete: true, - contains: "", - }, - }, - { - "invalid: withdraw non-supplied coin type", - args{ - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialModAccountBalance: sdk.Coins(nil), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - withdrawAmount: sdk.NewCoins(sdk.NewCoin("btcb", sdkmath.NewInt(200))), - createDeposit: true, - expectedAccountBalance: sdk.Coins{}, - expectedModAccountBalance: sdk.Coins{}, - finalDepositAmount: sdk.Coins{}, - }, - errArgs{ - expectPass: false, - expectDelete: false, - contains: "no coins of this type deposited", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - // create new app with one funded account - - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{sdk.NewCoins( - sdk.NewCoin("bnb", sdkmath.NewInt(1000)), - sdk.NewCoin("btcb", sdkmath.NewInt(1000)), - )}, - []sdk.AccAddress{tc.args.depositor}, - ) - - loanToValue := sdk.MustNewDecFromStr("0.6") - hardGS := types.NewGenesisState(types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("usdx", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "usdx:usd", sdkmath.NewInt(1000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("ukava", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "kava:usd", sdkmath.NewInt(1000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - types.NewMoneyMarket("bnb", types.NewBorrowLimit(false, sdk.NewDec(1000000000000000), loanToValue), "bnb:usd", sdkmath.NewInt(100000000), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - }, - sdk.NewDec(10), - ), types.DefaultAccumulationTimes, types.DefaultDeposits, types.DefaultBorrows, - types.DefaultTotalSupplied, types.DefaultTotalBorrowed, types.DefaultTotalReserves, - ) - - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "usdx:usd", BaseAsset: "usdx", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "usdx:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("10.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - }, - } - - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&hardGS)}) - keeper := tApp.GetHardKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - - // Mint coins to Hard module account - bankKeeper := tApp.GetBankKeeper() - err := bankKeeper.MintCoins(ctx, types.ModuleAccountName, tc.args.initialModAccountBalance) - suite.Require().NoError(err) - - if tc.args.createDeposit { - err := suite.keeper.Deposit(suite.ctx, tc.args.depositor, tc.args.depositAmount) - suite.Require().NoError(err) - } - - err = suite.keeper.Withdraw(suite.ctx, tc.args.depositor, tc.args.withdrawAmount) - - if tc.errArgs.expectPass { - suite.Require().NoError(err) - acc := suite.getAccount(tc.args.depositor) - suite.Require().Equal(tc.args.expectedAccountBalance, bankKeeper.GetAllBalances(ctx, acc.GetAddress())) - mAcc := suite.getModuleAccount(types.ModuleAccountName) - suite.Require().True(tc.args.expectedModAccountBalance.IsEqual(bankKeeper.GetAllBalances(ctx, mAcc.GetAddress()))) - testDeposit, f := suite.keeper.GetDeposit(suite.ctx, tc.args.depositor) - if tc.errArgs.expectDelete { - suite.Require().False(f) - } else { - suite.Require().True(f) - suite.Require().Equal(tc.args.finalDepositAmount, testDeposit.Amount) - } - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func (suite *KeeperTestSuite) TestLtvWithdraw() { - type args struct { - borrower sdk.AccAddress - initialModuleCoins sdk.Coins - initialBorrowerCoins sdk.Coins - depositCoins sdk.Coins - borrowCoins sdk.Coins - repayCoins sdk.Coins - futureTime int64 - } - - type errArgs struct { - expectPass bool - contains string - } - - type liqTest struct { - name string - args args - errArgs errArgs - } - - // Set up test constants - model := types.NewInterestRateModel(sdk.MustNewDecFromStr("0"), sdk.MustNewDecFromStr("0.1"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("0.5")) - reserveFactor := sdk.MustNewDecFromStr("0.05") - oneMonthInSeconds := int64(2592000) - borrower := sdk.AccAddress(crypto.AddressHash([]byte("testborrower"))) - - testCases := []liqTest{ - { - "invalid: withdraw is outside loan-to-value range", - args{ - borrower: borrower, - initialModuleCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), - initialBorrowerCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF)), sdk.NewCoin("usdx", sdkmath.NewInt(100*KAVA_CF))), - depositCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100*KAVA_CF))), // 100 * 2 = $200 - borrowCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(80*KAVA_CF))), // 80 * 2 = $160 - repayCoins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(60*KAVA_CF))), // 60 * 2 = $120 - futureTime: oneMonthInSeconds, - }, - errArgs{ - expectPass: false, - contains: "proposed withdraw outside loan-to-value range", - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - // Auth module genesis state - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{tc.args.initialBorrowerCoins}, - []sdk.AccAddress{tc.args.borrower}, - ) - - // Harvest module genesis state - harvestGS := types.NewGenesisState(types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("ukava", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "kava:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - model, // Interest Rate Model - reserveFactor, // Reserve Factor - sdk.MustNewDecFromStr("0.05")), // Keeper Reward Percent - types.NewMoneyMarket("usdx", - types.NewBorrowLimit(false, sdk.NewDec(100000000*KAVA_CF), sdk.MustNewDecFromStr("0.8")), // Borrow Limit - "usdx:usd", // Market ID - sdkmath.NewInt(KAVA_CF), // Conversion Factor - model, // Interest Rate Model - reserveFactor, // Reserve Factor - sdk.MustNewDecFromStr("0.05")), // Keeper Reward Percent - }, - sdk.NewDec(10), - ), types.DefaultAccumulationTimes, types.DefaultDeposits, types.DefaultBorrows, - types.DefaultTotalSupplied, types.DefaultTotalBorrowed, types.DefaultTotalReserves, - ) - - // Pricefeed module genesis state - pricefeedGS := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "usdx:usd", BaseAsset: "usdx", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "usdx:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("1.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: time.Now().Add(100 * time.Hour), - }, - }, - } - - // Initialize test application - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{pricefeedtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(&pricefeedGS)}, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&harvestGS)}) - - // Mint coins to Harvest module account - bankKeeper := tApp.GetBankKeeper() - err := bankKeeper.MintCoins(ctx, types.ModuleAccountName, tc.args.initialModuleCoins) - suite.Require().NoError(err) - - auctionKeeper := tApp.GetAuctionKeeper() - - keeper := tApp.GetHardKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - suite.auctionKeeper = auctionKeeper - - // Run begin blocker to set up state - hard.BeginBlocker(suite.ctx, suite.keeper) - - // Borrower deposits coins - err = suite.keeper.Deposit(suite.ctx, tc.args.borrower, tc.args.depositCoins) - suite.Require().NoError(err) - - // Borrower borrows coins - err = suite.keeper.Borrow(suite.ctx, tc.args.borrower, tc.args.borrowCoins) - suite.Require().NoError(err) - - // Attempting to withdraw fails - err = suite.keeper.Withdraw(suite.ctx, tc.args.borrower, sdk.NewCoins(sdk.NewCoin("ukava", sdk.OneInt()))) - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - - // Set up future chain context and run begin blocker, increasing user's owed borrow balance - runAtTime := time.Unix(suite.ctx.BlockTime().Unix()+(tc.args.futureTime), 0) - liqCtx := suite.ctx.WithBlockTime(runAtTime) - hard.BeginBlocker(liqCtx, suite.keeper) - - // Attempted withdraw of 1 coin still fails - err = suite.keeper.Withdraw(suite.ctx, tc.args.borrower, sdk.NewCoins(sdk.NewCoin("ukava", sdk.OneInt()))) - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - - // Repay the initial principal. Over pay the position so the borrow is closed. - err = suite.keeper.Repay(suite.ctx, tc.args.borrower, tc.args.borrower, tc.args.repayCoins) - suite.Require().NoError(err) - - // Attempted withdraw of all deposited coins fails as user hasn't repaid interest debt - err = suite.keeper.Withdraw(suite.ctx, tc.args.borrower, tc.args.depositCoins) - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - - // Withdrawing 10% of the coins should succeed - withdrawCoins := sdk.NewCoins(sdk.NewCoin("ukava", tc.args.depositCoins[0].Amount.Quo(sdkmath.NewInt(10)))) - err = suite.keeper.Withdraw(suite.ctx, tc.args.borrower, withdrawCoins) - suite.Require().NoError(err) - }) - } -} diff --git a/x/hard/legacy/v0_15/types.go b/x/hard/legacy/v0_15/types.go deleted file mode 100644 index bfdfd85d..00000000 --- a/x/hard/legacy/v0_15/types.go +++ /dev/null @@ -1,108 +0,0 @@ -package v0_15 - -import ( - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // ModuleName name that will be used throughout the module - ModuleName = "hard" -) - -// GenesisState is the state that must be provided at genesis. -type GenesisState struct { - Params Params `json:"params" yaml:"params"` - PreviousAccumulationTimes GenesisAccumulationTimes `json:"previous_accumulation_times" yaml:"previous_accumulation_times"` - Deposits Deposits `json:"deposits" yaml:"deposits"` - Borrows Borrows `json:"borrows" yaml:"borrows"` - TotalSupplied sdk.Coins `json:"total_supplied" yaml:"total_supplied"` - TotalBorrowed sdk.Coins `json:"total_borrowed" yaml:"total_borrowed"` - TotalReserves sdk.Coins `json:"total_reserves" yaml:"total_reserves"` -} - -// Params governance parameters for hard module -type Params struct { - MoneyMarkets MoneyMarkets `json:"money_markets" yaml:"money_markets"` - MinimumBorrowUSDValue sdk.Dec `json:"minimum_borrow_usd_value" yaml:"minimum_borrow_usd_value"` -} - -// MoneyMarkets slice of MoneyMarket -type MoneyMarkets []MoneyMarket - -// MoneyMarket is a money market for an individual asset -type MoneyMarket struct { - Denom string `json:"denom" yaml:"denom"` - BorrowLimit BorrowLimit `json:"borrow_limit" yaml:"borrow_limit"` - SpotMarketID string `json:"spot_market_id" yaml:"spot_market_id"` - ConversionFactor sdkmath.Int `json:"conversion_factor" yaml:"conversion_factor"` - InterestRateModel InterestRateModel `json:"interest_rate_model" yaml:"interest_rate_model"` - ReserveFactor sdk.Dec `json:"reserve_factor" yaml:"reserve_factor"` - KeeperRewardPercentage sdk.Dec `json:"keeper_reward_percentage" yaml:"keeper_reward_percentages"` -} - -// BorrowLimit enforces restrictions on a money market -type BorrowLimit struct { - HasMaxLimit bool `json:"has_max_limit" yaml:"has_max_limit"` - MaximumLimit sdk.Dec `json:"maximum_limit" yaml:"maximum_limit"` - LoanToValue sdk.Dec `json:"loan_to_value" yaml:"loan_to_value"` -} - -// InterestRateModel contains information about an asset's interest rate -type InterestRateModel struct { - BaseRateAPY sdk.Dec `json:"base_rate_apy" yaml:"base_rate_apy"` - BaseMultiplier sdk.Dec `json:"base_multiplier" yaml:"base_multiplier"` - Kink sdk.Dec `json:"kink" yaml:"kink"` - JumpMultiplier sdk.Dec `json:"jump_multiplier" yaml:"jump_multiplier"` -} - -// GenesisAccumulationTimes slice of GenesisAccumulationTime -type GenesisAccumulationTimes []GenesisAccumulationTime - -// GenesisAccumulationTime stores the previous distribution time and its corresponding denom -type GenesisAccumulationTime struct { - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - PreviousAccumulationTime time.Time `json:"previous_accumulation_time" yaml:"previous_accumulation_time"` - SupplyInterestFactor sdk.Dec `json:"supply_interest_factor" yaml:"supply_interest_factor"` - BorrowInterestFactor sdk.Dec `json:"borrow_interest_factor" yaml:"borrow_interest_factor"` -} - -// Deposits is a slice of Deposit -type Deposits []Deposit - -// Deposit defines an amount of coins deposited into a hard module account -type Deposit struct { - Depositor sdk.AccAddress `json:"depositor" yaml:"depositor"` - Amount sdk.Coins `json:"amount" yaml:"amount"` - Index SupplyInterestFactors `json:"index" yaml:"index"` -} - -// SupplyInterestFactors is a slice of SupplyInterestFactor, because Amino won't marshal maps -type SupplyInterestFactors []SupplyInterestFactor - -// SupplyInterestFactor defines an individual borrow interest factor -type SupplyInterestFactor struct { - Denom string `json:"denom" yaml:"denom"` - Value sdk.Dec `json:"value" yaml:"value"` -} - -// Borrows is a slice of Borrow -type Borrows []Borrow - -// Borrow defines an amount of coins borrowed from a hard module account -type Borrow struct { - Borrower sdk.AccAddress `json:"borrower" yaml:"borrower"` - Amount sdk.Coins `json:"amount" yaml:"amount"` - Index BorrowInterestFactors `json:"index" yaml:"index"` -} - -// BorrowInterestFactors is a slice of BorrowInterestFactor, because Amino won't marshal maps -type BorrowInterestFactors []BorrowInterestFactor - -// BorrowInterestFactor defines an individual borrow interest factor -type BorrowInterestFactor struct { - Denom string `json:"denom" yaml:"denom"` - Value sdk.Dec `json:"value" yaml:"value"` -} diff --git a/x/hard/legacy/v0_16/migrate.go b/x/hard/legacy/v0_16/migrate.go deleted file mode 100644 index ee306115..00000000 --- a/x/hard/legacy/v0_16/migrate.go +++ /dev/null @@ -1,128 +0,0 @@ -package v0_16 - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - v015hard "github.com/0glabs/0g-chain/x/hard/legacy/v0_15" - v016hard "github.com/0glabs/0g-chain/x/hard/types" -) - -// Denom generated via: echo -n transfer/channel-0/uatom | shasum -a 256 | awk '{printf "ibc/%s",toupper($1)}' -const UATOM_IBC_DENOM = "ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2" - -func migrateParams(params v015hard.Params) v016hard.Params { - var moneyMarkets []v016hard.MoneyMarket - for _, mm := range params.MoneyMarkets { - moneyMarket := v016hard.MoneyMarket{ - Denom: mm.Denom, - BorrowLimit: v016hard.BorrowLimit{ - HasMaxLimit: mm.BorrowLimit.HasMaxLimit, - MaximumLimit: mm.BorrowLimit.MaximumLimit, - LoanToValue: mm.BorrowLimit.LoanToValue, - }, - SpotMarketID: mm.SpotMarketID, - ConversionFactor: mm.ConversionFactor, - InterestRateModel: v016hard.InterestRateModel{ - BaseRateAPY: mm.InterestRateModel.BaseRateAPY, - BaseMultiplier: mm.InterestRateModel.BaseMultiplier, - Kink: mm.InterestRateModel.Kink, - JumpMultiplier: mm.InterestRateModel.JumpMultiplier, - }, - ReserveFactor: mm.ReserveFactor, - KeeperRewardPercentage: mm.KeeperRewardPercentage, - } - moneyMarkets = append(moneyMarkets, moneyMarket) - } - - atomMoneyMarket := v016hard.MoneyMarket{ - Denom: UATOM_IBC_DENOM, - BorrowLimit: v016hard.BorrowLimit{ - HasMaxLimit: true, - MaximumLimit: sdk.NewDec(25000000000), - LoanToValue: sdk.MustNewDecFromStr("0.5"), - }, - SpotMarketID: "atom:usd:30", - ConversionFactor: sdkmath.NewInt(1000000), - InterestRateModel: v016hard.InterestRateModel{ - BaseRateAPY: sdk.ZeroDec(), - BaseMultiplier: sdk.MustNewDecFromStr("0.05"), - Kink: sdk.MustNewDecFromStr("0.8"), - JumpMultiplier: sdk.NewDec(5), - }, - ReserveFactor: sdk.MustNewDecFromStr("0.025"), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.02"), - } - moneyMarkets = append(moneyMarkets, atomMoneyMarket) - - return v016hard.Params{ - MoneyMarkets: moneyMarkets, - MinimumBorrowUSDValue: params.MinimumBorrowUSDValue, - } -} - -func migrateDeposits(oldDeposits v015hard.Deposits) v016hard.Deposits { - deposits := make(v016hard.Deposits, len(oldDeposits)) - for i, deposit := range oldDeposits { - - interestFactors := make(v016hard.SupplyInterestFactors, len(deposit.Index)) - for j, interestFactor := range deposit.Index { - interestFactors[j] = v016hard.SupplyInterestFactor{ - Denom: interestFactor.Denom, - Value: interestFactor.Value, - } - } - - deposits[i] = v016hard.Deposit{ - Depositor: deposit.Depositor, - Amount: deposit.Amount, - Index: interestFactors, - } - } - return deposits -} - -func migratePrevAccTimes(oldPrevAccTimes v015hard.GenesisAccumulationTimes) v016hard.GenesisAccumulationTimes { - prevAccTimes := make(v016hard.GenesisAccumulationTimes, len(oldPrevAccTimes)) - for i, prevAccTime := range oldPrevAccTimes { - prevAccTimes[i] = v016hard.GenesisAccumulationTime{ - CollateralType: prevAccTime.CollateralType, - PreviousAccumulationTime: prevAccTime.PreviousAccumulationTime, - SupplyInterestFactor: prevAccTime.SupplyInterestFactor, - BorrowInterestFactor: prevAccTime.BorrowInterestFactor, - } - } - return prevAccTimes -} - -func migrateBorrows(oldBorrows v015hard.Borrows) v016hard.Borrows { - borrows := make(v016hard.Borrows, len(oldBorrows)) - for i, borrow := range oldBorrows { - interestFactors := make(v016hard.BorrowInterestFactors, len(borrow.Index)) - for j, interestFactor := range borrow.Index { - interestFactors[j] = v016hard.BorrowInterestFactor{ - Denom: interestFactor.Denom, - Value: interestFactor.Value, - } - } - borrows[i] = v016hard.Borrow{ - Borrower: borrow.Borrower, - Amount: borrow.Amount, - Index: interestFactors, - } - } - return borrows -} - -// Migrate converts v0.15 hard state and returns it in v0.16 format -func Migrate(oldState v015hard.GenesisState) *v016hard.GenesisState { - return &v016hard.GenesisState{ - Params: migrateParams(oldState.Params), - PreviousAccumulationTimes: migratePrevAccTimes(oldState.PreviousAccumulationTimes), - Deposits: migrateDeposits(oldState.Deposits), - Borrows: migrateBorrows(oldState.Borrows), - TotalSupplied: oldState.TotalSupplied, - TotalBorrowed: oldState.TotalBorrowed, - TotalReserves: oldState.TotalReserves, - } -} diff --git a/x/hard/legacy/v0_16/migrate_test.go b/x/hard/legacy/v0_16/migrate_test.go deleted file mode 100644 index 3b662e0f..00000000 --- a/x/hard/legacy/v0_16/migrate_test.go +++ /dev/null @@ -1,198 +0,0 @@ -package v0_16 - -import ( - "io/ioutil" - "path/filepath" - "testing" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - app "github.com/0glabs/0g-chain/app" - v015hard "github.com/0glabs/0g-chain/x/hard/legacy/v0_15" - v016hard "github.com/0glabs/0g-chain/x/hard/types" -) - -type migrateTestSuite struct { - suite.Suite - - addresses []sdk.AccAddress - cdc codec.Codec - legacyCdc *codec.LegacyAmino -} - -func (s *migrateTestSuite) SetupTest() { - app.SetSDKConfig() - config := app.MakeEncodingConfig() - s.cdc = config.Marshaler - - legacyCodec := codec.NewLegacyAmino() - s.legacyCdc = legacyCodec - - _, accAddresses := app.GeneratePrivKeyAddressPairs(10) - s.addresses = accAddresses -} - -func (s *migrateTestSuite) TestMigrate_JSON() { - file := filepath.Join("testdata", "v15-hard.json") - data, err := ioutil.ReadFile(file) - s.Require().NoError(err) - var v15genstate v015hard.GenesisState - err = s.legacyCdc.UnmarshalJSON(data, &v15genstate) - s.Require().NoError(err) - genstate := Migrate(v15genstate) - actual := s.cdc.MustMarshalJSON(genstate) - - file = filepath.Join("testdata", "v16-hard.json") - expected, err := ioutil.ReadFile(file) - s.Require().NoError(err) - s.Require().JSONEq(string(expected), string(actual)) -} - -func (s *migrateTestSuite) TestMigrate_GenState() { - v15genstate := v015hard.GenesisState{ - Params: v015hard.Params{ - MoneyMarkets: v015hard.MoneyMarkets{ - { - Denom: "kava", - BorrowLimit: v015hard.BorrowLimit{ - HasMaxLimit: true, - MaximumLimit: sdk.MustNewDecFromStr("0.1"), - LoanToValue: sdk.MustNewDecFromStr("0.2"), - }, - SpotMarketID: "spot-market-id", - ConversionFactor: sdkmath.NewInt(110), - InterestRateModel: v015hard.InterestRateModel{ - BaseRateAPY: sdk.MustNewDecFromStr("0.1"), - BaseMultiplier: sdk.MustNewDecFromStr("0.2"), - Kink: sdk.MustNewDecFromStr("0.3"), - JumpMultiplier: sdk.MustNewDecFromStr("0.4"), - }, - ReserveFactor: sdk.MustNewDecFromStr("0.5"), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.6"), - }, - }, - }, - PreviousAccumulationTimes: v015hard.GenesisAccumulationTimes{ - { - CollateralType: "kava", - PreviousAccumulationTime: time.Date(1998, time.January, 1, 12, 0, 0, 1, time.UTC), - SupplyInterestFactor: sdk.MustNewDecFromStr("0.1"), - BorrowInterestFactor: sdk.MustNewDecFromStr("0.2"), - }, - }, - Deposits: v015hard.Deposits{ - { - Depositor: s.addresses[0], - Amount: sdk.NewCoins(sdk.NewCoin("kava", sdkmath.NewInt(100))), - Index: v015hard.SupplyInterestFactors{ - { - Denom: "kava", - Value: sdk.MustNewDecFromStr("1.12"), - }, - }, - }, - }, - Borrows: v015hard.Borrows{ - { - Borrower: s.addresses[1], - Amount: sdk.NewCoins(sdk.NewCoin("kava", sdkmath.NewInt(100))), - Index: v015hard.BorrowInterestFactors{ - { - Denom: "kava", - Value: sdk.MustNewDecFromStr("1.12"), - }, - }, - }, - }, - TotalSupplied: sdk.NewCoins(sdk.NewCoin("kava", sdkmath.NewInt(100))), - TotalBorrowed: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - TotalReserves: sdk.NewCoins(sdk.NewCoin("xrp", sdkmath.NewInt(300))), - } - expected := v016hard.GenesisState{ - Params: v016hard.Params{ - MoneyMarkets: v016hard.MoneyMarkets{ - { - Denom: "kava", - BorrowLimit: v016hard.BorrowLimit{ - HasMaxLimit: true, - MaximumLimit: sdk.MustNewDecFromStr("0.1"), - LoanToValue: sdk.MustNewDecFromStr("0.2"), - }, - SpotMarketID: "spot-market-id", - ConversionFactor: sdkmath.NewInt(110), - InterestRateModel: v016hard.InterestRateModel{ - BaseRateAPY: sdk.MustNewDecFromStr("0.1"), - BaseMultiplier: sdk.MustNewDecFromStr("0.2"), - Kink: sdk.MustNewDecFromStr("0.3"), - JumpMultiplier: sdk.MustNewDecFromStr("0.4"), - }, - ReserveFactor: sdk.MustNewDecFromStr("0.5"), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.6"), - }, - { - Denom: UATOM_IBC_DENOM, - BorrowLimit: v016hard.BorrowLimit{ - HasMaxLimit: true, - MaximumLimit: sdk.NewDec(25000000000), - LoanToValue: sdk.MustNewDecFromStr("0.5"), - }, - SpotMarketID: "atom:usd:30", - ConversionFactor: sdkmath.NewInt(1000000), - InterestRateModel: v016hard.InterestRateModel{ - BaseRateAPY: sdk.ZeroDec(), - BaseMultiplier: sdk.MustNewDecFromStr("0.05"), - Kink: sdk.MustNewDecFromStr("0.8"), - JumpMultiplier: sdk.NewDec(5), - }, - ReserveFactor: sdk.MustNewDecFromStr("0.025"), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.02"), - }, - }, - }, - PreviousAccumulationTimes: v016hard.GenesisAccumulationTimes{ - { - CollateralType: "kava", - PreviousAccumulationTime: time.Date(1998, time.January, 1, 12, 0, 0, 1, time.UTC), - SupplyInterestFactor: sdk.MustNewDecFromStr("0.1"), - BorrowInterestFactor: sdk.MustNewDecFromStr("0.2"), - }, - }, - Deposits: v016hard.Deposits{ - { - Depositor: s.addresses[0], - Amount: sdk.NewCoins(sdk.NewCoin("kava", sdkmath.NewInt(100))), - Index: v016hard.SupplyInterestFactors{ - { - Denom: "kava", - Value: sdk.MustNewDecFromStr("1.12"), - }, - }, - }, - }, - Borrows: v016hard.Borrows{ - { - Borrower: s.addresses[1], - Amount: sdk.NewCoins(sdk.NewCoin("kava", sdkmath.NewInt(100))), - Index: v016hard.BorrowInterestFactors{ - { - Denom: "kava", - Value: sdk.MustNewDecFromStr("1.12"), - }, - }, - }, - }, - TotalSupplied: sdk.NewCoins(sdk.NewCoin("kava", sdkmath.NewInt(100))), - TotalBorrowed: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - TotalReserves: sdk.NewCoins(sdk.NewCoin("xrp", sdkmath.NewInt(300))), - } - genState := Migrate(v15genstate) - s.Require().Equal(expected, *genState) -} - -func TestHardMigrateTestSuite(t *testing.T) { - suite.Run(t, new(migrateTestSuite)) -} diff --git a/x/hard/legacy/v0_16/testdata/v15-hard.json b/x/hard/legacy/v0_16/testdata/v15-hard.json deleted file mode 100644 index c58c35a0..00000000 --- a/x/hard/legacy/v0_16/testdata/v15-hard.json +++ /dev/null @@ -1,115 +0,0 @@ -{ - "params": { - "minimum_borrow_usd_value": "10.0", - "money_markets": [ - { - "denom": "usdx", - "borrow_limit": { - "has_max_limit": false, - "maximum_limit": "20000000", - "loan_to_value": "0.80" - }, - "spot_market_id": "usdx:usd", - "conversion_factor": "1000000", - "interest_rate_model": { - "base_rate_apy": "0.05", - "base_multiplier": "0.1", - "kink": "0.8", - "jump_multiplier": "0.5" - }, - "reserve_factor": "0.0", - "keeper_reward_percentage": "0.05" - }, - { - "denom": "ukava", - "borrow_limit": { - "has_max_limit": false, - "maximum_limit": "100000000000", - "loan_to_value": "0.80" - }, - "spot_market_id": "kava:usd", - "conversion_factor": "1000000", - "interest_rate_model": { - "base_rate_apy": "0.05", - "base_multiplier": "2", - "kink": "0.85", - "jump_multiplier": "10" - }, - "reserve_factor": "0.1", - "keeper_reward_percentage": "0.01" - } - ] - }, - "deposits": [ - { - "amount": [ - { - "amount": "162103943", - "denom": "bnb" - }, - { - "amount": "19428483", - "denom": "btcb" - } - ], - "depositor": "kava1qq9ustlc0nv4aew275w93g4qy5zahqgxf5mwv9", - "index": [ - { - "denom": "bnb", - "value": "1.001740185031830285" - } - ] - } - ], - "borrows": [ - { - "amount": [ - { - "amount": "146724966", - "denom": "usdx" - }, - { - "amount": "541061835659", - "denom": "xrpb" - } - ], - "borrower": "kava1qq9ustlc0nv4aew275w93g4qy5zahqgxf5mwv9", - "index": [ - { - "denom": "usdx", - "value": "1.000156840239586720" - }, - { - "denom": "xrpb", - "value": "1.002063063678030789" - } - ] - } - ], - "total_supplied": [ - { - "amount": "1246173151758", - "denom": "bnb" - } - ], - "total_borrowed": [ - { - "amount": "704609324351367", - "denom": "busd" - } - ], - "total_reserves": [ - { - "amount": "711656301126744", - "denom": "xrpb" - } - ], - "previous_accumulation_times": [ - { - "borrow_interest_factor": "1.002233592784895182", - "collateral_type": "btcb", - "previous_accumulation_time": "2021-11-05T21:13:12.85608847Z", - "supply_interest_factor": "1.000205165357775358" - } - ] -} diff --git a/x/hard/legacy/v0_16/testdata/v16-hard.json b/x/hard/legacy/v0_16/testdata/v16-hard.json deleted file mode 100644 index 027676ed..00000000 --- a/x/hard/legacy/v0_16/testdata/v16-hard.json +++ /dev/null @@ -1,95 +0,0 @@ -{ - "params": { - "money_markets": [ - { - "denom": "usdx", - "borrow_limit": { - "has_max_limit": false, - "maximum_limit": "20000000.000000000000000000", - "loan_to_value": "0.800000000000000000" - }, - "spot_market_id": "usdx:usd", - "conversion_factor": "1000000", - "interest_rate_model": { - "base_rate_apy": "0.050000000000000000", - "base_multiplier": "0.100000000000000000", - "kink": "0.800000000000000000", - "jump_multiplier": "0.500000000000000000" - }, - "reserve_factor": "0.000000000000000000", - "keeper_reward_percentage": "0.050000000000000000" - }, - { - "denom": "ukava", - "borrow_limit": { - "has_max_limit": false, - "maximum_limit": "100000000000.000000000000000000", - "loan_to_value": "0.800000000000000000" - }, - "spot_market_id": "kava:usd", - "conversion_factor": "1000000", - "interest_rate_model": { - "base_rate_apy": "0.050000000000000000", - "base_multiplier": "2.000000000000000000", - "kink": "0.850000000000000000", - "jump_multiplier": "10.000000000000000000" - }, - "reserve_factor": "0.100000000000000000", - "keeper_reward_percentage": "0.010000000000000000" - }, - { - "denom": "ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2", - "borrow_limit": { - "has_max_limit": true, - "maximum_limit": "25000000000.000000000000000000", - "loan_to_value": "0.500000000000000000" - }, - "spot_market_id": "atom:usd:30", - "conversion_factor": "1000000", - "interest_rate_model": { - "base_rate_apy": "0.000000000000000000", - "base_multiplier": "0.050000000000000000", - "kink": "0.800000000000000000", - "jump_multiplier": "5.000000000000000000" - }, - "reserve_factor": "0.025000000000000000", - "keeper_reward_percentage": "0.020000000000000000" - } - ], - "minimum_borrow_usd_value": "10.000000000000000000" - }, - "previous_accumulation_times": [ - { - "collateral_type": "btcb", - "previous_accumulation_time": "2021-11-05T21:13:12.856088470Z", - "supply_interest_factor": "1.000205165357775358", - "borrow_interest_factor": "1.002233592784895182" - } - ], - "deposits": [ - { - "depositor": "kava1qq9ustlc0nv4aew275w93g4qy5zahqgxf5mwv9", - "amount": [ - { "denom": "bnb", "amount": "162103943" }, - { "denom": "btcb", "amount": "19428483" } - ], - "index": [{ "denom": "bnb", "value": "1.001740185031830285" }] - } - ], - "borrows": [ - { - "borrower": "kava1qq9ustlc0nv4aew275w93g4qy5zahqgxf5mwv9", - "amount": [ - { "denom": "usdx", "amount": "146724966" }, - { "denom": "xrpb", "amount": "541061835659" } - ], - "index": [ - { "denom": "usdx", "value": "1.000156840239586720" }, - { "denom": "xrpb", "value": "1.002063063678030789" } - ] - } - ], - "total_supplied": [{ "denom": "bnb", "amount": "1246173151758" }], - "total_borrowed": [{ "denom": "busd", "amount": "704609324351367" }], - "total_reserves": [{ "denom": "xrpb", "amount": "711656301126744" }] -} diff --git a/x/hard/module.go b/x/hard/module.go deleted file mode 100644 index b94f38f1..00000000 --- a/x/hard/module.go +++ /dev/null @@ -1,148 +0,0 @@ -package hard - -import ( - "context" - "encoding/json" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/0glabs/0g-chain/x/hard/client/cli" - "github.com/0glabs/0g-chain/x/hard/keeper" - "github.com/0glabs/0g-chain/x/hard/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name get module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis returns default genesis state as raw bytes for the hard -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - gs := types.DefaultGenesisState() - return cdc.MustMarshalJSON(&gs) -} - -// ValidateGenesis performs genesis state validation for the hard module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - err := cdc.UnmarshalJSON(bz, &gs) - if err != nil { - return err - } - return gs.Validate() -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the gov module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return 1 -} - -// GetTxCmd returns the root tx command for the hard module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the hard module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -//____________________________________________________________________________ - -// AppModule app module type -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - pricefeedKeeper types.PricefeedKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, accountKeeper types.AccountKeeper, bankKeeper types.BankKeeper, pricefeedKeeper types.PricefeedKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - pricefeedKeeper: pricefeedKeeper, - } -} - -// Name module name -func (AppModule) Name() string { - return types.ModuleName -} - -// RegisterInvariants register module invariants -func (AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper, am.accountKeeper, am.bankKeeper)) -} - -// InitGenesis performs genesis initialization for the hard module. It returns -// no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { - var genState types.GenesisState - // Initialize global index to index in genesis state - cdc.MustUnmarshalJSON(gs, &genState) - - InitGenesis(ctx, am.keeper, am.accountKeeper, genState) - return []abci.ValidatorUpdate{} -} - -// ExportGenesis returns the exported genesis state as raw bytes for the hard -// module. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(&gs) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { - BeginBlocker(ctx, am.keeper) -} - -// EndBlock module end-block -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/hard/spec/01_concepts.md b/x/hard/spec/01_concepts.md deleted file mode 100644 index 1886376f..00000000 --- a/x/hard/spec/01_concepts.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# Concepts - -## Automated, Cross-Chain Money Markets - -The hard module provides for functionality and governance of a two-sided money market protocol with autonomous interest rates. The main state transitions in the hard module are composed of deposit, withdraw, borrow and repay actions. Borrow positions can be liquidated by an external party called a "keeper". Keepers receive a fee in exchange for liquidating risk positions, and the fee rate is determined by governance. Internally, all funds are stored in a module account (the cosmos-sdk equivalent of the `address` portion of a smart contract), and can be accessed via the above actions. Each money market has governance parameters which are controlled by token-holder governance. Of particular note are the interest rate model, which determines (using a static formula) what the prevailing rate of interest will be for each block, and the loan-to-value (LTV), which determines how much borrowing power each unit of deposited collateral will count for. Initial parameterization of the hard module will stipulate that all markets are over-collateralized and that overall borrow limits for each collateral will start small and rise gradually. - -## HARD Token distribution - -[See Incentive Module](../../incentive/spec/01_concepts.md) diff --git a/x/hard/spec/02_state.md b/x/hard/spec/02_state.md deleted file mode 100644 index 0bc73e70..00000000 --- a/x/hard/spec/02_state.md +++ /dev/null @@ -1,67 +0,0 @@ - - -# State - -## Parameters and Genesis State - -`Parameters` define the governance parameters and default behavior of each money market. **Money markets should not be removed from params without careful procedures** as it will disable withdraws and liquidations. Deposits can not be explicitly turned off, but these steps remove the economic incentives to do so. In advance of deprecating a money market, the following steps should be observed: - -1. Borrowing: prevent new borrows by setting param `MoneyMarket.BorrowLimit.MaximumLimit` to 0. `HasMaxLimit` must also be set to true to enable limit checks. -2. Interest: turn off interest accumulation by setting params `MoneyMarket.InterestRateModel.BaseRateAPY`, `MoneyMarket.InterestRateModel.BaseMultiplier`, and `MoneyMarket.InterestRateModel.JumpMultiplier` to 0. -3. Rewards: turn off supply side and/or borrow side rewards by removing any coins in the relevant `RewardsPerSecond` param in the Incentive module. - -Without financial incentives, borrowers and suppliers will withdraw their funds from the money market over time. Once the balances have reached an acceptable level the money market can be deprecated and removed from params, with any additional lingering user funds reimbursed/reallocated as appropriate via a chain upgrade. - -```go -// Params governance parameters for hard module -type Params struct { - MoneyMarkets MoneyMarkets `json:"money_markets" yaml:"money_markets"` - MinimumBorrowUSDValue sdk.Dec `json:"minimum_borrow_usd_value" yaml:"minimum_borrow_usd_value"` -} - -// MoneyMarket is a money market for an individual asset -type MoneyMarket struct { - Denom string `json:"denom" yaml:"denom"` // the denomination of the token for this money market - BorrowLimit BorrowLimit `json:"borrow_limit" yaml:"borrow_limit"` // the borrow limits, if any, applied to this money market - SpotMarketID string `json:"spot_market_id" yaml:"spot_market_id"` // the pricefeed market where price data is fetched - ConversionFactor sdkmath.Int `json:"conversion_factor" yaml:"conversion_factor"` //the internal conversion factor for going from the smallest unit of a token to a whole unit (ie. 8 for BTC, 6 for KAVA, 18 for ETH) - InterestRateModel InterestRateModel `json:"interest_rate_model" yaml:"interest_rate_model"` // the model that determines the prevailing interest rate at each block - ReserveFactor sdk.Dec `json:"reserve_factor" yaml:"reserve_factor"` // the percentage of interest that is accumulated by the protocol as reserves - KeeperRewardPercentage sdk.Dec `json:"keeper_reward_percentage" yaml:"keeper_reward_percentages"` // the percentage of a liquidation that is given to the keeper that liquidated the position -} - -// MoneyMarkets slice of MoneyMarket -type MoneyMarkets []MoneyMarket - -// InterestRateModel contains information about an asset's interest rate -type InterestRateModel struct { - BaseRateAPY sdk.Dec `json:"base_rate_apy" yaml:"base_rate_apy"` // the base rate of APY when borrows are zero. Ex. A value of "0.02" would signify an interest rate of 2% APY as the Y-intercept of the interest rate model for the money market. Note that internally, interest rates are stored as per-second interest. - BaseMultiplier sdk.Dec `json:"base_multiplier" yaml:"base_multiplier"` // the percentage rate at which the interest rate APY increases for each percentage increase in borrow utilization. Ex. A value of "0.01" signifies that the APY interest rate increases by 1% for each additional percentage increase in borrow utilization. - Kink sdk.Dec `json:"kink" yaml:"kink"` // the inflection point at which the BaseMultiplier no longer applies and the JumpMultiplier does apply. For example, a value of "0.8" signifies that at 80% utilization, the JumpMultiplier applies - JumpMultiplier sdk.Dec `json:"jump_multiplier" yaml:"jump_multiplier"` // same as BaseMultiplier, but only applied when utilization is above the Kink -} - -// BorrowLimit enforces restrictions on a money market -type BorrowLimit struct { - HasMaxLimit bool `json:"has_max_limit" yaml:"has_max_limit"` // boolean for if the money market has a max amount that can be borrowed, irrespective of utilization. - MaximumLimit sdk.Dec `json:"maximum_limit" yaml:"maximum_limit"` // the maximum amount that can be borrowed for this money market, irrespective of utilization. Ignored if HasMaxLimit is false - LoanToValue sdk.Dec `json:"loan_to_value" yaml:"loan_to_value"` // the percentage amount of borrow power each unit of deposit accounts for. Ex. A value of "0.5" signifies that for $1 of supply of a particular asset, borrow limits will be increased by $0.5 -} -``` - -`GenesisState` defines the state that must be persisted when the blockchain stops/restarts in order for normal function of the hard module to resume and all outstanding funds + interest to be accounted for. - -```go -// GenesisState is the state that must be provided at genesis. -type GenesisState struct { - Params Params `json:"params" yaml:"params"` // governance parameters - PreviousAccumulationTimes GenesisAccumulationTimes `json:"previous_accumulation_times" yaml:"previous_accumulation_times"` // stores the last time interest was calculated for a particular money market - Deposits Deposits `json:"deposits" yaml:"deposits"` // stores existing deposits when the chain starts, if any - Borrows Borrows `json:"borrows" yaml:"borrows"` // stores existing borrows when the chain starts, if any - TotalSupplied sdk.Coins `json:"total_supplied" yaml:"total_supplied"` // stores the running total of supplied (deposits + interest) coins when the chain starts, if any - TotalBorrowed sdk.Coins `json:"total_borrowed" yaml:"total_borrowed"` // stores the running total of borrowed coins when the chain starts, if any - TotalReserves sdk.Coins `json:"total_reserves" yaml:"total_reserves"` // stores the running total of reserves when the chain starts, if any -} -``` diff --git a/x/hard/spec/03_messages.md b/x/hard/spec/03_messages.md deleted file mode 100644 index 15580606..00000000 --- a/x/hard/spec/03_messages.md +++ /dev/null @@ -1,58 +0,0 @@ - - -# Messages - -There are three messages in the hard module. Deposit allows users to deposit assets to the hard module. In version 2, depositors will be able to use their deposits as collateral to borrow from hard. Withdraw removes assets from the hard module, returning them to the user. Claim allows users to claim earned HARD tokens. - -```go -// MsgDeposit deposit collateral to the hard module. -type MsgDeposit struct { - Depositor sdk.AccAddress `json:"depositor" yaml:"depositor"` - Amount sdk.Coins `json:"amount" yaml:"amount"` -} -``` - -This message creates a `Deposit` object if one does not exist, or updates an existing one, as well as creating/updating the necessary indexes and synchronizing any outstanding interest. The `Amount` of coins is transferred from `Depositor` to the hard module account. The global variable for `TotalSupplied` is updated. - -```go -// MsgWithdraw withdraw from the hard module. -type MsgWithdraw struct { - Depositor sdk.AccAddress `json:"depositor" yaml:"depositor"` - Amount sdk.Coins `json:"amount" yaml:"amount"` -} -``` - -This message decrements a `Deposit` object, or deletes one if the `Amount` specified is greater than or equal to the total deposited amount, as well as creating/updating the necessary indexes and synchronizing any outstanding interest. For example, a message which requests to withdraw 100xyz tokens, if `Depositor` has only deposited 50xyz tokens, will withdraw the full 50xyz tokens. The `Amount` of coins, or the current deposited amount, whichever is lower, is transferred from the hard module account to `Depositor`. The global variable for `TotalSupplied` is updated. - -```go -// MsgBorrow borrows funds from the hard module. -type MsgBorrow struct { - Borrower sdk.AccAddress `json:"borrower" yaml:"borrower"` - Amount sdk.Coins `json:"amount" yaml:"amount"` -} -``` - -This message creates a `Borrow` object is one does not exist, or updates an existing one, as well as creating/updating the necessary indexes and synchronizing any outstanding interest. The `Amount` of coins is transferred from the hard module account to `Depositor`. The global variable for `TotalBorrowed` is updated. - -```go -// MsgRepay repays funds to the hard module. -type MsgRepay struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - Owner sdk.AccAddress `json:"owner" yaml:"owner"` - Amount sdk.Coins `json:"amount" yaml:"amount"` -} -``` - -This message decrements a `Borrow` object, or deletes one if the `Amount` specified is greater than or equal to the total borrowed amount, as well as creating/updating the necessary indexes and synchronizing any outstanding interest. For example, a message which requests to repay 100xyz tokens, if `Owner` has only deposited 50xyz tokens, the `Sender` will repay the full 50xyz tokens. The `Amount` of coins, or the current borrow amount, is transferred from `Sender`. The global variable for `TotalBorrowed` is updated. - -```go -// MsgLiquidate attempts to liquidate a borrower's borrow -type MsgLiquidate struct { - Keeper sdk.AccAddress `json:"keeper" yaml:"keeper"` - Borrower sdk.AccAddress `json:"borrower" yaml:"borrower"` -} -``` - -This message deletes `Borrower's` `Deposit` and `Borrow` objects if they are below the required LTV ratio. The keeper (the sender of the message) is rewarded a portion of the borrow position, according to the `KeeperReward` governance parameter. The coins from the `Deposit` are then sold at auction (see [auction module](../../auction/spec/README.md)), which any remaining tokens returned to `Borrower`. After being liquidated, `Borrower` no longer must repay the borrow amount. The global variables for `TotalSupplied` and `TotalBorrowed` are updated. diff --git a/x/hard/spec/04_events.md b/x/hard/spec/04_events.md deleted file mode 100644 index 44532100..00000000 --- a/x/hard/spec/04_events.md +++ /dev/null @@ -1,46 +0,0 @@ - - -# Events - -The hard module emits the following events: - -## Handlers - -### MsgDeposit - -| Type | Attribute Key | Attribute Value | -| ------------ | ------------- | --------------------- | -| message | module | hard | -| message | sender | `{sender address}` | -| hard_deposit | amount | `{amount}` | -| hard_deposit | depositor | `{depositor address}` | - -### MsgWithdraw - -| Type | Attribute Key | Attribute Value | -| --------------- | ------------- | --------------------- | -| message | module | hard | -| message | sender | `{sender address}` | -| hard_withdrawal | amount | `{amount}` | -| hard_withdrawal | depositor | `{depositor address}` | - -### MsgBorrow - -| Type | Attribute Key | Attribute Value | -| --------------- | ------------- | -------------------- | -| message | module | hard | -| message | sender | `{sender address}` | -| hard_borrow | borrow_coins | `{amount}` | -| hard_withdrawal | borrower | `{borrower address}` | - -### MsgRepay - -| Type | Attribute Key | Attribute Value | -| ---------- | ------------- | -------------------- | -| message | module | hard | -| message | sender | `{sender address}` | -| message | owner | `{owner address}` | -| hard_repay | repay_coins | `{amount}` | -| hard_repay | sender | `{borrower address}` | diff --git a/x/hard/spec/05_params.md b/x/hard/spec/05_params.md deleted file mode 100644 index 6f4ad2c5..00000000 --- a/x/hard/spec/05_params.md +++ /dev/null @@ -1,41 +0,0 @@ - - -# Parameters - -Example parameters for the Hard module: - -| Key | Type | Example | Description | -| --------------------- | ------------------- | ------------- | -------------------------------------------- | -| MoneyMarkets | array (MoneyMarket) | [{see below}] | Array of params for each supported market | -| MinimumBorrowUSDValue | sdk.Dec | 10.0 | Minimum amount an individual user can borrow | - -Example parameters for `MoneyMarket`: - -| Key | Type | Example | Description | -| ---------------------- | ----------------- | ------------- | --------------------------------------------------------------------- | -| Denom | string | "bnb" | Coin denom of the asset which can be deposited and borrowed | -| BorrowLimit | BorrowLimit | [{see below}] | Borrow limits applied to this money market | -| SpotMarketID | string | "bnb:usd" | The market id which determines the price of the asset | -| ConversionFactor | Int | "6" | Conversion factor for one unit (ie BNB) to the smallest internal unit | -| InterestRateModel | InterestRateModel | [{see below}] | Model which determines the prevailing interest rate per block | -| ReserveFactor | Dec | "0.01" | Percentage of interest that is kept as protocol reserves | -| KeeperRewardPercentage | Dec | "0.02" | Percentage of deposit rewarded to keeper who liquidates a position | - -Example parameters for `BorrowLimit`: - -| Key | Type | Example | Description | -| ------------ | ---- | ------------ | ----------------------------------------------------------------------- | -| HasMaxLimit | bool | "true" | Boolean for if a maximum limit is in effect | -| MaximumLimit | Dec | "10000000.0" | Global maximum amount of coins that can be borrowed | -| LoanToValue | Dec | "0.5" | The percentage amount of borrow power each unit of deposit accounts for | - -Example parameters for `InterestRateModel`: - -| Key | Type | Example | Description | -| -------------- | ---- | ------- | --------------------------------------------------------------------------------------------------------------- | -| BaseRateAPY | Dec | "0.0" | The base rate of APY interest when borrows are zero | -| BaseMultiplier | Dec | "0.01" | The percentage rate at which the interest rate APY increases for each percentage increase in borrow utilization | -| Kink | Dec | "0.5" | The inflection point of utilization at which the BaseMultiplier no longer applies and the JumpMultiplier does | -| JumpMultiplier | Dec | "0.5" | Same as BaseMultiplier, but only applied when utilization is above the Kink | diff --git a/x/hard/spec/06_begin_block.md b/x/hard/spec/06_begin_block.md deleted file mode 100644 index 173fb954..00000000 --- a/x/hard/spec/06_begin_block.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# Begin Block - -At the start of each block interest is accumulated - -```go -// BeginBlocker updates interest rates -func BeginBlocker(ctx sdk.Context, k Keeper) { - k.ApplyInterestRateUpdates(ctx) -} -``` diff --git a/x/hard/spec/README.md b/x/hard/spec/README.md deleted file mode 100644 index a37e6be2..00000000 --- a/x/hard/spec/README.md +++ /dev/null @@ -1,21 +0,0 @@ - - -# `hard` - - - -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** -5. **[Params](05_params.md)** -6. **[BeginBlock](06_begin_block.md)** - -## Abstract - -`x/hard` is an implementation of a Cosmos SDK Module that provides for functionality and governance of a two-sided, cross-chain, money market protocol. diff --git a/x/hard/types/borrow.go b/x/hard/types/borrow.go deleted file mode 100644 index 5c395610..00000000 --- a/x/hard/types/borrow.go +++ /dev/null @@ -1,198 +0,0 @@ -package types - -import ( - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// NewBorrow returns a new Borrow instance -func NewBorrow(borrower sdk.AccAddress, amount sdk.Coins, index BorrowInterestFactors) Borrow { - return Borrow{ - Borrower: borrower, - Amount: amount, - Index: index, - } -} - -// NormalizedBorrow is the borrow amounts divided by the interest factors. -// -// Multiplying the normalized borrow by the current global factors gives the current borrow (ie including all interest, ie a synced borrow). -// The normalized borrow is effectively how big the borrow would have been if it had been borrowed at time 0 and not touched since. -// -// An error is returned if the borrow is in an invalid state. -func (b Borrow) NormalizedBorrow() (sdk.DecCoins, error) { - normalized := sdk.NewDecCoins() - - for _, coin := range b.Amount { - - factor, found := b.Index.GetInterestFactor(coin.Denom) - if !found { - return nil, fmt.Errorf("borrowed amount '%s' missing interest factor", coin.Denom) - } - if factor.LT(sdk.OneDec()) { - return nil, fmt.Errorf("interest factor '%s' < 1", coin.Denom) - } - - normalized = normalized.Add( - sdk.NewDecCoinFromDec( - coin.Denom, - sdk.NewDecFromInt(coin.Amount).Quo(factor), - ), - ) - } - return normalized, nil -} - -// Validate deposit validation -func (b Borrow) Validate() error { - if b.Borrower.Empty() { - return fmt.Errorf("borrower cannot be empty") - } - if !b.Amount.IsValid() { - return fmt.Errorf("invalid borrow coins: %s", b.Amount) - } - - if err := b.Index.Validate(); err != nil { - return err - } - - return nil -} - -// ToResponse converts Borrow to BorrowResponse -func (b Borrow) ToResponse() BorrowResponse { - return NewBorrowResponse(b.Borrower, b.Amount, b.Index) -} - -// Borrows is a slice of Borrow -type Borrows []Borrow - -// Validate validates Borrows -func (bs Borrows) Validate() error { - borrowDupMap := make(map[string]Borrow) - for _, b := range bs { - if err := b.Validate(); err != nil { - return err - } - dup, ok := borrowDupMap[b.Borrower.String()] - if ok { - return fmt.Errorf("duplicate borrower: %s\n%s", b, dup) - } - borrowDupMap[b.Borrower.String()] = b - } - return nil -} - -// ToResponse converts Borrows to BorrowResponses -func (bs Borrows) ToResponse() BorrowResponses { - var bResponses BorrowResponses - - for _, b := range bs { - bResponses = append(bResponses, b.ToResponse()) - } - return bResponses -} - -// NewBorrowResponse returns a new BorrowResponse instance -func NewBorrowResponse(borrower sdk.AccAddress, amount sdk.Coins, index BorrowInterestFactors) BorrowResponse { - return BorrowResponse{ - Borrower: borrower.String(), - Amount: amount, - Index: index.ToResponse(), - } -} - -// BorrowResponses is a slice of BorrowResponse -type BorrowResponses []BorrowResponse - -// NewBorrowInterestFactor returns a new BorrowInterestFactor instance -func NewBorrowInterestFactor(denom string, value sdk.Dec) BorrowInterestFactor { - return BorrowInterestFactor{ - Denom: denom, - Value: value, - } -} - -// Validate validates BorrowInterestFactor values -func (bif BorrowInterestFactor) Validate() error { - if strings.TrimSpace(bif.Denom) == "" { - return fmt.Errorf("borrow interest factor denom cannot be empty") - } - if bif.Value.IsNegative() { - return fmt.Errorf("borrow interest factor value cannot be negative: %s", bif) - } - return nil -} - -// ToResponse converts BorrowInterestFactor to BorrowInterestFactorResponse -func (bif BorrowInterestFactor) ToResponse() BorrowInterestFactorResponse { - return NewBorrowInterestFactorResponse(bif.Denom, bif.Value) -} - -// NewBorrowInterestFactorResponse returns a new BorrowInterestFactorResponse instance -func NewBorrowInterestFactorResponse(denom string, value sdk.Dec) BorrowInterestFactorResponse { - return BorrowInterestFactorResponse{ - Denom: denom, - Value: value.String(), - } -} - -// BorrowInterestFactors is a slice of BorrowInterestFactor, because Amino won't marshal maps -type BorrowInterestFactors []BorrowInterestFactor - -// GetInterestFactor returns a denom's interest factor value -func (bifs BorrowInterestFactors) GetInterestFactor(denom string) (sdk.Dec, bool) { - for _, bif := range bifs { - if bif.Denom == denom { - return bif.Value, true - } - } - return sdk.ZeroDec(), false -} - -// SetInterestFactor sets a denom's interest factor value -func (bifs BorrowInterestFactors) SetInterestFactor(denom string, factor sdk.Dec) BorrowInterestFactors { - for i, bif := range bifs { - if bif.Denom == denom { - bif.Value = factor - bifs[i] = bif - return bifs - } - } - return append(bifs, NewBorrowInterestFactor(denom, factor)) -} - -// RemoveInterestFactor removes a denom's interest factor value -func (bifs BorrowInterestFactors) RemoveInterestFactor(denom string) (BorrowInterestFactors, bool) { - for i, bif := range bifs { - if bif.Denom == denom { - return append(bifs[:i], bifs[i+1:]...), true - } - } - return bifs, false -} - -// Validate validates BorrowInterestFactors -func (bifs BorrowInterestFactors) Validate() error { - for _, bif := range bifs { - if err := bif.Validate(); err != nil { - return err - } - } - return nil -} - -// ToResponse converts BorrowInterestFactors to BorrowInterestFactorResponses -func (bifs BorrowInterestFactors) ToResponse() BorrowInterestFactorResponses { - var bifResponses BorrowInterestFactorResponses - - for _, bif := range bifs { - bifResponses = append(bifResponses, bif.ToResponse()) - } - return bifResponses -} - -// BorrowInterestFactorResponses is a slice of BorrowInterestFactorResponse -type BorrowInterestFactorResponses []BorrowInterestFactorResponse diff --git a/x/hard/types/borrow_test.go b/x/hard/types/borrow_test.go deleted file mode 100644 index d24a3eaf..00000000 --- a/x/hard/types/borrow_test.go +++ /dev/null @@ -1,116 +0,0 @@ -package types_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/0glabs/0g-chain/x/hard/types" -) - -func TestBorrow_NormalizedBorrow(t *testing.T) { - testCases := []struct { - name string - borrow types.Borrow - expect sdk.DecCoins - expectErr string - }{ - { - name: "multiple denoms are calculated correctly", - borrow: types.Borrow{ - Amount: sdk.NewCoins( - sdk.NewInt64Coin("bnb", 100e8), - sdk.NewInt64Coin("xrpb", 1e8), - ), - Index: types.BorrowInterestFactors{ - { - Denom: "xrpb", - Value: sdk.MustNewDecFromStr("1.25"), - }, - { - Denom: "bnb", - Value: sdk.MustNewDecFromStr("2.0"), - }, - }, - }, - expect: sdk.NewDecCoins( - sdk.NewInt64DecCoin("bnb", 50e8), - sdk.NewInt64DecCoin("xrpb", 8e7), - ), - }, - { - name: "empty borrow amount returns empty dec coins", - borrow: types.Borrow{ - Amount: sdk.Coins{}, - Index: types.BorrowInterestFactors{}, - }, - expect: sdk.DecCoins{}, - }, - { - name: "nil borrow amount returns empty dec coins", - borrow: types.Borrow{ - Amount: nil, - Index: types.BorrowInterestFactors{}, - }, - expect: sdk.DecCoins{}, - }, - { - name: "missing indexes return error", - borrow: types.Borrow{ - Amount: sdk.NewCoins( - sdk.NewInt64Coin("bnb", 100e8), - ), - Index: types.BorrowInterestFactors{ - { - Denom: "xrpb", - Value: sdk.MustNewDecFromStr("1.25"), - }, - }, - }, - expectErr: "missing interest factor", - }, - { - name: "invalid indexes return error", - borrow: types.Borrow{ - Amount: sdk.NewCoins( - sdk.NewInt64Coin("bnb", 100e8), - ), - Index: types.BorrowInterestFactors{ - { - Denom: "bnb", - Value: sdk.MustNewDecFromStr("0.999999999999999999"), - }, - }, - }, - expectErr: "< 1", - }, - { - name: "zero indexes return error rather than panicking", - borrow: types.Borrow{ - Amount: sdk.NewCoins( - sdk.NewInt64Coin("bnb", 100e8), - ), - Index: types.BorrowInterestFactors{ - { - Denom: "bnb", - Value: sdk.MustNewDecFromStr("0"), - }, - }, - }, - expectErr: "< 1", - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - nb, err := tc.borrow.NormalizedBorrow() - - require.Equal(t, tc.expect, nb) - - if len(tc.expectErr) > 0 { - require.Error(t, err) - require.Contains(t, err.Error(), tc.expectErr) - } - }) - } -} diff --git a/x/hard/types/codec.go b/x/hard/types/codec.go deleted file mode 100644 index 44c19da4..00000000 --- a/x/hard/types/codec.go +++ /dev/null @@ -1,44 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" -) - -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgDeposit{}, "hard/MsgDeposit", nil) - cdc.RegisterConcrete(&MsgWithdraw{}, "hard/MsgWithdraw", nil) - cdc.RegisterConcrete(&MsgBorrow{}, "hard/MsgBorrow", nil) - cdc.RegisterConcrete(&MsgLiquidate{}, "hard/MsgLiquidate", nil) - cdc.RegisterConcrete(&MsgRepay{}, "hard/MsgRepay", nil) -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgDeposit{}, - &MsgWithdraw{}, - &MsgBorrow{}, - &MsgLiquidate{}, - &MsgRepay{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/hard/types/deposit.go b/x/hard/types/deposit.go deleted file mode 100644 index f73c4dd5..00000000 --- a/x/hard/types/deposit.go +++ /dev/null @@ -1,198 +0,0 @@ -package types - -import ( - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// NewDeposit returns a new deposit -func NewDeposit(depositor sdk.AccAddress, amount sdk.Coins, indexes SupplyInterestFactors) Deposit { - return Deposit{ - Depositor: depositor, - Amount: amount, - Index: indexes, - } -} - -// NormalizedDeposit is the deposit amounts divided by the interest factors. -// -// Multiplying the normalized deposit by the current global factors gives the current deposit (ie including all interest, ie a synced deposit). -// The normalized deposit is effectively how big the deposit would have been if it had been supplied at time 0 and not touched since. -// -// An error is returned if the deposit is in an invalid state. -func (b Deposit) NormalizedDeposit() (sdk.DecCoins, error) { - normalized := sdk.NewDecCoins() - - for _, coin := range b.Amount { - - factor, found := b.Index.GetInterestFactor(coin.Denom) - if !found { - return nil, fmt.Errorf("deposited amount '%s' missing interest factor", coin.Denom) - } - if factor.LT(sdk.OneDec()) { - return nil, fmt.Errorf("interest factor '%s' < 1", coin.Denom) - } - - normalized = normalized.Add( - sdk.NewDecCoinFromDec( - coin.Denom, - sdk.NewDecFromInt(coin.Amount).Quo(factor), - ), - ) - } - return normalized, nil -} - -// Validate deposit validation -func (d Deposit) Validate() error { - if d.Depositor.Empty() { - return fmt.Errorf("depositor cannot be empty") - } - if !d.Amount.IsValid() { - return fmt.Errorf("invalid deposit coins: %s", d.Amount) - } - - if err := d.Index.Validate(); err != nil { - return err - } - - return nil -} - -// ToResponse converts Deposit to DepositResponse -func (d Deposit) ToResponse() DepositResponse { - return NewDepositResponse(d.Depositor, d.Amount, d.Index) -} - -// Deposits is a slice of Deposit -type Deposits []Deposit - -// Validate validates Deposits -func (ds Deposits) Validate() error { - depositDupMap := make(map[string]Deposit) - for _, d := range ds { - if err := d.Validate(); err != nil { - return err - } - dup, ok := depositDupMap[d.Depositor.String()] - if ok { - return fmt.Errorf("duplicate depositor: %s\n%s", d, dup) - } - depositDupMap[d.Depositor.String()] = d - } - return nil -} - -// ToResponse converts Deposits to DepositResponses -func (ds Deposits) ToResponse() DepositResponses { - var dResponses DepositResponses - - for _, d := range ds { - dResponses = append(dResponses, d.ToResponse()) - } - return dResponses -} - -// NewDepositResponse returns a new DepositResponse -func NewDepositResponse(depositor sdk.AccAddress, amount sdk.Coins, indexes SupplyInterestFactors) DepositResponse { - return DepositResponse{ - Depositor: depositor.String(), - Amount: amount, - Index: indexes.ToResponse(), - } -} - -// DepositResponses is a slice of DepositResponse -type DepositResponses []DepositResponse - -// NewSupplyInterestFactor returns a new SupplyInterestFactor instance -func NewSupplyInterestFactor(denom string, value sdk.Dec) SupplyInterestFactor { - return SupplyInterestFactor{ - Denom: denom, - Value: value, - } -} - -// Validate validates SupplyInterestFactor values -func (sif SupplyInterestFactor) Validate() error { - if strings.TrimSpace(sif.Denom) == "" { - return fmt.Errorf("supply interest factor denom cannot be empty") - } - if sif.Value.IsNegative() { - return fmt.Errorf("supply interest factor value cannot be negative: %s", sif) - } - return nil -} - -// ToResponse converts SupplyInterestFactor to SupplyInterestFactorResponse -func (sif SupplyInterestFactor) ToResponse() SupplyInterestFactorResponse { - return NewSupplyInterestFactorResponse(sif.Denom, sif.Value) -} - -// NewSupplyInterestFactorResponse returns a new SupplyInterestFactorResponse instance -func NewSupplyInterestFactorResponse(denom string, value sdk.Dec) SupplyInterestFactorResponse { - return SupplyInterestFactorResponse{ - Denom: denom, - Value: value.String(), - } -} - -// SupplyInterestFactors is a slice of SupplyInterestFactor, because Amino won't marshal maps -type SupplyInterestFactors []SupplyInterestFactor - -// GetInterestFactor returns a denom's interest factor value -func (sifs SupplyInterestFactors) GetInterestFactor(denom string) (sdk.Dec, bool) { - for _, sif := range sifs { - if sif.Denom == denom { - return sif.Value, true - } - } - return sdk.ZeroDec(), false -} - -// SetInterestFactor sets a denom's interest factor value -func (sifs SupplyInterestFactors) SetInterestFactor(denom string, factor sdk.Dec) SupplyInterestFactors { - for i, sif := range sifs { - if sif.Denom == denom { - sif.Value = factor - sifs[i] = sif - return sifs - } - } - return append(sifs, NewSupplyInterestFactor(denom, factor)) -} - -// RemoveInterestFactor removes a denom's interest factor value -func (sifs SupplyInterestFactors) RemoveInterestFactor(denom string) (SupplyInterestFactors, bool) { - for i, sif := range sifs { - if sif.Denom == denom { - return append(sifs[:i], sifs[i+1:]...), true - } - } - return sifs, false -} - -// Validate validates SupplyInterestFactors -func (sifs SupplyInterestFactors) Validate() error { - for _, sif := range sifs { - if err := sif.Validate(); err != nil { - return err - } - } - return nil -} - -// ToResponse converts SupplyInterestFactor to SupplyInterestFactorResponses -func (sifs SupplyInterestFactors) ToResponse() SupplyInterestFactorResponses { - var sifResponses SupplyInterestFactorResponses - - for _, sif := range sifs { - sifResponses = append(sifResponses, sif.ToResponse()) - } - return sifResponses -} - -// SupplyInterestFactorResponses is a slice of SupplyInterestFactorResponse -type SupplyInterestFactorResponses []SupplyInterestFactorResponse diff --git a/x/hard/types/deposit_test.go b/x/hard/types/deposit_test.go deleted file mode 100644 index 069223f7..00000000 --- a/x/hard/types/deposit_test.go +++ /dev/null @@ -1,116 +0,0 @@ -package types_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/0glabs/0g-chain/x/hard/types" -) - -func TestDeposit_NormalizedDeposit(t *testing.T) { - testCases := []struct { - name string - deposit types.Deposit - expect sdk.DecCoins - expectErr string - }{ - { - name: "multiple denoms are calculated correctly", - deposit: types.Deposit{ - Amount: sdk.NewCoins( - sdk.NewInt64Coin("bnb", 100e8), - sdk.NewInt64Coin("xrpb", 1e8), - ), - Index: types.SupplyInterestFactors{ - { - Denom: "xrpb", - Value: sdk.MustNewDecFromStr("1.25"), - }, - { - Denom: "bnb", - Value: sdk.MustNewDecFromStr("2.0"), - }, - }, - }, - expect: sdk.NewDecCoins( - sdk.NewInt64DecCoin("bnb", 50e8), - sdk.NewInt64DecCoin("xrpb", 8e7), - ), - }, - { - name: "empty deposit amount returns empty dec coins", - deposit: types.Deposit{ - Amount: sdk.Coins{}, - Index: types.SupplyInterestFactors{}, - }, - expect: sdk.DecCoins{}, - }, - { - name: "nil deposit amount returns empty dec coins", - deposit: types.Deposit{ - Amount: nil, - Index: types.SupplyInterestFactors{}, - }, - expect: sdk.DecCoins{}, - }, - { - name: "missing indexes return error", - deposit: types.Deposit{ - Amount: sdk.NewCoins( - sdk.NewInt64Coin("bnb", 100e8), - ), - Index: types.SupplyInterestFactors{ - { - Denom: "xrpb", - Value: sdk.MustNewDecFromStr("1.25"), - }, - }, - }, - expectErr: "missing interest factor", - }, - { - name: "invalid indexes return error", - deposit: types.Deposit{ - Amount: sdk.NewCoins( - sdk.NewInt64Coin("bnb", 100e8), - ), - Index: types.SupplyInterestFactors{ - { - Denom: "bnb", - Value: sdk.MustNewDecFromStr("0.999999999999999999"), - }, - }, - }, - expectErr: "< 1", - }, - { - name: "zero indexes return error rather than panicking", - deposit: types.Deposit{ - Amount: sdk.NewCoins( - sdk.NewInt64Coin("bnb", 100e8), - ), - Index: types.SupplyInterestFactors{ - { - Denom: "bnb", - Value: sdk.MustNewDecFromStr("0"), - }, - }, - }, - expectErr: "< 1", - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - nb, err := tc.deposit.NormalizedDeposit() - - require.Equal(t, tc.expect, nb) - - if len(tc.expectErr) > 0 { - require.Error(t, err) - require.Contains(t, err.Error(), tc.expectErr) - } - }) - } -} diff --git a/x/hard/types/errors.go b/x/hard/types/errors.go deleted file mode 100644 index 98cf4c47..00000000 --- a/x/hard/types/errors.go +++ /dev/null @@ -1,70 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -// DONTCOVER - -var ( - // ErrInvalidDepositDenom error for invalid deposit denoms - ErrInvalidDepositDenom = errorsmod.Register(ModuleName, 2, "invalid deposit denom") - // ErrDepositNotFound error for deposit not found - ErrDepositNotFound = errorsmod.Register(ModuleName, 3, "deposit not found") - // ErrInvalidWithdrawAmount error for invalid withdrawal amount - ErrInvalidWithdrawAmount = errorsmod.Register(ModuleName, 4, "invalid withdrawal amount") - // ErrInsufficientModAccountBalance error for module account with innsufficient balance - ErrInsufficientModAccountBalance = errorsmod.Register(ModuleName, 5, "module account has insufficient balance to pay reward") - // ErrInvalidAccountType error for unsupported accounts - ErrInvalidAccountType = errorsmod.Register(ModuleName, 6, "receiver account type not supported") - // ErrAccountNotFound error for accounts that are not found in state - ErrAccountNotFound = errorsmod.Register(ModuleName, 7, "account not found") - // ErrInvalidReceiver error for when sending and receiving accounts don't match - ErrInvalidReceiver = errorsmod.Register(ModuleName, 8, "receiver account must match sender account") - // ErrMoneyMarketNotFound error for money market param not found - ErrMoneyMarketNotFound = errorsmod.Register(ModuleName, 9, "no money market found") - // ErrDepositsNotFound error for no deposits found - ErrDepositsNotFound = errorsmod.Register(ModuleName, 10, "no deposits found") - // ErrInsufficientLoanToValue error for when an attempted borrow exceeds maximum loan-to-value - ErrInsufficientLoanToValue = errorsmod.Register(ModuleName, 11, "not enough collateral supplied by account") - // ErrMarketNotFound error for when a market for the input denom is not found - ErrMarketNotFound = errorsmod.Register(ModuleName, 12, "no market found for denom") - // ErrPriceNotFound error for when a price for the input market is not found - ErrPriceNotFound = errorsmod.Register(ModuleName, 13, "no price found for market") - // ErrBorrowExceedsAvailableBalance for when a requested borrow exceeds available module acc balances - ErrBorrowExceedsAvailableBalance = errorsmod.Register(ModuleName, 14, "exceeds module account balance") - // ErrBorrowedCoinsNotFound error for when the total amount of borrowed coins cannot be found - ErrBorrowedCoinsNotFound = errorsmod.Register(ModuleName, 15, "no borrowed coins found") - // ErrNegativeBorrowedCoins error for when substracting coins from the total borrowed balance results in a negative amount - ErrNegativeBorrowedCoins = errorsmod.Register(ModuleName, 16, "subtraction results in negative borrow amount") - // ErrGreaterThanAssetBorrowLimit error for when a proposed borrow would increase borrowed amount over the asset's global borrow limit - ErrGreaterThanAssetBorrowLimit = errorsmod.Register(ModuleName, 17, "fails global asset borrow limit validation") - // ErrBorrowEmptyCoins error for when you cannot borrow empty coins - ErrBorrowEmptyCoins = errorsmod.Register(ModuleName, 18, "cannot borrow zero coins") - // ErrBorrowNotFound error for when a user's borrow is not found in the store - ErrBorrowNotFound = errorsmod.Register(ModuleName, 19, "borrow not found") - // ErrPreviousAccrualTimeNotFound error for no previous accrual time found in store - ErrPreviousAccrualTimeNotFound = errorsmod.Register(ModuleName, 20, "no previous accrual time found") - // ErrInsufficientBalanceForRepay error for when requested repay exceeds user's balance - ErrInsufficientBalanceForRepay = errorsmod.Register(ModuleName, 21, "insufficient balance") - // ErrBorrowNotLiquidatable error for when a borrow is within valid LTV and cannot be liquidated - ErrBorrowNotLiquidatable = errorsmod.Register(ModuleName, 22, "borrow not liquidatable") - // ErrInsufficientCoins error for when there are not enough coins for the operation - ErrInsufficientCoins = errorsmod.Register(ModuleName, 23, "unrecoverable state - insufficient coins") - // ErrInsufficientBalanceForBorrow error for when the requested borrow exceeds user's balance - ErrInsufficientBalanceForBorrow = errorsmod.Register(ModuleName, 24, "insufficient balance") - // ErrSuppliedCoinsNotFound error for when the total amount of supplied coins cannot be found - ErrSuppliedCoinsNotFound = errorsmod.Register(ModuleName, 25, "no supplied coins found") - // ErrNegativeSuppliedCoins error for when substracting coins from the total supplied balance results in a negative amount - ErrNegativeSuppliedCoins = errorsmod.Register(ModuleName, 26, "subtraction results in negative supplied amount") - // ErrInvalidWithdrawDenom error for when user attempts to withdraw a non-supplied coin type - ErrInvalidWithdrawDenom = errorsmod.Register(ModuleName, 27, "no coins of this type deposited") - // ErrInvalidRepaymentDenom error for when user attempts to repay a non-borrowed coin type - ErrInvalidRepaymentDenom = errorsmod.Register(ModuleName, 28, "no coins of this type borrowed") - // ErrInvalidIndexFactorDenom error for when index factor denom cannot be found - ErrInvalidIndexFactorDenom = errorsmod.Register(ModuleName, 29, "no index factor found for denom") - // ErrBelowMinimumBorrowValue error for when a proposed borrow position is less than the minimum USD value - ErrBelowMinimumBorrowValue = errorsmod.Register(ModuleName, 30, "invalid proposed borrow value") - // ErrExceedsProtocolBorrowableBalance for when a requested borrow exceeds the module account's borrowable balance - ErrExceedsProtocolBorrowableBalance = errorsmod.Register(ModuleName, 31, "exceeds borrowable module account balance") - // ErrReservesExceedCash for when the protocol is insolvent because available reserves exceeds available cash - ErrReservesExceedCash = errorsmod.Register(ModuleName, 32, "insolvency - protocol reserves exceed available cash") -) diff --git a/x/hard/types/events.go b/x/hard/types/events.go deleted file mode 100644 index d0b1386e..00000000 --- a/x/hard/types/events.go +++ /dev/null @@ -1,25 +0,0 @@ -package types - -// Event types for hard module -const ( - EventTypeHardDeposit = "hard_deposit" - EventTypeHardWithdrawal = "hard_withdrawal" - EventTypeHardBorrow = "hard_borrow" - EventTypeHardLiquidation = "hard_liquidation" - EventTypeHardRepay = "hard_repay" - AttributeValueCategory = ModuleName - AttributeKeyDeposit = "deposit" - AttributeKeyDepositDenom = "deposit_denom" - AttributeKeyDepositCoins = "deposit_coins" - AttributeKeyDepositor = "depositor" - AttributeKeyBorrow = "borrow" - AttributeKeyBorrower = "borrower" - AttributeKeyBorrowCoins = "borrow_coins" - AttributeKeySender = "sender" - AttributeKeyRepayCoins = "repay_coins" - AttributeKeyLiquidatedOwner = "liquidated_owner" - AttributeKeyLiquidatedCoins = "liquidated_coins" - AttributeKeyKeeper = "keeper" - AttributeKeyKeeperRewardCoins = "keeper_reward_coins" - AttributeKeyOwner = "owner" -) diff --git a/x/hard/types/expected_keepers.go b/x/hard/types/expected_keepers.go deleted file mode 100644 index c21e4cf1..00000000 --- a/x/hard/types/expected_keepers.go +++ /dev/null @@ -1,60 +0,0 @@ -package types // noalias - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - pftypes "github.com/0glabs/0g-chain/x/pricefeed/types" -) - -// BankKeeper defines the expected bank keeper -type BankKeeper interface { - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - - GetSupply(ctx sdk.Context, denom string) sdk.Coin - GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins -} - -// AccountKeeper defines the expected keeper interface for interacting with account -type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI - SetAccount(ctx sdk.Context, acc authtypes.AccountI) - - GetModuleAddress(name string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, name string) authtypes.ModuleAccountI -} - -// StakingKeeper defines the expected keeper interface for the staking keeper -type StakingKeeper interface { - IterateLastValidators(ctx sdk.Context, fn func(index int64, validator stakingtypes.ValidatorI) (stop bool)) - IterateValidators(sdk.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool)) - IterateAllDelegations(ctx sdk.Context, cb func(delegation stakingtypes.Delegation) (stop bool)) - GetBondedPool(ctx sdk.Context) (bondedPool authtypes.ModuleAccountI) - BondDenom(ctx sdk.Context) (res string) -} - -// PricefeedKeeper defines the expected interface for the pricefeed -type PricefeedKeeper interface { - GetCurrentPrice(sdk.Context, string) (pftypes.CurrentPrice, error) -} - -// AuctionKeeper expected interface for the auction keeper (noalias) -type AuctionKeeper interface { - StartCollateralAuction(ctx sdk.Context, seller string, lot sdk.Coin, maxBid sdk.Coin, lotReturnAddrs []sdk.AccAddress, lotReturnWeights []sdkmath.Int, debt sdk.Coin) (uint64, error) -} - -// HARDHooks event hooks for other keepers to run code in response to HARD modifications -type HARDHooks interface { - AfterDepositCreated(ctx sdk.Context, deposit Deposit) - BeforeDepositModified(ctx sdk.Context, deposit Deposit) - AfterDepositModified(ctx sdk.Context, deposit Deposit) - AfterBorrowCreated(ctx sdk.Context, borrow Borrow) - BeforeBorrowModified(ctx sdk.Context, borrow Borrow) - AfterBorrowModified(ctx sdk.Context, borrow Borrow) -} diff --git a/x/hard/types/genesis.go b/x/hard/types/genesis.go deleted file mode 100644 index e138b16a..00000000 --- a/x/hard/types/genesis.go +++ /dev/null @@ -1,99 +0,0 @@ -package types - -import ( - "fmt" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// NewGenesisState returns a new genesis state -func NewGenesisState( - params Params, prevAccumulationTimes GenesisAccumulationTimes, deposits Deposits, - borrows Borrows, totalSupplied, totalBorrowed, totalReserves sdk.Coins, -) GenesisState { - return GenesisState{ - Params: params, - PreviousAccumulationTimes: prevAccumulationTimes, - Deposits: deposits, - Borrows: borrows, - TotalSupplied: totalSupplied, - TotalBorrowed: totalBorrowed, - TotalReserves: totalReserves, - } -} - -// DefaultGenesisState returns a default genesis state -func DefaultGenesisState() GenesisState { - return GenesisState{ - Params: DefaultParams(), - PreviousAccumulationTimes: DefaultAccumulationTimes, - Deposits: DefaultDeposits, - Borrows: DefaultBorrows, - TotalSupplied: DefaultTotalSupplied, - TotalBorrowed: DefaultTotalBorrowed, - TotalReserves: DefaultTotalReserves, - } -} - -// Validate performs basic validation of genesis data returning an -// error for any failed validation criteria. -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - if err := gs.PreviousAccumulationTimes.Validate(); err != nil { - return err - } - if err := gs.Deposits.Validate(); err != nil { - return err - } - if err := gs.Borrows.Validate(); err != nil { - return err - } - - if !gs.TotalSupplied.IsValid() { - return fmt.Errorf("invalid total supplied coins: %s", gs.TotalSupplied) - } - if !gs.TotalBorrowed.IsValid() { - return fmt.Errorf("invalid total borrowed coins: %s", gs.TotalBorrowed) - } - if !gs.TotalReserves.IsValid() { - return fmt.Errorf("invalid total reserves coins: %s", gs.TotalReserves) - } - return nil -} - -// NewGenesisAccumulationTime returns a new GenesisAccumulationTime -func NewGenesisAccumulationTime(ctype string, prevTime time.Time, supplyFactor, borrowFactor sdk.Dec) GenesisAccumulationTime { - return GenesisAccumulationTime{ - CollateralType: ctype, - PreviousAccumulationTime: prevTime, - SupplyInterestFactor: supplyFactor, - BorrowInterestFactor: borrowFactor, - } -} - -// GenesisAccumulationTimes slice of GenesisAccumulationTime -type GenesisAccumulationTimes []GenesisAccumulationTime - -// Validate performs validation of GenesisAccumulationTimes -func (gats GenesisAccumulationTimes) Validate() error { - for _, gat := range gats { - if err := gat.Validate(); err != nil { - return err - } - } - return nil -} - -// Validate performs validation of GenesisAccumulationTime -func (gat GenesisAccumulationTime) Validate() error { - if gat.SupplyInterestFactor.LT(sdk.OneDec()) { - return fmt.Errorf("supply interest factor should be ≥ 1.0, is %s for %s", gat.SupplyInterestFactor, gat.CollateralType) - } - if gat.BorrowInterestFactor.LT(sdk.OneDec()) { - return fmt.Errorf("borrow interest factor should be ≥ 1.0, is %s for %s", gat.BorrowInterestFactor, gat.CollateralType) - } - return nil -} diff --git a/x/hard/types/genesis.pb.go b/x/hard/types/genesis.pb.go deleted file mode 100644 index 50e0cdf2..00000000 --- a/x/hard/types/genesis.pb.go +++ /dev/null @@ -1,1041 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/hard/v1beta1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// GenesisState defines the hard module's genesis state. -type GenesisState struct { - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - PreviousAccumulationTimes GenesisAccumulationTimes `protobuf:"bytes,2,rep,name=previous_accumulation_times,json=previousAccumulationTimes,proto3,castrepeated=GenesisAccumulationTimes" json:"previous_accumulation_times"` - Deposits Deposits `protobuf:"bytes,3,rep,name=deposits,proto3,castrepeated=Deposits" json:"deposits"` - Borrows Borrows `protobuf:"bytes,4,rep,name=borrows,proto3,castrepeated=Borrows" json:"borrows"` - TotalSupplied github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,5,rep,name=total_supplied,json=totalSupplied,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"total_supplied"` - TotalBorrowed github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,6,rep,name=total_borrowed,json=totalBorrowed,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"total_borrowed"` - TotalReserves github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,7,rep,name=total_reserves,json=totalReserves,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"total_reserves"` -} - -func (m *GenesisState) Reset() { *m = GenesisState{} } -func (m *GenesisState) String() string { return proto.CompactTextString(m) } -func (*GenesisState) ProtoMessage() {} -func (*GenesisState) Descriptor() ([]byte, []int) { - return fileDescriptor_20a1f6c2cf728e74, []int{0} -} -func (m *GenesisState) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisState) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisState.Merge(m, src) -} -func (m *GenesisState) XXX_Size() int { - return m.Size() -} -func (m *GenesisState) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisState.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisState proto.InternalMessageInfo - -func (m *GenesisState) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -func (m *GenesisState) GetPreviousAccumulationTimes() GenesisAccumulationTimes { - if m != nil { - return m.PreviousAccumulationTimes - } - return nil -} - -func (m *GenesisState) GetDeposits() Deposits { - if m != nil { - return m.Deposits - } - return nil -} - -func (m *GenesisState) GetBorrows() Borrows { - if m != nil { - return m.Borrows - } - return nil -} - -func (m *GenesisState) GetTotalSupplied() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.TotalSupplied - } - return nil -} - -func (m *GenesisState) GetTotalBorrowed() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.TotalBorrowed - } - return nil -} - -func (m *GenesisState) GetTotalReserves() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.TotalReserves - } - return nil -} - -// GenesisAccumulationTime stores the previous distribution time and its corresponding denom. -type GenesisAccumulationTime struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - PreviousAccumulationTime time.Time `protobuf:"bytes,2,opt,name=previous_accumulation_time,json=previousAccumulationTime,proto3,stdtime" json:"previous_accumulation_time"` - SupplyInterestFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=supply_interest_factor,json=supplyInterestFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"supply_interest_factor"` - BorrowInterestFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=borrow_interest_factor,json=borrowInterestFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"borrow_interest_factor"` -} - -func (m *GenesisAccumulationTime) Reset() { *m = GenesisAccumulationTime{} } -func (m *GenesisAccumulationTime) String() string { return proto.CompactTextString(m) } -func (*GenesisAccumulationTime) ProtoMessage() {} -func (*GenesisAccumulationTime) Descriptor() ([]byte, []int) { - return fileDescriptor_20a1f6c2cf728e74, []int{1} -} -func (m *GenesisAccumulationTime) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisAccumulationTime) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisAccumulationTime.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisAccumulationTime) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisAccumulationTime.Merge(m, src) -} -func (m *GenesisAccumulationTime) XXX_Size() int { - return m.Size() -} -func (m *GenesisAccumulationTime) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisAccumulationTime.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisAccumulationTime proto.InternalMessageInfo - -func (m *GenesisAccumulationTime) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -func (m *GenesisAccumulationTime) GetPreviousAccumulationTime() time.Time { - if m != nil { - return m.PreviousAccumulationTime - } - return time.Time{} -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "kava.hard.v1beta1.GenesisState") - proto.RegisterType((*GenesisAccumulationTime)(nil), "kava.hard.v1beta1.GenesisAccumulationTime") -} - -func init() { proto.RegisterFile("kava/hard/v1beta1/genesis.proto", fileDescriptor_20a1f6c2cf728e74) } - -var fileDescriptor_20a1f6c2cf728e74 = []byte{ - // 595 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x94, 0x4d, 0x6f, 0xd3, 0x30, - 0x18, 0xc7, 0x9b, 0x75, 0x2f, 0xc5, 0x83, 0x0d, 0xa2, 0x09, 0xdc, 0x82, 0x92, 0x6a, 0x07, 0x56, - 0x21, 0x35, 0xe9, 0xc6, 0x81, 0x0b, 0x97, 0x85, 0x8a, 0x97, 0x1b, 0xca, 0x7a, 0xe2, 0x12, 0x39, - 0xa9, 0x97, 0x5a, 0x4b, 0xe2, 0xc8, 0x76, 0x0a, 0xfd, 0x0e, 0x08, 0xed, 0x73, 0x70, 0xe6, 0x13, - 0x70, 0xda, 0x71, 0xe2, 0x84, 0x38, 0x6c, 0xa8, 0xfd, 0x22, 0x28, 0xb6, 0xdb, 0x0e, 0xb5, 0x95, - 0x38, 0xb0, 0x53, 0x6b, 0xfb, 0xff, 0xfc, 0x7f, 0x8f, 0x1f, 0x3f, 0x4f, 0x80, 0x7d, 0x86, 0x86, - 0xc8, 0x1d, 0x20, 0xd6, 0x77, 0x87, 0x87, 0x21, 0x16, 0xe8, 0xd0, 0x8d, 0x71, 0x86, 0x39, 0xe1, - 0x4e, 0xce, 0xa8, 0xa0, 0xe6, 0x83, 0x52, 0xe0, 0x94, 0x02, 0x47, 0x0b, 0x1a, 0x56, 0x44, 0x79, - 0x4a, 0xb9, 0x1b, 0x22, 0x8e, 0x67, 0x51, 0x11, 0x25, 0x99, 0x0a, 0x69, 0xd4, 0xd5, 0x79, 0x20, - 0x57, 0xae, 0x5a, 0xe8, 0xa3, 0xbd, 0x98, 0xc6, 0x54, 0xed, 0x97, 0xff, 0xf4, 0xae, 0x1d, 0x53, - 0x1a, 0x27, 0xd8, 0x95, 0xab, 0xb0, 0x38, 0x75, 0x05, 0x49, 0x31, 0x17, 0x28, 0xcd, 0xb5, 0xe0, - 0xc9, 0x62, 0x96, 0x32, 0x23, 0x79, 0xba, 0xff, 0x7d, 0x03, 0xdc, 0x7d, 0xa3, 0x92, 0x3e, 0x11, - 0x48, 0x60, 0xf3, 0x05, 0xd8, 0xcc, 0x11, 0x43, 0x29, 0x87, 0x46, 0xd3, 0x68, 0x6d, 0x1f, 0xd5, - 0x9d, 0x85, 0x4b, 0x38, 0xef, 0xa5, 0xc0, 0x5b, 0xbf, 0xb8, 0xb2, 0x2b, 0xbe, 0x96, 0x9b, 0x9f, - 0x0d, 0xf0, 0x38, 0x67, 0x78, 0x48, 0x68, 0xc1, 0x03, 0x14, 0x45, 0x45, 0x5a, 0x24, 0x48, 0x10, - 0x9a, 0x05, 0x32, 0x23, 0xb8, 0xd6, 0xac, 0xb6, 0xb6, 0x8f, 0x9e, 0x2d, 0xb1, 0xd3, 0xfc, 0xe3, - 0x1b, 0x31, 0x3d, 0x92, 0x62, 0xaf, 0x59, 0xfa, 0x7f, 0xbd, 0xb6, 0xe1, 0x0a, 0x01, 0xf7, 0xeb, - 0x53, 0xe0, 0xc2, 0x91, 0xf9, 0x16, 0xd4, 0xfa, 0x38, 0xa7, 0x9c, 0x08, 0x0e, 0xab, 0x12, 0xdd, - 0x58, 0x82, 0xee, 0x2a, 0x89, 0x77, 0x5f, 0xa3, 0x6a, 0x7a, 0x83, 0xfb, 0xb3, 0x68, 0xb3, 0x0b, - 0xb6, 0x42, 0xca, 0x18, 0xfd, 0xc8, 0xe1, 0xba, 0x34, 0x5a, 0x56, 0x12, 0x4f, 0x2a, 0xbc, 0x5d, - 0xed, 0xb3, 0xa5, 0xd6, 0xdc, 0x9f, 0x86, 0x9a, 0x0c, 0xec, 0x08, 0x2a, 0x50, 0x12, 0xf0, 0x22, - 0xcf, 0x13, 0x82, 0xfb, 0x70, 0x43, 0x9b, 0xe9, 0x47, 0x2e, 0x3b, 0x62, 0x66, 0xf7, 0x8a, 0x92, - 0xcc, 0xeb, 0x68, 0xb3, 0x56, 0x4c, 0xc4, 0xa0, 0x08, 0x9d, 0x88, 0xa6, 0xba, 0x23, 0xf4, 0x4f, - 0x9b, 0xf7, 0xcf, 0x5c, 0x31, 0xca, 0x31, 0x97, 0x01, 0xdc, 0xbf, 0x27, 0x11, 0x27, 0x9a, 0x30, - 0x67, 0xaa, 0x24, 0x70, 0x1f, 0x6e, 0xde, 0x16, 0xd3, 0xd3, 0x84, 0x39, 0x93, 0x61, 0x8e, 0xd9, - 0x10, 0x73, 0xb8, 0x75, 0x5b, 0x4c, 0x5f, 0x13, 0xf6, 0xbf, 0x54, 0xc1, 0xa3, 0x15, 0x3d, 0x62, - 0x1e, 0x80, 0xdd, 0x88, 0x26, 0x09, 0x12, 0x98, 0xa1, 0x24, 0x28, 0x4d, 0x64, 0x63, 0xdf, 0xf1, - 0x77, 0xe6, 0xdb, 0xbd, 0x51, 0x8e, 0xcd, 0x10, 0x34, 0x56, 0xb7, 0x2f, 0x5c, 0x93, 0xc3, 0xd0, - 0x70, 0xd4, 0xb4, 0x39, 0xd3, 0x69, 0x73, 0x7a, 0xd3, 0x69, 0xf3, 0x6a, 0xe5, 0x2d, 0xce, 0xaf, - 0x6d, 0xc3, 0x87, 0xab, 0xba, 0xd2, 0x64, 0xe0, 0xa1, 0x7c, 0xfe, 0x51, 0x40, 0x32, 0x81, 0x19, - 0xe6, 0x22, 0x38, 0x45, 0x91, 0xa0, 0x0c, 0x56, 0xcb, 0x9c, 0xbc, 0x97, 0xa5, 0xc7, 0xaf, 0x2b, - 0xfb, 0xe9, 0x3f, 0x54, 0xa2, 0x8b, 0xa3, 0x1f, 0xdf, 0xda, 0x40, 0x57, 0xb5, 0x8b, 0x23, 0x7f, - 0x4f, 0x79, 0xbf, 0xd3, 0xd6, 0xaf, 0xa5, 0x73, 0xc9, 0x54, 0xcf, 0xbf, 0xc0, 0x5c, 0xff, 0x1f, - 0x4c, 0xe5, 0xfd, 0x37, 0xd3, 0x3b, 0xbe, 0x18, 0x5b, 0xc6, 0xe5, 0xd8, 0x32, 0x7e, 0x8f, 0x2d, - 0xe3, 0x7c, 0x62, 0x55, 0x2e, 0x27, 0x56, 0xe5, 0xe7, 0xc4, 0xaa, 0x7c, 0x38, 0xb8, 0x41, 0xe9, - 0xc4, 0x09, 0x0a, 0xb9, 0xdb, 0x89, 0xdb, 0xd1, 0x00, 0x91, 0xcc, 0xfd, 0xa4, 0xbe, 0x52, 0x12, - 0x15, 0x6e, 0xca, 0x12, 0x3f, 0xff, 0x13, 0x00, 0x00, 0xff, 0xff, 0x1f, 0x65, 0x16, 0xde, 0x65, - 0x05, 0x00, 0x00, -} - -func (m *GenesisState) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.TotalReserves) > 0 { - for iNdEx := len(m.TotalReserves) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TotalReserves[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - } - if len(m.TotalBorrowed) > 0 { - for iNdEx := len(m.TotalBorrowed) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TotalBorrowed[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - } - } - if len(m.TotalSupplied) > 0 { - for iNdEx := len(m.TotalSupplied) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TotalSupplied[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - } - if len(m.Borrows) > 0 { - for iNdEx := len(m.Borrows) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Borrows[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.Deposits) > 0 { - for iNdEx := len(m.Deposits) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposits[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.PreviousAccumulationTimes) > 0 { - for iNdEx := len(m.PreviousAccumulationTimes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.PreviousAccumulationTimes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *GenesisAccumulationTime) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisAccumulationTime) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisAccumulationTime) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.BorrowInterestFactor.Size() - i -= size - if _, err := m.BorrowInterestFactor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.SupplyInterestFactor.Size() - i -= size - if _, err := m.SupplyInterestFactor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - n2, err2 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.PreviousAccumulationTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.PreviousAccumulationTime):]) - if err2 != nil { - return 0, err2 - } - i -= n2 - i = encodeVarintGenesis(dAtA, i, uint64(n2)) - i-- - dAtA[i] = 0x12 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *GenesisState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.PreviousAccumulationTimes) > 0 { - for _, e := range m.PreviousAccumulationTimes { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.Deposits) > 0 { - for _, e := range m.Deposits { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.Borrows) > 0 { - for _, e := range m.Borrows { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.TotalSupplied) > 0 { - for _, e := range m.TotalSupplied { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.TotalBorrowed) > 0 { - for _, e := range m.TotalBorrowed { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.TotalReserves) > 0 { - for _, e := range m.TotalReserves { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func (m *GenesisAccumulationTime) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.PreviousAccumulationTime) - n += 1 + l + sovGenesis(uint64(l)) - l = m.SupplyInterestFactor.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.BorrowInterestFactor.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *GenesisState) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PreviousAccumulationTimes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PreviousAccumulationTimes = append(m.PreviousAccumulationTimes, GenesisAccumulationTime{}) - if err := m.PreviousAccumulationTimes[len(m.PreviousAccumulationTimes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposits", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Deposits = append(m.Deposits, Deposit{}) - if err := m.Deposits[len(m.Deposits)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Borrows", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Borrows = append(m.Borrows, Borrow{}) - if err := m.Borrows[len(m.Borrows)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalSupplied", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TotalSupplied = append(m.TotalSupplied, types.Coin{}) - if err := m.TotalSupplied[len(m.TotalSupplied)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalBorrowed", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TotalBorrowed = append(m.TotalBorrowed, types.Coin{}) - if err := m.TotalBorrowed[len(m.TotalBorrowed)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalReserves", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TotalReserves = append(m.TotalReserves, types.Coin{}) - if err := m.TotalReserves[len(m.TotalReserves)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *GenesisAccumulationTime) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisAccumulationTime: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisAccumulationTime: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PreviousAccumulationTime", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.PreviousAccumulationTime, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SupplyInterestFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.SupplyInterestFactor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BorrowInterestFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BorrowInterestFactor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/hard/types/genesis_test.go b/x/hard/types/genesis_test.go deleted file mode 100644 index 45295f89..00000000 --- a/x/hard/types/genesis_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package types_test - -import ( - "strings" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/hard/types" -) - -const ( - USDX_CF = 1000000 - KAVA_CF = 1000000 - BTCB_CF = 100000000 - BNB_CF = 100000000 - BUSD_CF = 100000000 -) - -type GenesisTestSuite struct { - suite.Suite -} - -func (suite *GenesisTestSuite) TestGenesisValidation() { - type args struct { - params types.Params - gats types.GenesisAccumulationTimes - deps types.Deposits - brws types.Borrows - ts sdk.Coins - tb sdk.Coins - tr sdk.Coins - } - testCases := []struct { - name string - args args - expectPass bool - expectedErr string - }{ - { - name: "default", - args: args{ - params: types.DefaultParams(), - gats: types.DefaultAccumulationTimes, - deps: types.DefaultDeposits, - brws: types.DefaultBorrows, - ts: types.DefaultTotalSupplied, - tb: types.DefaultTotalBorrowed, - tr: types.DefaultTotalReserves, - }, - expectPass: true, - expectedErr: "", - }, - { - name: "valid", - args: args{ - params: types.NewParams( - types.MoneyMarkets{ - types.NewMoneyMarket("usdx", types.NewBorrowLimit(true, sdk.MustNewDecFromStr("100000000000"), sdk.MustNewDecFromStr("1")), "usdx:usd", sdkmath.NewInt(USDX_CF), types.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - }, - sdk.MustNewDecFromStr("10"), - ), - gats: types.GenesisAccumulationTimes{ - types.NewGenesisAccumulationTime("usdx", time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), sdk.OneDec(), sdk.OneDec()), - }, - deps: types.DefaultDeposits, - brws: types.DefaultBorrows, - ts: sdk.Coins{}, - tb: sdk.Coins{}, - tr: sdk.Coins{}, - }, - expectPass: true, - expectedErr: "", - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - gs := types.NewGenesisState(tc.args.params, tc.args.gats, tc.args.deps, tc.args.brws, tc.args.ts, tc.args.tb, tc.args.tr) - err := gs.Validate() - if tc.expectPass { - suite.NoError(err) - } else { - suite.Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.expectedErr)) - } - }) - } -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(GenesisTestSuite)) -} diff --git a/x/hard/types/hard.pb.go b/x/hard/types/hard.pb.go deleted file mode 100644 index e94d02c3..00000000 --- a/x/hard/types/hard.pb.go +++ /dev/null @@ -1,2560 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/hard/v1beta1/hard.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// Params defines the parameters for the hard module. -type Params struct { - MoneyMarkets MoneyMarkets `protobuf:"bytes,1,rep,name=money_markets,json=moneyMarkets,proto3,castrepeated=MoneyMarkets" json:"money_markets"` - MinimumBorrowUSDValue github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=minimum_borrow_usd_value,json=minimumBorrowUsdValue,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"minimum_borrow_usd_value"` -} - -func (m *Params) Reset() { *m = Params{} } -func (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_23a5de800263a2ff, []int{0} -} -func (m *Params) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Params.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Params) XXX_Merge(src proto.Message) { - xxx_messageInfo_Params.Merge(m, src) -} -func (m *Params) XXX_Size() int { - return m.Size() -} -func (m *Params) XXX_DiscardUnknown() { - xxx_messageInfo_Params.DiscardUnknown(m) -} - -var xxx_messageInfo_Params proto.InternalMessageInfo - -// MoneyMarket is a money market for an individual asset. -type MoneyMarket struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - BorrowLimit BorrowLimit `protobuf:"bytes,2,opt,name=borrow_limit,json=borrowLimit,proto3" json:"borrow_limit"` - SpotMarketID string `protobuf:"bytes,3,opt,name=spot_market_id,json=spotMarketId,proto3" json:"spot_market_id,omitempty"` - ConversionFactor github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,4,opt,name=conversion_factor,json=conversionFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"conversion_factor"` - InterestRateModel InterestRateModel `protobuf:"bytes,5,opt,name=interest_rate_model,json=interestRateModel,proto3" json:"interest_rate_model"` - ReserveFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,6,opt,name=reserve_factor,json=reserveFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"reserve_factor"` - KeeperRewardPercentage github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,7,opt,name=keeper_reward_percentage,json=keeperRewardPercentage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"keeper_reward_percentage"` -} - -func (m *MoneyMarket) Reset() { *m = MoneyMarket{} } -func (m *MoneyMarket) String() string { return proto.CompactTextString(m) } -func (*MoneyMarket) ProtoMessage() {} -func (*MoneyMarket) Descriptor() ([]byte, []int) { - return fileDescriptor_23a5de800263a2ff, []int{1} -} -func (m *MoneyMarket) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MoneyMarket) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MoneyMarket.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MoneyMarket) XXX_Merge(src proto.Message) { - xxx_messageInfo_MoneyMarket.Merge(m, src) -} -func (m *MoneyMarket) XXX_Size() int { - return m.Size() -} -func (m *MoneyMarket) XXX_DiscardUnknown() { - xxx_messageInfo_MoneyMarket.DiscardUnknown(m) -} - -var xxx_messageInfo_MoneyMarket proto.InternalMessageInfo - -// BorrowLimit enforces restrictions on a money market. -type BorrowLimit struct { - HasMaxLimit bool `protobuf:"varint,1,opt,name=has_max_limit,json=hasMaxLimit,proto3" json:"has_max_limit"` - MaximumLimit github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=maximum_limit,json=maximumLimit,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"maximum_limit"` - LoanToValue github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=loan_to_value,json=loanToValue,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"loan_to_value"` -} - -func (m *BorrowLimit) Reset() { *m = BorrowLimit{} } -func (m *BorrowLimit) String() string { return proto.CompactTextString(m) } -func (*BorrowLimit) ProtoMessage() {} -func (*BorrowLimit) Descriptor() ([]byte, []int) { - return fileDescriptor_23a5de800263a2ff, []int{2} -} -func (m *BorrowLimit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *BorrowLimit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_BorrowLimit.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *BorrowLimit) XXX_Merge(src proto.Message) { - xxx_messageInfo_BorrowLimit.Merge(m, src) -} -func (m *BorrowLimit) XXX_Size() int { - return m.Size() -} -func (m *BorrowLimit) XXX_DiscardUnknown() { - xxx_messageInfo_BorrowLimit.DiscardUnknown(m) -} - -var xxx_messageInfo_BorrowLimit proto.InternalMessageInfo - -// InterestRateModel contains information about an asset's interest rate. -type InterestRateModel struct { - BaseRateAPY github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=base_rate_apy,json=baseRateApy,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"base_rate_apy"` - BaseMultiplier github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=base_multiplier,json=baseMultiplier,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"base_multiplier"` - Kink github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=kink,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"kink"` - JumpMultiplier github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=jump_multiplier,json=jumpMultiplier,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"jump_multiplier"` -} - -func (m *InterestRateModel) Reset() { *m = InterestRateModel{} } -func (m *InterestRateModel) String() string { return proto.CompactTextString(m) } -func (*InterestRateModel) ProtoMessage() {} -func (*InterestRateModel) Descriptor() ([]byte, []int) { - return fileDescriptor_23a5de800263a2ff, []int{3} -} -func (m *InterestRateModel) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *InterestRateModel) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_InterestRateModel.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *InterestRateModel) XXX_Merge(src proto.Message) { - xxx_messageInfo_InterestRateModel.Merge(m, src) -} -func (m *InterestRateModel) XXX_Size() int { - return m.Size() -} -func (m *InterestRateModel) XXX_DiscardUnknown() { - xxx_messageInfo_InterestRateModel.DiscardUnknown(m) -} - -var xxx_messageInfo_InterestRateModel proto.InternalMessageInfo - -// Deposit defines an amount of coins deposited into a hard module account. -type Deposit struct { - Depositor github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=depositor,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"depositor,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` - Index SupplyInterestFactors `protobuf:"bytes,3,rep,name=index,proto3,castrepeated=SupplyInterestFactors" json:"index"` -} - -func (m *Deposit) Reset() { *m = Deposit{} } -func (m *Deposit) String() string { return proto.CompactTextString(m) } -func (*Deposit) ProtoMessage() {} -func (*Deposit) Descriptor() ([]byte, []int) { - return fileDescriptor_23a5de800263a2ff, []int{4} -} -func (m *Deposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Deposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Deposit.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Deposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_Deposit.Merge(m, src) -} -func (m *Deposit) XXX_Size() int { - return m.Size() -} -func (m *Deposit) XXX_DiscardUnknown() { - xxx_messageInfo_Deposit.DiscardUnknown(m) -} - -var xxx_messageInfo_Deposit proto.InternalMessageInfo - -// Borrow defines an amount of coins borrowed from a hard module account. -type Borrow struct { - Borrower github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=borrower,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"borrower,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` - Index BorrowInterestFactors `protobuf:"bytes,3,rep,name=index,proto3,castrepeated=BorrowInterestFactors" json:"index"` -} - -func (m *Borrow) Reset() { *m = Borrow{} } -func (m *Borrow) String() string { return proto.CompactTextString(m) } -func (*Borrow) ProtoMessage() {} -func (*Borrow) Descriptor() ([]byte, []int) { - return fileDescriptor_23a5de800263a2ff, []int{5} -} -func (m *Borrow) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Borrow) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Borrow.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Borrow) XXX_Merge(src proto.Message) { - xxx_messageInfo_Borrow.Merge(m, src) -} -func (m *Borrow) XXX_Size() int { - return m.Size() -} -func (m *Borrow) XXX_DiscardUnknown() { - xxx_messageInfo_Borrow.DiscardUnknown(m) -} - -var xxx_messageInfo_Borrow proto.InternalMessageInfo - -// SupplyInterestFactor defines an individual borrow interest factor. -type SupplyInterestFactor struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Value github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=value,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"value"` -} - -func (m *SupplyInterestFactor) Reset() { *m = SupplyInterestFactor{} } -func (m *SupplyInterestFactor) String() string { return proto.CompactTextString(m) } -func (*SupplyInterestFactor) ProtoMessage() {} -func (*SupplyInterestFactor) Descriptor() ([]byte, []int) { - return fileDescriptor_23a5de800263a2ff, []int{6} -} -func (m *SupplyInterestFactor) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *SupplyInterestFactor) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SupplyInterestFactor.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *SupplyInterestFactor) XXX_Merge(src proto.Message) { - xxx_messageInfo_SupplyInterestFactor.Merge(m, src) -} -func (m *SupplyInterestFactor) XXX_Size() int { - return m.Size() -} -func (m *SupplyInterestFactor) XXX_DiscardUnknown() { - xxx_messageInfo_SupplyInterestFactor.DiscardUnknown(m) -} - -var xxx_messageInfo_SupplyInterestFactor proto.InternalMessageInfo - -// BorrowInterestFactor defines an individual borrow interest factor. -type BorrowInterestFactor struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Value github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=value,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"value"` -} - -func (m *BorrowInterestFactor) Reset() { *m = BorrowInterestFactor{} } -func (m *BorrowInterestFactor) String() string { return proto.CompactTextString(m) } -func (*BorrowInterestFactor) ProtoMessage() {} -func (*BorrowInterestFactor) Descriptor() ([]byte, []int) { - return fileDescriptor_23a5de800263a2ff, []int{7} -} -func (m *BorrowInterestFactor) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *BorrowInterestFactor) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_BorrowInterestFactor.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *BorrowInterestFactor) XXX_Merge(src proto.Message) { - xxx_messageInfo_BorrowInterestFactor.Merge(m, src) -} -func (m *BorrowInterestFactor) XXX_Size() int { - return m.Size() -} -func (m *BorrowInterestFactor) XXX_DiscardUnknown() { - xxx_messageInfo_BorrowInterestFactor.DiscardUnknown(m) -} - -var xxx_messageInfo_BorrowInterestFactor proto.InternalMessageInfo - -// CoinsProto defines a Protobuf wrapper around a Coins slice -type CoinsProto struct { - Coins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=coins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"coins"` -} - -func (m *CoinsProto) Reset() { *m = CoinsProto{} } -func (m *CoinsProto) String() string { return proto.CompactTextString(m) } -func (*CoinsProto) ProtoMessage() {} -func (*CoinsProto) Descriptor() ([]byte, []int) { - return fileDescriptor_23a5de800263a2ff, []int{8} -} -func (m *CoinsProto) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CoinsProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CoinsProto.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CoinsProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_CoinsProto.Merge(m, src) -} -func (m *CoinsProto) XXX_Size() int { - return m.Size() -} -func (m *CoinsProto) XXX_DiscardUnknown() { - xxx_messageInfo_CoinsProto.DiscardUnknown(m) -} - -var xxx_messageInfo_CoinsProto proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Params)(nil), "kava.hard.v1beta1.Params") - proto.RegisterType((*MoneyMarket)(nil), "kava.hard.v1beta1.MoneyMarket") - proto.RegisterType((*BorrowLimit)(nil), "kava.hard.v1beta1.BorrowLimit") - proto.RegisterType((*InterestRateModel)(nil), "kava.hard.v1beta1.InterestRateModel") - proto.RegisterType((*Deposit)(nil), "kava.hard.v1beta1.Deposit") - proto.RegisterType((*Borrow)(nil), "kava.hard.v1beta1.Borrow") - proto.RegisterType((*SupplyInterestFactor)(nil), "kava.hard.v1beta1.SupplyInterestFactor") - proto.RegisterType((*BorrowInterestFactor)(nil), "kava.hard.v1beta1.BorrowInterestFactor") - proto.RegisterType((*CoinsProto)(nil), "kava.hard.v1beta1.CoinsProto") -} - -func init() { proto.RegisterFile("kava/hard/v1beta1/hard.proto", fileDescriptor_23a5de800263a2ff) } - -var fileDescriptor_23a5de800263a2ff = []byte{ - // 918 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x96, 0xcf, 0x8f, 0x1b, 0x35, - 0x14, 0xc7, 0x33, 0x9b, 0x1f, 0x6d, 0x9d, 0x64, 0x69, 0xdc, 0x5d, 0x34, 0xad, 0x60, 0x52, 0x45, - 0x88, 0xee, 0x25, 0xc9, 0x16, 0x04, 0x27, 0x2e, 0x3b, 0x84, 0x1f, 0x2b, 0x88, 0x14, 0xcd, 0x52, - 0xa4, 0x56, 0x48, 0x83, 0x33, 0xe3, 0x26, 0x26, 0xf1, 0x78, 0x64, 0x3b, 0x69, 0x72, 0xe3, 0xca, - 0x05, 0xf1, 0x47, 0x70, 0xe2, 0x86, 0xb4, 0x7f, 0xc4, 0x1e, 0xab, 0x9e, 0x10, 0x87, 0x00, 0xd9, - 0x1b, 0x67, 0x4e, 0x9c, 0x90, 0x7f, 0xe4, 0x47, 0xb7, 0xa9, 0xd4, 0xd5, 0x46, 0xa8, 0xa7, 0xc4, - 0x7e, 0xcf, 0x9f, 0xf7, 0x7d, 0xcf, 0xcf, 0x1e, 0x83, 0xb7, 0x06, 0x68, 0x8c, 0x9a, 0x7d, 0xc4, - 0xe3, 0xe6, 0xf8, 0x7e, 0x17, 0x4b, 0x74, 0x5f, 0x0f, 0x1a, 0x29, 0x67, 0x92, 0xc1, 0x8a, 0xb2, - 0x36, 0xf4, 0x84, 0xb5, 0xde, 0xf1, 0x22, 0x26, 0x28, 0x13, 0xcd, 0x2e, 0x12, 0x78, 0xb9, 0x24, - 0x62, 0x24, 0x31, 0x4b, 0xee, 0xdc, 0x36, 0xf6, 0x50, 0x8f, 0x9a, 0x66, 0x60, 0x4d, 0x7b, 0x3d, - 0xd6, 0x63, 0x66, 0x5e, 0xfd, 0x33, 0xb3, 0xb5, 0x7f, 0x1c, 0x50, 0xe8, 0x20, 0x8e, 0xa8, 0x80, - 0x0f, 0x41, 0x99, 0xb2, 0x04, 0x4f, 0x43, 0x8a, 0xf8, 0x00, 0x4b, 0xe1, 0x3a, 0x77, 0xb3, 0x07, - 0xc5, 0xf7, 0xbc, 0xc6, 0x0b, 0x32, 0x1a, 0x6d, 0xe5, 0xd7, 0xd6, 0x6e, 0xfe, 0xde, 0xd9, 0xac, - 0x9a, 0xf9, 0xe5, 0x8f, 0x6a, 0x69, 0x6d, 0x52, 0x04, 0x25, 0xba, 0x36, 0x82, 0x3f, 0x3a, 0xc0, - 0xa5, 0x24, 0x21, 0x74, 0x44, 0xc3, 0x2e, 0xe3, 0x9c, 0x3d, 0x09, 0x47, 0x22, 0x0e, 0xc7, 0x68, - 0x38, 0xc2, 0xee, 0xce, 0x5d, 0xe7, 0xe0, 0x86, 0xff, 0x40, 0x61, 0x7e, 0x9f, 0x55, 0xdf, 0xed, - 0x11, 0xd9, 0x1f, 0x75, 0x1b, 0x11, 0xa3, 0x56, 0xbf, 0xfd, 0xa9, 0x8b, 0x78, 0xd0, 0x94, 0xd3, - 0x14, 0x8b, 0x46, 0x0b, 0x47, 0xf3, 0x59, 0x75, 0xbf, 0x6d, 0x88, 0xbe, 0x06, 0x3e, 0x38, 0x69, - 0x7d, 0xad, 0x70, 0xcf, 0x4e, 0xeb, 0xc0, 0xe6, 0xdd, 0xc2, 0x51, 0xb0, 0x4f, 0x9f, 0x73, 0x12, - 0xb1, 0x76, 0xaa, 0x9d, 0xe5, 0x40, 0x71, 0x4d, 0x2f, 0xdc, 0x03, 0xf9, 0x18, 0x27, 0x8c, 0xba, - 0x8e, 0x12, 0x13, 0x98, 0x01, 0xfc, 0x0c, 0x94, 0xac, 0xda, 0x21, 0xa1, 0x44, 0x6a, 0xa5, 0x9b, - 0x0b, 0x62, 0xf0, 0x5f, 0x2a, 0x2f, 0x3f, 0xa7, 0x32, 0x09, 0x8a, 0xdd, 0xd5, 0x14, 0xfc, 0x10, - 0xec, 0x8a, 0x94, 0x49, 0x5b, 0xd9, 0x90, 0xc4, 0x6e, 0x56, 0x27, 0x7d, 0x73, 0x3e, 0xab, 0x96, - 0x4e, 0x52, 0x26, 0x8d, 0x8c, 0xe3, 0x56, 0x50, 0x12, 0xab, 0x51, 0x0c, 0x09, 0xa8, 0x44, 0x2c, - 0x19, 0x63, 0x2e, 0x08, 0x4b, 0xc2, 0xc7, 0x28, 0x92, 0x8c, 0xbb, 0x39, 0xbd, 0xf4, 0xa3, 0x4b, - 0xd4, 0xeb, 0x38, 0x91, 0x6b, 0x65, 0x39, 0x4e, 0x64, 0x70, 0x73, 0x85, 0xfd, 0x54, 0x53, 0xe1, - 0x23, 0x70, 0x8b, 0x24, 0x12, 0x73, 0x2c, 0x64, 0xc8, 0x91, 0xc4, 0x21, 0x65, 0x31, 0x1e, 0xba, - 0x79, 0x9d, 0xf2, 0x3b, 0x1b, 0x52, 0x3e, 0xb6, 0xde, 0x01, 0x92, 0xb8, 0xad, 0x7c, 0x6d, 0xe2, - 0x15, 0x72, 0xd1, 0x00, 0x23, 0xb0, 0xcb, 0xb1, 0xc0, 0x7c, 0x8c, 0x17, 0x39, 0x14, 0x2e, 0x9d, - 0x43, 0x0b, 0x47, 0x17, 0xb6, 0xb6, 0x6c, 0x99, 0x36, 0x81, 0x31, 0x70, 0x07, 0x18, 0xa7, 0x98, - 0x87, 0x1c, 0x3f, 0x41, 0x3c, 0x0e, 0x53, 0xcc, 0x23, 0x9c, 0x48, 0xd4, 0xc3, 0xee, 0xb5, 0x2d, - 0x84, 0x7b, 0xd3, 0xd0, 0x03, 0x0d, 0xef, 0x2c, 0xd9, 0xb5, 0x1f, 0x76, 0x40, 0x71, 0x6d, 0xfb, - 0xe1, 0x07, 0xa0, 0xdc, 0x47, 0x22, 0xa4, 0x68, 0x62, 0xbb, 0x46, 0xb5, 0xd4, 0x75, 0xbf, 0xf2, - 0xf7, 0xac, 0xfa, 0xbc, 0x21, 0x28, 0xf6, 0x91, 0x68, 0xa3, 0x89, 0x59, 0x86, 0x40, 0x99, 0xa2, - 0x89, 0x3e, 0x21, 0xab, 0x66, 0xbb, 0xaa, 0xe6, 0x92, 0x45, 0x9a, 0x10, 0xdf, 0x82, 0xf2, 0x90, - 0xa1, 0x24, 0x94, 0xcc, 0x9e, 0xbc, 0xec, 0x16, 0x42, 0x14, 0x15, 0xf2, 0x2b, 0x66, 0x8e, 0xd5, - 0xcf, 0x59, 0x50, 0x79, 0xa1, 0x2f, 0x20, 0x03, 0x65, 0x75, 0x5f, 0x99, 0xb6, 0x42, 0xe9, 0xd4, - 0x1c, 0x32, 0xff, 0x8b, 0x4b, 0x9f, 0xf8, 0xa2, 0x8f, 0x04, 0x56, 0xdc, 0xa3, 0xce, 0xc3, 0x8b, - 0x32, 0xba, 0x0b, 0x53, 0x3a, 0x85, 0x18, 0xbc, 0xa1, 0x03, 0xd2, 0xd1, 0x50, 0x92, 0x74, 0x48, - 0x30, 0xdf, 0x4a, 0x35, 0x77, 0x15, 0xb4, 0xbd, 0x64, 0xc2, 0x0e, 0xc8, 0x0d, 0x48, 0x32, 0xd8, - 0x4a, 0x19, 0x35, 0x49, 0x09, 0xff, 0x6e, 0x44, 0xd3, 0x75, 0xe1, 0xb9, 0x6d, 0x08, 0x57, 0xd0, - 0x95, 0xf0, 0xda, 0xe9, 0x0e, 0xb8, 0xd6, 0xc2, 0x29, 0x13, 0x44, 0xc2, 0xc7, 0xe0, 0x46, 0x6c, - 0xfe, 0x32, 0x6e, 0x37, 0xe6, 0xf3, 0x7f, 0x67, 0xd5, 0xfa, 0x2b, 0x04, 0x3a, 0x8a, 0xa2, 0xa3, - 0x38, 0xe6, 0x58, 0x88, 0x67, 0xa7, 0xf5, 0x5b, 0x36, 0x9e, 0x9d, 0xf1, 0xa7, 0x12, 0x8b, 0x60, - 0x85, 0x86, 0x11, 0x28, 0x20, 0xca, 0x46, 0x89, 0x6a, 0x6c, 0xf5, 0x59, 0xb9, 0xdd, 0xb0, 0x0b, - 0x54, 0x51, 0x97, 0x97, 0xca, 0xc7, 0x8c, 0x24, 0xfe, 0xa1, 0xfd, 0xa2, 0x1c, 0xbc, 0x82, 0x06, - 0xb5, 0x40, 0x04, 0x16, 0x0d, 0xbf, 0x01, 0x79, 0x92, 0xc4, 0x78, 0xe2, 0x66, 0x75, 0x8c, 0x7b, - 0x1b, 0xae, 0xad, 0x93, 0x51, 0x9a, 0x0e, 0xa7, 0x8b, 0x26, 0x35, 0x77, 0x87, 0xff, 0xb6, 0x8d, - 0xb8, 0xbf, 0xc9, 0x2a, 0x02, 0x03, 0xad, 0xfd, 0xba, 0x03, 0x0a, 0xe6, 0xa4, 0xc3, 0x18, 0x5c, - 0x37, 0xf7, 0x3b, 0xde, 0x7e, 0xd1, 0x96, 0xe4, 0xd7, 0xa6, 0x66, 0x26, 0xe9, 0x97, 0xd5, 0x6c, - 0x93, 0x75, 0x59, 0xb3, 0xef, 0x1d, 0xb0, 0xb7, 0xa9, 0xa8, 0x2f, 0xf9, 0xe2, 0x06, 0x20, 0xbf, - 0xfe, 0x28, 0xb8, 0x5a, 0xdb, 0x1b, 0x94, 0x96, 0xb0, 0x49, 0xe3, 0xff, 0x28, 0x81, 0x01, 0xa0, - 0x8b, 0xde, 0xd1, 0xef, 0x3a, 0x04, 0xf2, 0xea, 0xc9, 0xb6, 0x78, 0x60, 0x6d, 0x75, 0x57, 0x0d, - 0xd9, 0xff, 0xe4, 0xec, 0x2f, 0x2f, 0x73, 0x36, 0xf7, 0x9c, 0xa7, 0x73, 0xcf, 0xf9, 0x73, 0xee, - 0x39, 0x3f, 0x9d, 0x7b, 0x99, 0xa7, 0xe7, 0x5e, 0xe6, 0xb7, 0x73, 0x2f, 0xf3, 0xe8, 0xde, 0x1a, - 0xee, 0xb0, 0x37, 0x44, 0x5d, 0xd1, 0x3c, 0xec, 0xd5, 0xa3, 0x3e, 0x22, 0x49, 0x73, 0x62, 0x9e, - 0xa3, 0x9a, 0xd9, 0x2d, 0xe8, 0x47, 0xe2, 0xfb, 0xff, 0x05, 0x00, 0x00, 0xff, 0xff, 0xa4, 0xfe, - 0x27, 0x46, 0xa8, 0x0a, 0x00, 0x00, -} - -func (m *Params) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Params) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.MinimumBorrowUSDValue.Size() - i -= size - if _, err := m.MinimumBorrowUSDValue.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.MoneyMarkets) > 0 { - for iNdEx := len(m.MoneyMarkets) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.MoneyMarkets[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *MoneyMarket) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MoneyMarket) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MoneyMarket) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.KeeperRewardPercentage.Size() - i -= size - if _, err := m.KeeperRewardPercentage.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - { - size := m.ReserveFactor.Size() - i -= size - if _, err := m.ReserveFactor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size, err := m.InterestRateModel.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.ConversionFactor.Size() - i -= size - if _, err := m.ConversionFactor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - if len(m.SpotMarketID) > 0 { - i -= len(m.SpotMarketID) - copy(dAtA[i:], m.SpotMarketID) - i = encodeVarintHard(dAtA, i, uint64(len(m.SpotMarketID))) - i-- - dAtA[i] = 0x1a - } - { - size, err := m.BorrowLimit.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintHard(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *BorrowLimit) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *BorrowLimit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *BorrowLimit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.LoanToValue.Size() - i -= size - if _, err := m.LoanToValue.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.MaximumLimit.Size() - i -= size - if _, err := m.MaximumLimit.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.HasMaxLimit { - i-- - if m.HasMaxLimit { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *InterestRateModel) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *InterestRateModel) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *InterestRateModel) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.JumpMultiplier.Size() - i -= size - if _, err := m.JumpMultiplier.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.Kink.Size() - i -= size - if _, err := m.Kink.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.BaseMultiplier.Size() - i -= size - if _, err := m.BaseMultiplier.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.BaseRateAPY.Size() - i -= size - if _, err := m.BaseRateAPY.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *Deposit) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Deposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Deposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Index) > 0 { - for iNdEx := len(m.Index) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Index[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintHard(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *Borrow) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Borrow) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Borrow) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Index) > 0 { - for iNdEx := len(m.Index) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Index[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Borrower) > 0 { - i -= len(m.Borrower) - copy(dAtA[i:], m.Borrower) - i = encodeVarintHard(dAtA, i, uint64(len(m.Borrower))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *SupplyInterestFactor) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *SupplyInterestFactor) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SupplyInterestFactor) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Value.Size() - i -= size - if _, err := m.Value.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintHard(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *BorrowInterestFactor) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *BorrowInterestFactor) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *BorrowInterestFactor) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Value.Size() - i -= size - if _, err := m.Value.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintHard(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CoinsProto) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CoinsProto) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CoinsProto) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Coins) > 0 { - for iNdEx := len(m.Coins) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Coins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintHard(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintHard(dAtA []byte, offset int, v uint64) int { - offset -= sovHard(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.MoneyMarkets) > 0 { - for _, e := range m.MoneyMarkets { - l = e.Size() - n += 1 + l + sovHard(uint64(l)) - } - } - l = m.MinimumBorrowUSDValue.Size() - n += 1 + l + sovHard(uint64(l)) - return n -} - -func (m *MoneyMarket) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovHard(uint64(l)) - } - l = m.BorrowLimit.Size() - n += 1 + l + sovHard(uint64(l)) - l = len(m.SpotMarketID) - if l > 0 { - n += 1 + l + sovHard(uint64(l)) - } - l = m.ConversionFactor.Size() - n += 1 + l + sovHard(uint64(l)) - l = m.InterestRateModel.Size() - n += 1 + l + sovHard(uint64(l)) - l = m.ReserveFactor.Size() - n += 1 + l + sovHard(uint64(l)) - l = m.KeeperRewardPercentage.Size() - n += 1 + l + sovHard(uint64(l)) - return n -} - -func (m *BorrowLimit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.HasMaxLimit { - n += 2 - } - l = m.MaximumLimit.Size() - n += 1 + l + sovHard(uint64(l)) - l = m.LoanToValue.Size() - n += 1 + l + sovHard(uint64(l)) - return n -} - -func (m *InterestRateModel) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseRateAPY.Size() - n += 1 + l + sovHard(uint64(l)) - l = m.BaseMultiplier.Size() - n += 1 + l + sovHard(uint64(l)) - l = m.Kink.Size() - n += 1 + l + sovHard(uint64(l)) - l = m.JumpMultiplier.Size() - n += 1 + l + sovHard(uint64(l)) - return n -} - -func (m *Deposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovHard(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovHard(uint64(l)) - } - } - if len(m.Index) > 0 { - for _, e := range m.Index { - l = e.Size() - n += 1 + l + sovHard(uint64(l)) - } - } - return n -} - -func (m *Borrow) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Borrower) - if l > 0 { - n += 1 + l + sovHard(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovHard(uint64(l)) - } - } - if len(m.Index) > 0 { - for _, e := range m.Index { - l = e.Size() - n += 1 + l + sovHard(uint64(l)) - } - } - return n -} - -func (m *SupplyInterestFactor) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovHard(uint64(l)) - } - l = m.Value.Size() - n += 1 + l + sovHard(uint64(l)) - return n -} - -func (m *BorrowInterestFactor) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovHard(uint64(l)) - } - l = m.Value.Size() - n += 1 + l + sovHard(uint64(l)) - return n -} - -func (m *CoinsProto) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Coins) > 0 { - for _, e := range m.Coins { - l = e.Size() - n += 1 + l + sovHard(uint64(l)) - } - } - return n -} - -func sovHard(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozHard(x uint64) (n int) { - return sovHard(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Params) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Params: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MoneyMarkets", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MoneyMarkets = append(m.MoneyMarkets, MoneyMarket{}) - if err := m.MoneyMarkets[len(m.MoneyMarkets)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MinimumBorrowUSDValue", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MinimumBorrowUSDValue.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHard(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHard - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MoneyMarket) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MoneyMarket: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MoneyMarket: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BorrowLimit", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BorrowLimit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SpotMarketID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SpotMarketID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ConversionFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ConversionFactor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InterestRateModel", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.InterestRateModel.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ReserveFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ReserveFactor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field KeeperRewardPercentage", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.KeeperRewardPercentage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHard(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHard - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *BorrowLimit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: BorrowLimit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BorrowLimit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field HasMaxLimit", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.HasMaxLimit = bool(v != 0) - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaximumLimit", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MaximumLimit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LoanToValue", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.LoanToValue.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHard(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHard - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *InterestRateModel) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: InterestRateModel: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: InterestRateModel: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseRateAPY", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseRateAPY.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseMultiplier", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseMultiplier.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Kink", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Kink.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field JumpMultiplier", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.JumpMultiplier.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHard(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHard - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Deposit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Deposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Deposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = github_com_cosmos_cosmos_sdk_types.AccAddress(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Index = append(m.Index, SupplyInterestFactor{}) - if err := m.Index[len(m.Index)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHard(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHard - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Borrow) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Borrow: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Borrow: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Borrower", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Borrower = github_com_cosmos_cosmos_sdk_types.AccAddress(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Index = append(m.Index, BorrowInterestFactor{}) - if err := m.Index[len(m.Index)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHard(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHard - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *SupplyInterestFactor) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: SupplyInterestFactor: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SupplyInterestFactor: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHard(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHard - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *BorrowInterestFactor) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: BorrowInterestFactor: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BorrowInterestFactor: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHard(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHard - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CoinsProto) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CoinsProto: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CoinsProto: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Coins", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHard - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthHard - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthHard - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Coins = append(m.Coins, types.Coin{}) - if err := m.Coins[len(m.Coins)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHard(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHard - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipHard(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHard - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHard - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHard - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthHard - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupHard - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthHard - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthHard = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowHard = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupHard = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/hard/types/hooks.go b/x/hard/types/hooks.go deleted file mode 100644 index 80260d87..00000000 --- a/x/hard/types/hooks.go +++ /dev/null @@ -1,53 +0,0 @@ -package types - -import sdk "github.com/cosmos/cosmos-sdk/types" - -// MultiHARDHooks combine multiple HARD hooks, all hook functions are run in array sequence -type MultiHARDHooks []HARDHooks - -// NewMultiHARDHooks returns a new MultiHARDHooks -func NewMultiHARDHooks(hooks ...HARDHooks) MultiHARDHooks { - return hooks -} - -// AfterDepositCreated runs after a deposit is created -func (h MultiHARDHooks) AfterDepositCreated(ctx sdk.Context, deposit Deposit) { - for i := range h { - h[i].AfterDepositCreated(ctx, deposit) - } -} - -// BeforeDepositModified runs before a deposit is modified -func (h MultiHARDHooks) BeforeDepositModified(ctx sdk.Context, deposit Deposit) { - for i := range h { - h[i].BeforeDepositModified(ctx, deposit) - } -} - -// AfterDepositModified runs after a deposit is modified -func (h MultiHARDHooks) AfterDepositModified(ctx sdk.Context, deposit Deposit) { - for i := range h { - h[i].AfterDepositModified(ctx, deposit) - } -} - -// AfterBorrowCreated runs after a borrow is created -func (h MultiHARDHooks) AfterBorrowCreated(ctx sdk.Context, borrow Borrow) { - for i := range h { - h[i].AfterBorrowCreated(ctx, borrow) - } -} - -// BeforeBorrowModified runs before a borrow is modified -func (h MultiHARDHooks) BeforeBorrowModified(ctx sdk.Context, borrow Borrow) { - for i := range h { - h[i].BeforeBorrowModified(ctx, borrow) - } -} - -// AfterBorrowModified runs after a borrow is modified -func (h MultiHARDHooks) AfterBorrowModified(ctx sdk.Context, borrow Borrow) { - for i := range h { - h[i].AfterBorrowModified(ctx, borrow) - } -} diff --git a/x/hard/types/keys.go b/x/hard/types/keys.go deleted file mode 100644 index cc42bec0..00000000 --- a/x/hard/types/keys.go +++ /dev/null @@ -1,43 +0,0 @@ -package types - -const ( - // ModuleName name that will be used throughout the module - ModuleName = "hard" - - // ModuleAccountName name of module account used to hold deposits - ModuleAccountName = "hard" - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey Top level router key - RouterKey = ModuleName - - // DefaultParamspace default name for parameter store - DefaultParamspace = ModuleName -) - -var ( - DepositsKeyPrefix = []byte{0x01} - BorrowsKeyPrefix = []byte{0x02} - BorrowedCoinsPrefix = []byte{0x03} - SuppliedCoinsPrefix = []byte{0x04} - MoneyMarketsPrefix = []byte{0x05} - PreviousAccrualTimePrefix = []byte{0x06} // denom -> time - TotalReservesPrefix = []byte{0x07} // denom -> sdk.Coin - BorrowInterestFactorPrefix = []byte{0x08} // denom -> sdk.Dec - SupplyInterestFactorPrefix = []byte{0x09} // denom -> sdk.Dec - DelegatorInterestFactorPrefix = []byte{0x10} // denom -> sdk.Dec -) - -// DepositTypeIteratorKey returns an interator prefix for interating over deposits by deposit denom -func DepositTypeIteratorKey(denom string) []byte { - return createKey([]byte(denom)) -} - -func createKey(bytes ...[]byte) (r []byte) { - for _, b := range bytes { - r = append(r, b...) - } - return -} diff --git a/x/hard/types/liquidation.go b/x/hard/types/liquidation.go deleted file mode 100644 index 81398eb9..00000000 --- a/x/hard/types/liquidation.go +++ /dev/null @@ -1,70 +0,0 @@ -package types - -import ( - "sort" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// ValuationMap holds the USD value of various coin types -type ValuationMap struct { - Usd map[string]sdk.Dec -} - -// NewValuationMap returns a new instance of ValuationMap -func NewValuationMap() ValuationMap { - return ValuationMap{ - Usd: make(map[string]sdk.Dec), - } -} - -// Get returns the USD value for a specific denom -func (m ValuationMap) Get(denom string) sdk.Dec { - return m.Usd[denom] -} - -// SetZero sets the USD value for a specific denom to 0 -func (m ValuationMap) SetZero(denom string) { - m.Usd[denom] = sdk.ZeroDec() -} - -// Increment increments the USD value of a denom -func (m ValuationMap) Increment(denom string, amount sdk.Dec) { - _, ok := m.Usd[denom] - if !ok { - m.Usd[denom] = amount - return - } - m.Usd[denom] = m.Usd[denom].Add(amount) -} - -// Decrement decrements the USD value of a denom -func (m ValuationMap) Decrement(denom string, amount sdk.Dec) { - _, ok := m.Usd[denom] - if !ok { - m.Usd[denom] = amount - return - } - m.Usd[denom] = m.Usd[denom].Sub(amount) -} - -// Sum returns the total USD value of all coins in the map -func (m ValuationMap) Sum() sdk.Dec { - sum := sdk.ZeroDec() - for _, v := range m.Usd { - sum = sum.Add(v) - } - return sum -} - -// GetSortedKeys returns an array of the map's keys in alphabetical order -func (m ValuationMap) GetSortedKeys() []string { - keys := make([]string, len(m.Usd)) - i := 0 - for k := range m.Usd { - keys[i] = k - i++ - } - sort.Strings(keys) - return keys -} diff --git a/x/hard/types/msg.go b/x/hard/types/msg.go deleted file mode 100644 index c62ce328..00000000 --- a/x/hard/types/msg.go +++ /dev/null @@ -1,228 +0,0 @@ -package types - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// ensure Msg interface compliance at compile time -var ( - _ sdk.Msg = &MsgDeposit{} - _ sdk.Msg = &MsgWithdraw{} - _ sdk.Msg = &MsgBorrow{} - _ sdk.Msg = &MsgRepay{} - _ sdk.Msg = &MsgLiquidate{} -) - -// NewMsgDeposit returns a new MsgDeposit -func NewMsgDeposit(depositor sdk.AccAddress, amount sdk.Coins) MsgDeposit { - return MsgDeposit{ - Depositor: depositor.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgDeposit) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgDeposit) Type() string { return "hard_deposit" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgDeposit) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "deposit amount %s", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgDeposit) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgDeposit) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - panic(err) - } - return []sdk.AccAddress{depositor} -} - -// NewMsgWithdraw returns a new MsgWithdraw -func NewMsgWithdraw(depositor sdk.AccAddress, amount sdk.Coins) MsgWithdraw { - return MsgWithdraw{ - Depositor: depositor.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgWithdraw) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgWithdraw) Type() string { return "hard_withdraw" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgWithdraw) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - if !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "deposit amount %s", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgWithdraw) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgWithdraw) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - panic(err) - } - return []sdk.AccAddress{depositor} -} - -// NewMsgBorrow returns a new MsgBorrow -func NewMsgBorrow(borrower sdk.AccAddress, amount sdk.Coins) MsgBorrow { - return MsgBorrow{ - Borrower: borrower.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgBorrow) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgBorrow) Type() string { return "hard_borrow" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgBorrow) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Borrower) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - if !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "borrow amount %s", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgBorrow) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgBorrow) GetSigners() []sdk.AccAddress { - borrower, err := sdk.AccAddressFromBech32(msg.Borrower) - if err != nil { - panic(err) - } - return []sdk.AccAddress{borrower} -} - -// NewMsgRepay returns a new MsgRepay -func NewMsgRepay(sender, owner sdk.AccAddress, amount sdk.Coins) MsgRepay { - return MsgRepay{ - Sender: sender.String(), - Owner: owner.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgRepay) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgRepay) Type() string { return "hard_repay" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgRepay) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - _, err = sdk.AccAddressFromBech32(msg.Owner) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - if !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "repay amount %s", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgRepay) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgRepay) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgLiquidate returns a new MsgLiquidate -func NewMsgLiquidate(keeper, borrower sdk.AccAddress) MsgLiquidate { - return MsgLiquidate{ - Keeper: keeper.String(), - Borrower: borrower.String(), - } -} - -// Route return the message type used for routing the message. -func (msg MsgLiquidate) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgLiquidate) Type() string { return "liquidate" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgLiquidate) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Keeper) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - _, err = sdk.AccAddressFromBech32(msg.Borrower) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgLiquidate) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgLiquidate) GetSigners() []sdk.AccAddress { - keeper, err := sdk.AccAddressFromBech32(msg.Keeper) - if err != nil { - panic(err) - } - return []sdk.AccAddress{keeper} -} diff --git a/x/hard/types/msg_test.go b/x/hard/types/msg_test.go deleted file mode 100644 index f4235423..00000000 --- a/x/hard/types/msg_test.go +++ /dev/null @@ -1,195 +0,0 @@ -package types_test - -import ( - "strings" - "testing" - - sdkmath "cosmossdk.io/math" - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/hard/types" -) - -type MsgTestSuite struct { - suite.Suite -} - -func (suite *MsgTestSuite) TestMsgDeposit() { - type args struct { - depositor sdk.AccAddress - amount sdk.Coins - } - addrs := []sdk.AccAddress{ - sdk.AccAddress("test1"), - sdk.AccAddress("test2"), - } - testCases := []struct { - name string - args args - expectPass bool - expectedErr string - }{ - { - name: "valid", - args: args{ - depositor: addrs[0], - amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10000000))), - }, - expectPass: true, - expectedErr: "", - }, - { - name: "valid2", - args: args{ - depositor: addrs[0], - amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10000000))), - }, - expectPass: true, - expectedErr: "", - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - msg := types.NewMsgDeposit(tc.args.depositor, tc.args.amount) - err := msg.ValidateBasic() - if tc.expectPass { - suite.NoError(err) - } else { - suite.Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.expectedErr)) - } - }) - } -} - -func (suite *MsgTestSuite) TestMsgWithdraw() { - type args struct { - depositor sdk.AccAddress - amount sdk.Coins - } - addrs := []sdk.AccAddress{ - sdk.AccAddress("test1"), - sdk.AccAddress("test2"), - } - testCases := []struct { - name string - args args - expectPass bool - expectedErr string - }{ - { - name: "valid", - args: args{ - depositor: addrs[0], - amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10000000))), - }, - expectPass: true, - expectedErr: "", - }, - { - name: "valid2", - args: args{ - depositor: addrs[0], - amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10000000))), - }, - expectPass: true, - expectedErr: "", - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - msg := types.NewMsgWithdraw(tc.args.depositor, tc.args.amount) - err := msg.ValidateBasic() - if tc.expectPass { - suite.NoError(err) - } else { - suite.Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.expectedErr)) - } - }) - } -} - -func (suite *MsgTestSuite) TestMsgBorrow() { - type args struct { - borrower sdk.AccAddress - amount sdk.Coins - } - addrs := []sdk.AccAddress{ - sdk.AccAddress("test1"), - } - testCases := []struct { - name string - args args - expectPass bool - expectedErr string - }{ - { - name: "valid", - args: args{ - borrower: addrs[0], - amount: sdk.NewCoins(sdk.NewCoin("test", sdkmath.NewInt(1000000))), - }, - expectPass: true, - expectedErr: "", - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - msg := types.NewMsgBorrow(tc.args.borrower, tc.args.amount) - err := msg.ValidateBasic() - if tc.expectPass { - suite.NoError(err) - } else { - suite.Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.expectedErr)) - } - }) - } -} - -func (suite *MsgTestSuite) TestMsgRepay() { - type args struct { - sender sdk.AccAddress - owner sdk.AccAddress - amount sdk.Coins - } - addrs := []sdk.AccAddress{ - sdk.AccAddress("test1"), - } - testCases := []struct { - name string - args args - expectPass bool - expectedErr string - }{ - { - name: "valid", - args: args{ - sender: addrs[0], - owner: addrs[0], - amount: sdk.NewCoins(sdk.NewCoin("test", sdkmath.NewInt(1000000))), - }, - expectPass: true, - expectedErr: "", - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - msg := types.NewMsgRepay(tc.args.sender, tc.args.owner, tc.args.amount) - err := msg.ValidateBasic() - if tc.expectPass { - suite.NoError(err) - } else { - suite.Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.expectedErr)) - } - }) - } -} - -func TestMsgTestSuite(t *testing.T) { - suite.Run(t, new(MsgTestSuite)) -} diff --git a/x/hard/types/params.go b/x/hard/types/params.go deleted file mode 100644 index f3422a8e..00000000 --- a/x/hard/types/params.go +++ /dev/null @@ -1,252 +0,0 @@ -package types - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -// Parameter keys and default values -var ( - KeyMoneyMarkets = []byte("MoneyMarkets") - KeyMinimumBorrowUSDValue = []byte("MinimumBorrowUSDValue") - DefaultMoneyMarkets = MoneyMarkets{} - DefaultMinimumBorrowUSDValue = sdk.NewDec(10) // $10 USD minimum borrow value - DefaultAccumulationTimes = GenesisAccumulationTimes{} - DefaultTotalSupplied = sdk.Coins{} - DefaultTotalBorrowed = sdk.Coins{} - DefaultTotalReserves = sdk.Coins{} - DefaultDeposits = Deposits{} - DefaultBorrows = Borrows{} -) - -// NewBorrowLimit returns a new BorrowLimit -func NewBorrowLimit(hasMaxLimit bool, maximumLimit, loanToValue sdk.Dec) BorrowLimit { - return BorrowLimit{ - HasMaxLimit: hasMaxLimit, - MaximumLimit: maximumLimit, - LoanToValue: loanToValue, - } -} - -// Validate BorrowLimit -func (bl BorrowLimit) Validate() error { - if bl.MaximumLimit.IsNegative() { - return fmt.Errorf("maximum limit USD cannot be negative: %s", bl.MaximumLimit) - } - if bl.LoanToValue.IsNegative() { - return fmt.Errorf("loan-to-value must be a non-negative decimal: %s", bl.LoanToValue) - } - if bl.LoanToValue.GT(sdk.OneDec()) { - return fmt.Errorf("loan-to-value cannot be greater than 1.0: %s", bl.LoanToValue) - } - return nil -} - -// Equal returns a boolean indicating if an BorrowLimit is equal to another BorrowLimit -func (bl BorrowLimit) Equal(blCompareTo BorrowLimit) bool { - if bl.HasMaxLimit != blCompareTo.HasMaxLimit { - return false - } - if !bl.MaximumLimit.Equal(blCompareTo.MaximumLimit) { - return false - } - if !bl.LoanToValue.Equal(blCompareTo.LoanToValue) { - return false - } - return true -} - -// NewMoneyMarket returns a new MoneyMarket -func NewMoneyMarket(denom string, borrowLimit BorrowLimit, spotMarketID string, conversionFactor sdkmath.Int, - interestRateModel InterestRateModel, reserveFactor, keeperRewardPercentage sdk.Dec, -) MoneyMarket { - return MoneyMarket{ - Denom: denom, - BorrowLimit: borrowLimit, - SpotMarketID: spotMarketID, - ConversionFactor: conversionFactor, - InterestRateModel: interestRateModel, - ReserveFactor: reserveFactor, - KeeperRewardPercentage: keeperRewardPercentage, - } -} - -// Validate MoneyMarket param -func (mm MoneyMarket) Validate() error { - if err := sdk.ValidateDenom(mm.Denom); err != nil { - return err - } - - if err := mm.BorrowLimit.Validate(); err != nil { - return err - } - - if mm.ConversionFactor.IsNil() || mm.ConversionFactor.LT(sdk.OneInt()) { - return fmt.Errorf("conversion '%s' factor must be ≥ one", mm.ConversionFactor) - } - - if err := mm.InterestRateModel.Validate(); err != nil { - return err - } - - if mm.ReserveFactor.IsNegative() || mm.ReserveFactor.GT(sdk.OneDec()) { - return fmt.Errorf("reserve factor must be between 0.0-1.0") - } - - if mm.KeeperRewardPercentage.IsNegative() || mm.KeeperRewardPercentage.GT(sdk.OneDec()) { - return fmt.Errorf("keeper reward percentage must be between 0.0-1.0") - } - - return nil -} - -// Equal returns a boolean indicating if a MoneyMarket is equal to another MoneyMarket -func (mm MoneyMarket) Equal(mmCompareTo MoneyMarket) bool { - if mm.Denom != mmCompareTo.Denom { - return false - } - if !mm.BorrowLimit.Equal(mmCompareTo.BorrowLimit) { - return false - } - if mm.SpotMarketID != mmCompareTo.SpotMarketID { - return false - } - if !mm.ConversionFactor.Equal(mmCompareTo.ConversionFactor) { - return false - } - if !mm.InterestRateModel.Equal(mmCompareTo.InterestRateModel) { - return false - } - if !mm.ReserveFactor.Equal(mmCompareTo.ReserveFactor) { - return false - } - if !mm.KeeperRewardPercentage.Equal(mmCompareTo.KeeperRewardPercentage) { - return false - } - return true -} - -// MoneyMarkets slice of MoneyMarket -type MoneyMarkets []MoneyMarket - -// Validate borrow limits -func (mms MoneyMarkets) Validate() error { - for _, moneyMarket := range mms { - if err := moneyMarket.Validate(); err != nil { - return err - } - } - return nil -} - -// NewInterestRateModel returns a new InterestRateModel -func NewInterestRateModel(baseRateAPY, baseMultiplier, kink, jumpMultiplier sdk.Dec) InterestRateModel { - return InterestRateModel{ - BaseRateAPY: baseRateAPY, - BaseMultiplier: baseMultiplier, - Kink: kink, - JumpMultiplier: jumpMultiplier, - } -} - -// Validate InterestRateModel param -func (irm InterestRateModel) Validate() error { - if irm.BaseRateAPY.IsNegative() || irm.BaseRateAPY.GT(sdk.OneDec()) { - return fmt.Errorf("base rate APY must be in the inclusive range 0.0-1.0") - } - - if irm.BaseMultiplier.IsNegative() { - return fmt.Errorf("base multiplier must not be negative") - } - - if irm.Kink.IsNegative() || irm.Kink.GT(sdk.OneDec()) { - return fmt.Errorf("kink must be in the inclusive range 0.0-1.0") - } - - if irm.JumpMultiplier.IsNegative() { - return fmt.Errorf("jump multiplier must not be negative") - } - - return nil -} - -// Equal returns a boolean indicating if an InterestRateModel is equal to another InterestRateModel -func (irm InterestRateModel) Equal(irmCompareTo InterestRateModel) bool { - if !irm.BaseRateAPY.Equal(irmCompareTo.BaseRateAPY) { - return false - } - if !irm.BaseMultiplier.Equal(irmCompareTo.BaseMultiplier) { - return false - } - if !irm.Kink.Equal(irmCompareTo.Kink) { - return false - } - if !irm.JumpMultiplier.Equal(irmCompareTo.JumpMultiplier) { - return false - } - return true -} - -// InterestRateModels slice of InterestRateModel -type InterestRateModels []InterestRateModel - -// NewParams returns a new params object -func NewParams(moneyMarkets MoneyMarkets, minimumBorrowUSDValue sdk.Dec) Params { - return Params{ - MoneyMarkets: moneyMarkets, - MinimumBorrowUSDValue: minimumBorrowUSDValue, - } -} - -// DefaultParams returns default params for hard module -func DefaultParams() Params { - return NewParams(DefaultMoneyMarkets, DefaultMinimumBorrowUSDValue) -} - -// ParamKeyTable Key declaration for parameters -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements the ParamSet interface and returns all the key/value pairs -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyMoneyMarkets, &p.MoneyMarkets, validateMoneyMarketParams), - paramtypes.NewParamSetPair(KeyMinimumBorrowUSDValue, &p.MinimumBorrowUSDValue, validateMinimumBorrowUSDValue), - } -} - -// Validate checks that the parameters have valid values. -func (p Params) Validate() error { - if err := validateMinimumBorrowUSDValue(p.MinimumBorrowUSDValue); err != nil { - return err - } - - return validateMoneyMarketParams(p.MoneyMarkets) -} - -func validateMinimumBorrowUSDValue(i interface{}) error { - minBorrowVal, ok := i.(sdk.Dec) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if minBorrowVal.IsNegative() { - return fmt.Errorf("minimum borrow USD value cannot be negative") - } - - return nil -} - -func validateMoneyMarketParams(i interface{}) error { - mm, ok := i.(MoneyMarkets) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return mm.Validate() -} diff --git a/x/hard/types/params_test.go b/x/hard/types/params_test.go deleted file mode 100644 index 225d0487..00000000 --- a/x/hard/types/params_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package types_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/hard/types" -) - -type ParamTestSuite struct { - suite.Suite -} - -func (suite *ParamTestSuite) TestParamValidation() { - type args struct { - minBorrowVal sdk.Dec - mms types.MoneyMarkets - } - testCases := []struct { - name string - args args - expectPass bool - expectedErr string - }{ - { - name: "default", - args: args{ - minBorrowVal: types.DefaultMinimumBorrowUSDValue, - mms: types.DefaultMoneyMarkets, - }, - expectPass: true, - expectedErr: "", - }, - { - name: "invalid: conversion factor < one", - args: args{ - minBorrowVal: types.DefaultMinimumBorrowUSDValue, - mms: types.MoneyMarkets{ - { - Denom: "btcb", - BorrowLimit: types.NewBorrowLimit( - false, - sdk.MustNewDecFromStr("100000000000"), - sdk.MustNewDecFromStr("0.5"), - ), - SpotMarketID: "btc:usd", - ConversionFactor: sdkmath.NewInt(0), - InterestRateModel: types.InterestRateModel{}, - ReserveFactor: sdk.MustNewDecFromStr("0.05"), - KeeperRewardPercentage: sdk.MustNewDecFromStr("0.05"), - }, - }, - }, - expectPass: false, - expectedErr: "conversion '0' factor must be ≥ one", - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - params := types.NewParams(tc.args.mms, tc.args.minBorrowVal) - err := params.Validate() - if tc.expectPass { - suite.NoError(err) - } else { - suite.Error(err) - suite.Require().Contains(err.Error(), tc.expectedErr) - } - }) - } -} - -func TestParamTestSuite(t *testing.T) { - suite.Run(t, new(ParamTestSuite)) -} diff --git a/x/hard/types/period.go b/x/hard/types/period.go deleted file mode 100644 index 10787a99..00000000 --- a/x/hard/types/period.go +++ /dev/null @@ -1,20 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" -) - -// NewPeriod returns a new vesting period -func NewPeriod(amount sdk.Coins, length int64) vestingtypes.Period { - return vestingtypes.Period{Amount: amount, Length: length} -} - -// GetTotalVestingPeriodLength returns the summed length of all vesting periods -func GetTotalVestingPeriodLength(periods vestingtypes.Periods) int64 { - length := int64(0) - for _, period := range periods { - length += period.Length - } - return length -} diff --git a/x/hard/types/query.go b/x/hard/types/query.go deleted file mode 100644 index ef91d134..00000000 --- a/x/hard/types/query.go +++ /dev/null @@ -1,7 +0,0 @@ -package types - -// MoneyMarketInterestRates is a slice of MoneyMarketInterestRate -type MoneyMarketInterestRates []MoneyMarketInterestRate - -// InterestFactors is a slice of InterestFactor -type InterestFactors []InterestFactor diff --git a/x/hard/types/query.pb.go b/x/hard/types/query.pb.go deleted file mode 100644 index 74cfbded..00000000 --- a/x/hard/types/query.pb.go +++ /dev/null @@ -1,6733 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/hard/v1beta1/query.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types1 "github.com/cosmos/cosmos-sdk/types" - query "github.com/cosmos/cosmos-sdk/types/query" - types "github.com/cosmos/cosmos-sdk/x/auth/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// QueryParamsRequest is the request type for the Query/Params RPC method. -type QueryParamsRequest struct { -} - -func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } -func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryParamsRequest) ProtoMessage() {} -func (*QueryParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{0} -} -func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsRequest.Merge(m, src) -} -func (m *QueryParamsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo - -// QueryParamsResponse is the response type for the Query/Params RPC method. -type QueryParamsResponse struct { - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` -} - -func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } -func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryParamsResponse) ProtoMessage() {} -func (*QueryParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{1} -} -func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsResponse.Merge(m, src) -} -func (m *QueryParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo - -func (m *QueryParamsResponse) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -// QueryAccountsRequest is the request type for the Query/Accounts RPC method. -type QueryAccountsRequest struct { -} - -func (m *QueryAccountsRequest) Reset() { *m = QueryAccountsRequest{} } -func (m *QueryAccountsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAccountsRequest) ProtoMessage() {} -func (*QueryAccountsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{2} -} -func (m *QueryAccountsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAccountsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAccountsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryAccountsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAccountsRequest.Merge(m, src) -} -func (m *QueryAccountsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryAccountsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAccountsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAccountsRequest proto.InternalMessageInfo - -// QueryAccountsResponse is the response type for the Query/Accounts RPC method. -type QueryAccountsResponse struct { - Accounts []types.ModuleAccount `protobuf:"bytes,1,rep,name=accounts,proto3" json:"accounts"` -} - -func (m *QueryAccountsResponse) Reset() { *m = QueryAccountsResponse{} } -func (m *QueryAccountsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAccountsResponse) ProtoMessage() {} -func (*QueryAccountsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{3} -} -func (m *QueryAccountsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryAccountsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAccountsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryAccountsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAccountsResponse.Merge(m, src) -} -func (m *QueryAccountsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryAccountsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAccountsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAccountsResponse proto.InternalMessageInfo - -func (m *QueryAccountsResponse) GetAccounts() []types.ModuleAccount { - if m != nil { - return m.Accounts - } - return nil -} - -// QueryDepositsRequest is the request type for the Query/Deposits RPC method. -type QueryDepositsRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Pagination *query.PageRequest `protobuf:"bytes,3,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDepositsRequest) Reset() { *m = QueryDepositsRequest{} } -func (m *QueryDepositsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsRequest) ProtoMessage() {} -func (*QueryDepositsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{4} -} -func (m *QueryDepositsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryDepositsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsRequest.Merge(m, src) -} -func (m *QueryDepositsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsRequest proto.InternalMessageInfo - -func (m *QueryDepositsRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *QueryDepositsRequest) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *QueryDepositsRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryDepositsResponse is the response type for the Query/Deposits RPC method. -type QueryDepositsResponse struct { - Deposits DepositResponses `protobuf:"bytes,1,rep,name=deposits,proto3,castrepeated=DepositResponses" json:"deposits"` - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDepositsResponse) Reset() { *m = QueryDepositsResponse{} } -func (m *QueryDepositsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsResponse) ProtoMessage() {} -func (*QueryDepositsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{5} -} -func (m *QueryDepositsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryDepositsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsResponse.Merge(m, src) -} -func (m *QueryDepositsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsResponse proto.InternalMessageInfo - -func (m *QueryDepositsResponse) GetDeposits() DepositResponses { - if m != nil { - return m.Deposits - } - return nil -} - -func (m *QueryDepositsResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryUnsyncedDepositsRequest is the request type for the Query/UnsyncedDeposits RPC method. -type QueryUnsyncedDepositsRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Pagination *query.PageRequest `protobuf:"bytes,3,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryUnsyncedDepositsRequest) Reset() { *m = QueryUnsyncedDepositsRequest{} } -func (m *QueryUnsyncedDepositsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryUnsyncedDepositsRequest) ProtoMessage() {} -func (*QueryUnsyncedDepositsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{6} -} -func (m *QueryUnsyncedDepositsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryUnsyncedDepositsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryUnsyncedDepositsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryUnsyncedDepositsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryUnsyncedDepositsRequest.Merge(m, src) -} -func (m *QueryUnsyncedDepositsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryUnsyncedDepositsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryUnsyncedDepositsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryUnsyncedDepositsRequest proto.InternalMessageInfo - -func (m *QueryUnsyncedDepositsRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *QueryUnsyncedDepositsRequest) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *QueryUnsyncedDepositsRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryUnsyncedDepositsResponse is the response type for the Query/UnsyncedDeposits RPC method. -type QueryUnsyncedDepositsResponse struct { - Deposits DepositResponses `protobuf:"bytes,1,rep,name=deposits,proto3,castrepeated=DepositResponses" json:"deposits"` - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryUnsyncedDepositsResponse) Reset() { *m = QueryUnsyncedDepositsResponse{} } -func (m *QueryUnsyncedDepositsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryUnsyncedDepositsResponse) ProtoMessage() {} -func (*QueryUnsyncedDepositsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{7} -} -func (m *QueryUnsyncedDepositsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryUnsyncedDepositsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryUnsyncedDepositsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryUnsyncedDepositsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryUnsyncedDepositsResponse.Merge(m, src) -} -func (m *QueryUnsyncedDepositsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryUnsyncedDepositsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryUnsyncedDepositsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryUnsyncedDepositsResponse proto.InternalMessageInfo - -func (m *QueryUnsyncedDepositsResponse) GetDeposits() DepositResponses { - if m != nil { - return m.Deposits - } - return nil -} - -func (m *QueryUnsyncedDepositsResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryTotalDepositedRequest is the request type for the Query/TotalDeposited RPC method. -type QueryTotalDepositedRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` -} - -func (m *QueryTotalDepositedRequest) Reset() { *m = QueryTotalDepositedRequest{} } -func (m *QueryTotalDepositedRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalDepositedRequest) ProtoMessage() {} -func (*QueryTotalDepositedRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{8} -} -func (m *QueryTotalDepositedRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalDepositedRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalDepositedRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTotalDepositedRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalDepositedRequest.Merge(m, src) -} -func (m *QueryTotalDepositedRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalDepositedRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalDepositedRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalDepositedRequest proto.InternalMessageInfo - -func (m *QueryTotalDepositedRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -// QueryTotalDepositedResponse is the response type for the Query/TotalDeposited RPC method. -type QueryTotalDepositedResponse struct { - SuppliedCoins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=supplied_coins,json=suppliedCoins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"supplied_coins"` -} - -func (m *QueryTotalDepositedResponse) Reset() { *m = QueryTotalDepositedResponse{} } -func (m *QueryTotalDepositedResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalDepositedResponse) ProtoMessage() {} -func (*QueryTotalDepositedResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{9} -} -func (m *QueryTotalDepositedResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalDepositedResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalDepositedResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTotalDepositedResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalDepositedResponse.Merge(m, src) -} -func (m *QueryTotalDepositedResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalDepositedResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalDepositedResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalDepositedResponse proto.InternalMessageInfo - -func (m *QueryTotalDepositedResponse) GetSuppliedCoins() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.SuppliedCoins - } - return nil -} - -// QueryBorrowsRequest is the request type for the Query/Borrows RPC method. -type QueryBorrowsRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Pagination *query.PageRequest `protobuf:"bytes,3,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryBorrowsRequest) Reset() { *m = QueryBorrowsRequest{} } -func (m *QueryBorrowsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryBorrowsRequest) ProtoMessage() {} -func (*QueryBorrowsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{10} -} -func (m *QueryBorrowsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryBorrowsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryBorrowsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryBorrowsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryBorrowsRequest.Merge(m, src) -} -func (m *QueryBorrowsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryBorrowsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryBorrowsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryBorrowsRequest proto.InternalMessageInfo - -func (m *QueryBorrowsRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *QueryBorrowsRequest) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *QueryBorrowsRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryBorrowsResponse is the response type for the Query/Borrows RPC method. -type QueryBorrowsResponse struct { - Borrows BorrowResponses `protobuf:"bytes,1,rep,name=borrows,proto3,castrepeated=BorrowResponses" json:"borrows"` - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryBorrowsResponse) Reset() { *m = QueryBorrowsResponse{} } -func (m *QueryBorrowsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryBorrowsResponse) ProtoMessage() {} -func (*QueryBorrowsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{11} -} -func (m *QueryBorrowsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryBorrowsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryBorrowsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryBorrowsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryBorrowsResponse.Merge(m, src) -} -func (m *QueryBorrowsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryBorrowsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryBorrowsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryBorrowsResponse proto.InternalMessageInfo - -func (m *QueryBorrowsResponse) GetBorrows() BorrowResponses { - if m != nil { - return m.Borrows - } - return nil -} - -func (m *QueryBorrowsResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryUnsyncedBorrowsRequest is the request type for the Query/UnsyncedBorrows RPC method. -type QueryUnsyncedBorrowsRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Pagination *query.PageRequest `protobuf:"bytes,3,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryUnsyncedBorrowsRequest) Reset() { *m = QueryUnsyncedBorrowsRequest{} } -func (m *QueryUnsyncedBorrowsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryUnsyncedBorrowsRequest) ProtoMessage() {} -func (*QueryUnsyncedBorrowsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{12} -} -func (m *QueryUnsyncedBorrowsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryUnsyncedBorrowsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryUnsyncedBorrowsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryUnsyncedBorrowsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryUnsyncedBorrowsRequest.Merge(m, src) -} -func (m *QueryUnsyncedBorrowsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryUnsyncedBorrowsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryUnsyncedBorrowsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryUnsyncedBorrowsRequest proto.InternalMessageInfo - -func (m *QueryUnsyncedBorrowsRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *QueryUnsyncedBorrowsRequest) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *QueryUnsyncedBorrowsRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryUnsyncedBorrowsResponse is the response type for the Query/UnsyncedBorrows RPC method. -type QueryUnsyncedBorrowsResponse struct { - Borrows BorrowResponses `protobuf:"bytes,1,rep,name=borrows,proto3,castrepeated=BorrowResponses" json:"borrows"` - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryUnsyncedBorrowsResponse) Reset() { *m = QueryUnsyncedBorrowsResponse{} } -func (m *QueryUnsyncedBorrowsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryUnsyncedBorrowsResponse) ProtoMessage() {} -func (*QueryUnsyncedBorrowsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{13} -} -func (m *QueryUnsyncedBorrowsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryUnsyncedBorrowsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryUnsyncedBorrowsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryUnsyncedBorrowsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryUnsyncedBorrowsResponse.Merge(m, src) -} -func (m *QueryUnsyncedBorrowsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryUnsyncedBorrowsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryUnsyncedBorrowsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryUnsyncedBorrowsResponse proto.InternalMessageInfo - -func (m *QueryUnsyncedBorrowsResponse) GetBorrows() BorrowResponses { - if m != nil { - return m.Borrows - } - return nil -} - -func (m *QueryUnsyncedBorrowsResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryTotalBorrowedRequest is the request type for the Query/TotalBorrowed RPC method. -type QueryTotalBorrowedRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` -} - -func (m *QueryTotalBorrowedRequest) Reset() { *m = QueryTotalBorrowedRequest{} } -func (m *QueryTotalBorrowedRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalBorrowedRequest) ProtoMessage() {} -func (*QueryTotalBorrowedRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{14} -} -func (m *QueryTotalBorrowedRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalBorrowedRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalBorrowedRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTotalBorrowedRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalBorrowedRequest.Merge(m, src) -} -func (m *QueryTotalBorrowedRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalBorrowedRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalBorrowedRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalBorrowedRequest proto.InternalMessageInfo - -func (m *QueryTotalBorrowedRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -// QueryTotalBorrowedResponse is the response type for the Query/TotalBorrowed RPC method. -type QueryTotalBorrowedResponse struct { - BorrowedCoins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=borrowed_coins,json=borrowedCoins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"borrowed_coins"` -} - -func (m *QueryTotalBorrowedResponse) Reset() { *m = QueryTotalBorrowedResponse{} } -func (m *QueryTotalBorrowedResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalBorrowedResponse) ProtoMessage() {} -func (*QueryTotalBorrowedResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{15} -} -func (m *QueryTotalBorrowedResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalBorrowedResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalBorrowedResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTotalBorrowedResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalBorrowedResponse.Merge(m, src) -} -func (m *QueryTotalBorrowedResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalBorrowedResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalBorrowedResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalBorrowedResponse proto.InternalMessageInfo - -func (m *QueryTotalBorrowedResponse) GetBorrowedCoins() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.BorrowedCoins - } - return nil -} - -// QueryInterestRateRequest is the request type for the Query/InterestRate RPC method. -type QueryInterestRateRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` -} - -func (m *QueryInterestRateRequest) Reset() { *m = QueryInterestRateRequest{} } -func (m *QueryInterestRateRequest) String() string { return proto.CompactTextString(m) } -func (*QueryInterestRateRequest) ProtoMessage() {} -func (*QueryInterestRateRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{16} -} -func (m *QueryInterestRateRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryInterestRateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryInterestRateRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryInterestRateRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryInterestRateRequest.Merge(m, src) -} -func (m *QueryInterestRateRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryInterestRateRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryInterestRateRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryInterestRateRequest proto.InternalMessageInfo - -func (m *QueryInterestRateRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -// QueryInterestRateResponse is the response type for the Query/InterestRate RPC method. -type QueryInterestRateResponse struct { - InterestRates MoneyMarketInterestRates `protobuf:"bytes,1,rep,name=interest_rates,json=interestRates,proto3,castrepeated=MoneyMarketInterestRates" json:"interest_rates"` -} - -func (m *QueryInterestRateResponse) Reset() { *m = QueryInterestRateResponse{} } -func (m *QueryInterestRateResponse) String() string { return proto.CompactTextString(m) } -func (*QueryInterestRateResponse) ProtoMessage() {} -func (*QueryInterestRateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{17} -} -func (m *QueryInterestRateResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryInterestRateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryInterestRateResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryInterestRateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryInterestRateResponse.Merge(m, src) -} -func (m *QueryInterestRateResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryInterestRateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryInterestRateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryInterestRateResponse proto.InternalMessageInfo - -func (m *QueryInterestRateResponse) GetInterestRates() MoneyMarketInterestRates { - if m != nil { - return m.InterestRates - } - return nil -} - -// QueryReservesRequest is the request type for the Query/Reserves RPC method. -type QueryReservesRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` -} - -func (m *QueryReservesRequest) Reset() { *m = QueryReservesRequest{} } -func (m *QueryReservesRequest) String() string { return proto.CompactTextString(m) } -func (*QueryReservesRequest) ProtoMessage() {} -func (*QueryReservesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{18} -} -func (m *QueryReservesRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryReservesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryReservesRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryReservesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryReservesRequest.Merge(m, src) -} -func (m *QueryReservesRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryReservesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryReservesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryReservesRequest proto.InternalMessageInfo - -func (m *QueryReservesRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -// QueryReservesResponse is the response type for the Query/Reserves RPC method. -type QueryReservesResponse struct { - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *QueryReservesResponse) Reset() { *m = QueryReservesResponse{} } -func (m *QueryReservesResponse) String() string { return proto.CompactTextString(m) } -func (*QueryReservesResponse) ProtoMessage() {} -func (*QueryReservesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{19} -} -func (m *QueryReservesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryReservesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryReservesResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryReservesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryReservesResponse.Merge(m, src) -} -func (m *QueryReservesResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryReservesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryReservesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryReservesResponse proto.InternalMessageInfo - -func (m *QueryReservesResponse) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -// QueryInterestFactorsRequest is the request type for the Query/InterestFactors RPC method. -type QueryInterestFactorsRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` -} - -func (m *QueryInterestFactorsRequest) Reset() { *m = QueryInterestFactorsRequest{} } -func (m *QueryInterestFactorsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryInterestFactorsRequest) ProtoMessage() {} -func (*QueryInterestFactorsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{20} -} -func (m *QueryInterestFactorsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryInterestFactorsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryInterestFactorsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryInterestFactorsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryInterestFactorsRequest.Merge(m, src) -} -func (m *QueryInterestFactorsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryInterestFactorsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryInterestFactorsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryInterestFactorsRequest proto.InternalMessageInfo - -func (m *QueryInterestFactorsRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -// QueryInterestFactorsResponse is the response type for the Query/InterestFactors RPC method. -type QueryInterestFactorsResponse struct { - InterestFactors InterestFactors `protobuf:"bytes,1,rep,name=interest_factors,json=interestFactors,proto3,castrepeated=InterestFactors" json:"interest_factors"` -} - -func (m *QueryInterestFactorsResponse) Reset() { *m = QueryInterestFactorsResponse{} } -func (m *QueryInterestFactorsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryInterestFactorsResponse) ProtoMessage() {} -func (*QueryInterestFactorsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{21} -} -func (m *QueryInterestFactorsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryInterestFactorsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryInterestFactorsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryInterestFactorsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryInterestFactorsResponse.Merge(m, src) -} -func (m *QueryInterestFactorsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryInterestFactorsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryInterestFactorsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryInterestFactorsResponse proto.InternalMessageInfo - -func (m *QueryInterestFactorsResponse) GetInterestFactors() InterestFactors { - if m != nil { - return m.InterestFactors - } - return nil -} - -// DepositResponse defines an amount of coins deposited into a hard module account. -type DepositResponse struct { - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` - Index SupplyInterestFactorResponses `protobuf:"bytes,3,rep,name=index,proto3,castrepeated=SupplyInterestFactorResponses" json:"index"` -} - -func (m *DepositResponse) Reset() { *m = DepositResponse{} } -func (m *DepositResponse) String() string { return proto.CompactTextString(m) } -func (*DepositResponse) ProtoMessage() {} -func (*DepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{22} -} -func (m *DepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DepositResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *DepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_DepositResponse.Merge(m, src) -} -func (m *DepositResponse) XXX_Size() int { - return m.Size() -} -func (m *DepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_DepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_DepositResponse proto.InternalMessageInfo - -func (m *DepositResponse) GetDepositor() string { - if m != nil { - return m.Depositor - } - return "" -} - -func (m *DepositResponse) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -func (m *DepositResponse) GetIndex() SupplyInterestFactorResponses { - if m != nil { - return m.Index - } - return nil -} - -// SupplyInterestFactorResponse defines an individual borrow interest factor. -type SupplyInterestFactorResponse struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - // sdk.Dec as string - Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` -} - -func (m *SupplyInterestFactorResponse) Reset() { *m = SupplyInterestFactorResponse{} } -func (m *SupplyInterestFactorResponse) String() string { return proto.CompactTextString(m) } -func (*SupplyInterestFactorResponse) ProtoMessage() {} -func (*SupplyInterestFactorResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{23} -} -func (m *SupplyInterestFactorResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *SupplyInterestFactorResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SupplyInterestFactorResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *SupplyInterestFactorResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_SupplyInterestFactorResponse.Merge(m, src) -} -func (m *SupplyInterestFactorResponse) XXX_Size() int { - return m.Size() -} -func (m *SupplyInterestFactorResponse) XXX_DiscardUnknown() { - xxx_messageInfo_SupplyInterestFactorResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_SupplyInterestFactorResponse proto.InternalMessageInfo - -func (m *SupplyInterestFactorResponse) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *SupplyInterestFactorResponse) GetValue() string { - if m != nil { - return m.Value - } - return "" -} - -// BorrowResponse defines an amount of coins borrowed from a hard module account. -type BorrowResponse struct { - Borrower string `protobuf:"bytes,1,opt,name=borrower,proto3" json:"borrower,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` - Index BorrowInterestFactorResponses `protobuf:"bytes,3,rep,name=index,proto3,castrepeated=BorrowInterestFactorResponses" json:"index"` -} - -func (m *BorrowResponse) Reset() { *m = BorrowResponse{} } -func (m *BorrowResponse) String() string { return proto.CompactTextString(m) } -func (*BorrowResponse) ProtoMessage() {} -func (*BorrowResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{24} -} -func (m *BorrowResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *BorrowResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_BorrowResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *BorrowResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_BorrowResponse.Merge(m, src) -} -func (m *BorrowResponse) XXX_Size() int { - return m.Size() -} -func (m *BorrowResponse) XXX_DiscardUnknown() { - xxx_messageInfo_BorrowResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_BorrowResponse proto.InternalMessageInfo - -func (m *BorrowResponse) GetBorrower() string { - if m != nil { - return m.Borrower - } - return "" -} - -func (m *BorrowResponse) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -func (m *BorrowResponse) GetIndex() BorrowInterestFactorResponses { - if m != nil { - return m.Index - } - return nil -} - -// BorrowInterestFactorResponse defines an individual borrow interest factor. -type BorrowInterestFactorResponse struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - // sdk.Dec as string - Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` -} - -func (m *BorrowInterestFactorResponse) Reset() { *m = BorrowInterestFactorResponse{} } -func (m *BorrowInterestFactorResponse) String() string { return proto.CompactTextString(m) } -func (*BorrowInterestFactorResponse) ProtoMessage() {} -func (*BorrowInterestFactorResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{25} -} -func (m *BorrowInterestFactorResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *BorrowInterestFactorResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_BorrowInterestFactorResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *BorrowInterestFactorResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_BorrowInterestFactorResponse.Merge(m, src) -} -func (m *BorrowInterestFactorResponse) XXX_Size() int { - return m.Size() -} -func (m *BorrowInterestFactorResponse) XXX_DiscardUnknown() { - xxx_messageInfo_BorrowInterestFactorResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_BorrowInterestFactorResponse proto.InternalMessageInfo - -func (m *BorrowInterestFactorResponse) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *BorrowInterestFactorResponse) GetValue() string { - if m != nil { - return m.Value - } - return "" -} - -// MoneyMarketInterestRate is a unique type returned by interest rate queries -type MoneyMarketInterestRate struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - // sdk.Dec as String - SupplyInterestRate string `protobuf:"bytes,2,opt,name=supply_interest_rate,json=supplyInterestRate,proto3" json:"supply_interest_rate,omitempty"` - // sdk.Dec as String - BorrowInterestRate string `protobuf:"bytes,3,opt,name=borrow_interest_rate,json=borrowInterestRate,proto3" json:"borrow_interest_rate,omitempty"` -} - -func (m *MoneyMarketInterestRate) Reset() { *m = MoneyMarketInterestRate{} } -func (m *MoneyMarketInterestRate) String() string { return proto.CompactTextString(m) } -func (*MoneyMarketInterestRate) ProtoMessage() {} -func (*MoneyMarketInterestRate) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{26} -} -func (m *MoneyMarketInterestRate) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MoneyMarketInterestRate) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MoneyMarketInterestRate.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MoneyMarketInterestRate) XXX_Merge(src proto.Message) { - xxx_messageInfo_MoneyMarketInterestRate.Merge(m, src) -} -func (m *MoneyMarketInterestRate) XXX_Size() int { - return m.Size() -} -func (m *MoneyMarketInterestRate) XXX_DiscardUnknown() { - xxx_messageInfo_MoneyMarketInterestRate.DiscardUnknown(m) -} - -var xxx_messageInfo_MoneyMarketInterestRate proto.InternalMessageInfo - -func (m *MoneyMarketInterestRate) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *MoneyMarketInterestRate) GetSupplyInterestRate() string { - if m != nil { - return m.SupplyInterestRate - } - return "" -} - -func (m *MoneyMarketInterestRate) GetBorrowInterestRate() string { - if m != nil { - return m.BorrowInterestRate - } - return "" -} - -// InterestFactor is a unique type returned by interest factor queries -type InterestFactor struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - // sdk.Dec as String - BorrowInterestFactor string `protobuf:"bytes,2,opt,name=borrow_interest_factor,json=borrowInterestFactor,proto3" json:"borrow_interest_factor,omitempty"` - // sdk.Dec as String - SupplyInterestFactor string `protobuf:"bytes,3,opt,name=supply_interest_factor,json=supplyInterestFactor,proto3" json:"supply_interest_factor,omitempty"` -} - -func (m *InterestFactor) Reset() { *m = InterestFactor{} } -func (m *InterestFactor) String() string { return proto.CompactTextString(m) } -func (*InterestFactor) ProtoMessage() {} -func (*InterestFactor) Descriptor() ([]byte, []int) { - return fileDescriptor_1eedf429c9bff7da, []int{27} -} -func (m *InterestFactor) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *InterestFactor) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_InterestFactor.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *InterestFactor) XXX_Merge(src proto.Message) { - xxx_messageInfo_InterestFactor.Merge(m, src) -} -func (m *InterestFactor) XXX_Size() int { - return m.Size() -} -func (m *InterestFactor) XXX_DiscardUnknown() { - xxx_messageInfo_InterestFactor.DiscardUnknown(m) -} - -var xxx_messageInfo_InterestFactor proto.InternalMessageInfo - -func (m *InterestFactor) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *InterestFactor) GetBorrowInterestFactor() string { - if m != nil { - return m.BorrowInterestFactor - } - return "" -} - -func (m *InterestFactor) GetSupplyInterestFactor() string { - if m != nil { - return m.SupplyInterestFactor - } - return "" -} - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.hard.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.hard.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryAccountsRequest)(nil), "kava.hard.v1beta1.QueryAccountsRequest") - proto.RegisterType((*QueryAccountsResponse)(nil), "kava.hard.v1beta1.QueryAccountsResponse") - proto.RegisterType((*QueryDepositsRequest)(nil), "kava.hard.v1beta1.QueryDepositsRequest") - proto.RegisterType((*QueryDepositsResponse)(nil), "kava.hard.v1beta1.QueryDepositsResponse") - proto.RegisterType((*QueryUnsyncedDepositsRequest)(nil), "kava.hard.v1beta1.QueryUnsyncedDepositsRequest") - proto.RegisterType((*QueryUnsyncedDepositsResponse)(nil), "kava.hard.v1beta1.QueryUnsyncedDepositsResponse") - proto.RegisterType((*QueryTotalDepositedRequest)(nil), "kava.hard.v1beta1.QueryTotalDepositedRequest") - proto.RegisterType((*QueryTotalDepositedResponse)(nil), "kava.hard.v1beta1.QueryTotalDepositedResponse") - proto.RegisterType((*QueryBorrowsRequest)(nil), "kava.hard.v1beta1.QueryBorrowsRequest") - proto.RegisterType((*QueryBorrowsResponse)(nil), "kava.hard.v1beta1.QueryBorrowsResponse") - proto.RegisterType((*QueryUnsyncedBorrowsRequest)(nil), "kava.hard.v1beta1.QueryUnsyncedBorrowsRequest") - proto.RegisterType((*QueryUnsyncedBorrowsResponse)(nil), "kava.hard.v1beta1.QueryUnsyncedBorrowsResponse") - proto.RegisterType((*QueryTotalBorrowedRequest)(nil), "kava.hard.v1beta1.QueryTotalBorrowedRequest") - proto.RegisterType((*QueryTotalBorrowedResponse)(nil), "kava.hard.v1beta1.QueryTotalBorrowedResponse") - proto.RegisterType((*QueryInterestRateRequest)(nil), "kava.hard.v1beta1.QueryInterestRateRequest") - proto.RegisterType((*QueryInterestRateResponse)(nil), "kava.hard.v1beta1.QueryInterestRateResponse") - proto.RegisterType((*QueryReservesRequest)(nil), "kava.hard.v1beta1.QueryReservesRequest") - proto.RegisterType((*QueryReservesResponse)(nil), "kava.hard.v1beta1.QueryReservesResponse") - proto.RegisterType((*QueryInterestFactorsRequest)(nil), "kava.hard.v1beta1.QueryInterestFactorsRequest") - proto.RegisterType((*QueryInterestFactorsResponse)(nil), "kava.hard.v1beta1.QueryInterestFactorsResponse") - proto.RegisterType((*DepositResponse)(nil), "kava.hard.v1beta1.DepositResponse") - proto.RegisterType((*SupplyInterestFactorResponse)(nil), "kava.hard.v1beta1.SupplyInterestFactorResponse") - proto.RegisterType((*BorrowResponse)(nil), "kava.hard.v1beta1.BorrowResponse") - proto.RegisterType((*BorrowInterestFactorResponse)(nil), "kava.hard.v1beta1.BorrowInterestFactorResponse") - proto.RegisterType((*MoneyMarketInterestRate)(nil), "kava.hard.v1beta1.MoneyMarketInterestRate") - proto.RegisterType((*InterestFactor)(nil), "kava.hard.v1beta1.InterestFactor") -} - -func init() { proto.RegisterFile("kava/hard/v1beta1/query.proto", fileDescriptor_1eedf429c9bff7da) } - -var fileDescriptor_1eedf429c9bff7da = []byte{ - // 1324 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x58, 0xcf, 0x6f, 0x1b, 0xc5, - 0x17, 0xcf, 0x3a, 0xdf, 0xa4, 0xe9, 0x6b, 0x9b, 0xf4, 0x3b, 0x98, 0xd6, 0x76, 0x12, 0x37, 0xd9, - 0x34, 0x3f, 0x48, 0x63, 0xaf, 0x93, 0x56, 0x70, 0x8e, 0xa9, 0x8a, 0x40, 0x0a, 0x82, 0x6d, 0x91, - 0x10, 0x12, 0x8a, 0xd6, 0xde, 0xc1, 0x59, 0xc5, 0xd9, 0x71, 0x77, 0xd6, 0x69, 0x83, 0x10, 0x87, - 0x4a, 0xdc, 0x0b, 0x39, 0x20, 0x04, 0x12, 0x87, 0x72, 0x02, 0x8e, 0x70, 0x41, 0xe2, 0xc2, 0xa9, - 0xe2, 0x54, 0xc1, 0x85, 0x13, 0xa0, 0x84, 0x3f, 0x04, 0xed, 0xcc, 0x9b, 0xb5, 0x77, 0xbd, 0xbb, - 0x0e, 0x12, 0x45, 0xe9, 0x29, 0x99, 0x99, 0xf7, 0xe3, 0xf3, 0x3e, 0xf3, 0xe6, 0xed, 0x7b, 0x86, - 0xd9, 0x5d, 0x6b, 0xdf, 0x32, 0x76, 0x2c, 0xcf, 0x36, 0xf6, 0xd7, 0x1b, 0xd4, 0xb7, 0xd6, 0x8d, - 0xbb, 0x5d, 0xea, 0x1d, 0x54, 0x3b, 0x1e, 0xf3, 0x19, 0xf9, 0x7f, 0x70, 0x5c, 0x0d, 0x8e, 0xab, - 0x78, 0x5c, 0x2a, 0x37, 0x19, 0xdf, 0x63, 0xdc, 0xb0, 0xba, 0xfe, 0x4e, 0xa8, 0x13, 0x2c, 0xa4, - 0x4a, 0x69, 0x15, 0xcf, 0x1b, 0x16, 0xa7, 0xd2, 0x56, 0x28, 0xd5, 0xb1, 0x5a, 0x8e, 0x6b, 0xf9, - 0x0e, 0x73, 0x51, 0xb6, 0xdc, 0x2f, 0xab, 0xa4, 0x9a, 0xcc, 0x51, 0xe7, 0x45, 0x79, 0xbe, 0x2d, - 0x56, 0x86, 0x5c, 0xe0, 0x51, 0xbe, 0xc5, 0x5a, 0x4c, 0xee, 0x07, 0xff, 0xe1, 0xee, 0x4c, 0x8b, - 0xb1, 0x56, 0x9b, 0x1a, 0x56, 0xc7, 0x31, 0x2c, 0xd7, 0x65, 0xbe, 0xf0, 0xa6, 0x74, 0x66, 0x06, - 0x83, 0x15, 0xa1, 0x89, 0x53, 0x3d, 0x0f, 0xe4, 0xcd, 0x00, 0xee, 0x1b, 0x96, 0x67, 0xed, 0x71, - 0x93, 0xde, 0xed, 0x52, 0xee, 0xeb, 0xaf, 0xc3, 0x73, 0x91, 0x5d, 0xde, 0x61, 0x2e, 0xa7, 0xe4, - 0x25, 0x18, 0xef, 0x88, 0x9d, 0x82, 0x36, 0xa7, 0xad, 0x9c, 0xdb, 0x28, 0x56, 0x07, 0x98, 0xaa, - 0x4a, 0x95, 0xfa, 0xff, 0x1e, 0xff, 0x7e, 0x65, 0xc4, 0x44, 0x71, 0xfd, 0x12, 0xe4, 0x85, 0xbd, - 0xcd, 0x66, 0x93, 0x75, 0x5d, 0x3f, 0xf4, 0xf3, 0x2e, 0x3c, 0x1f, 0xdb, 0x47, 0x4f, 0x37, 0x61, - 0xc2, 0xc2, 0xbd, 0x82, 0x36, 0x37, 0xba, 0x72, 0x6e, 0x43, 0xaf, 0x22, 0x13, 0x82, 0x75, 0xe5, - 0x6d, 0x8b, 0xd9, 0xdd, 0x36, 0x45, 0x75, 0x74, 0x1a, 0x6a, 0xea, 0x5f, 0x69, 0xe8, 0xf7, 0x26, - 0xed, 0x30, 0xee, 0x84, 0x7e, 0x49, 0x1e, 0xc6, 0x6c, 0xea, 0xb2, 0x3d, 0x11, 0xc7, 0x59, 0x53, - 0x2e, 0x48, 0x15, 0xc6, 0xd8, 0x3d, 0x97, 0x7a, 0x85, 0x5c, 0xb0, 0x5b, 0x2f, 0xfc, 0xf2, 0x5d, - 0x25, 0x8f, 0x4e, 0x37, 0x6d, 0xdb, 0xa3, 0x9c, 0xdf, 0xf6, 0x3d, 0xc7, 0x6d, 0x99, 0x52, 0x8c, - 0xdc, 0x02, 0xe8, 0x5d, 0x6e, 0x61, 0x54, 0x50, 0xb2, 0xa4, 0x60, 0x06, 0xb7, 0x5b, 0x95, 0x59, - 0xd5, 0xa3, 0xa6, 0x45, 0x11, 0x81, 0xd9, 0xa7, 0xa9, 0xff, 0xa0, 0x21, 0x0d, 0x3d, 0x98, 0x48, - 0xc3, 0xdb, 0x30, 0x61, 0xe3, 0x5e, 0x48, 0xc3, 0x20, 0xe5, 0xa8, 0xa6, 0xb4, 0xea, 0x85, 0x80, - 0x86, 0xaf, 0xff, 0xb8, 0x72, 0x31, 0x76, 0xc0, 0xcd, 0xd0, 0x1a, 0x79, 0x25, 0x82, 0x3d, 0x27, - 0xb0, 0x2f, 0x0f, 0xc5, 0x2e, 0xed, 0x44, 0xc0, 0x7f, 0xab, 0xc1, 0x8c, 0x00, 0xff, 0x96, 0xcb, - 0x0f, 0xdc, 0x26, 0xb5, 0x4f, 0x37, 0xd7, 0x3f, 0x69, 0x30, 0x9b, 0x02, 0xf7, 0xd9, 0xe1, 0x7c, - 0x03, 0x4a, 0x22, 0x86, 0x3b, 0xcc, 0xb7, 0xda, 0xe8, 0x90, 0xda, 0x99, 0x84, 0xeb, 0x1f, 0x6b, - 0x30, 0x9d, 0xa8, 0x84, 0x61, 0x7b, 0x30, 0xc9, 0xbb, 0x9d, 0x4e, 0xdb, 0xa1, 0xf6, 0x76, 0x50, - 0x8c, 0x78, 0x21, 0x27, 0x82, 0x2f, 0x46, 0x00, 0x2a, 0x68, 0x2f, 0x33, 0xc7, 0xad, 0xd7, 0x30, - 0xe6, 0x95, 0x96, 0xe3, 0xef, 0x74, 0x1b, 0xd5, 0x26, 0xdb, 0xc3, 0x72, 0x85, 0x7f, 0x2a, 0xdc, - 0xde, 0x35, 0xfc, 0x83, 0x0e, 0xe5, 0x42, 0x81, 0x9b, 0x17, 0x94, 0x0b, 0xb1, 0xd4, 0x1f, 0x69, - 0x58, 0x67, 0xea, 0xcc, 0xf3, 0xd8, 0xbd, 0x53, 0x9a, 0x32, 0xdf, 0xab, 0x2a, 0x12, 0xa2, 0x44, - 0xca, 0xee, 0xc0, 0x99, 0x86, 0xdc, 0xc2, 0x44, 0x99, 0x4f, 0x48, 0x14, 0xa9, 0x14, 0xe6, 0xc9, - 0x65, 0xe4, 0x6c, 0x2a, 0xba, 0xcf, 0x4d, 0x65, 0xea, 0xdf, 0xcb, 0x92, 0x6f, 0xd4, 0x8d, 0xab, - 0x54, 0x3f, 0xd5, 0x2c, 0xff, 0x18, 0xaf, 0x23, 0xcf, 0x18, 0xdb, 0xeb, 0x50, 0xec, 0x3d, 0x2f, - 0xe9, 0x6e, 0xd8, 0x93, 0x7c, 0xa8, 0xf5, 0xbf, 0xe3, 0x9e, 0x4e, 0xef, 0x45, 0x36, 0x70, 0xef, - 0x29, 0xbe, 0x48, 0xe5, 0x42, 0xbe, 0xc8, 0x1a, 0x14, 0x04, 0xa2, 0x57, 0x5d, 0x9f, 0x7a, 0xc1, - 0x15, 0x59, 0x3e, 0x1d, 0x1a, 0x44, 0x31, 0x41, 0x05, 0x63, 0xe0, 0x30, 0xe9, 0xe0, 0xfe, 0xb6, - 0x67, 0xf9, 0x54, 0xdd, 0xdd, 0x6a, 0xc2, 0xdd, 0x6d, 0x31, 0x97, 0x1e, 0x6c, 0x59, 0xde, 0x2e, - 0xf5, 0xfb, 0x6d, 0xd5, 0xe7, 0x30, 0xa8, 0x42, 0x8a, 0x00, 0x37, 0x2f, 0x38, 0xfd, 0x4b, 0x7d, - 0x0d, 0xdf, 0xab, 0x49, 0x39, 0xf5, 0xf6, 0x69, 0x76, 0xc2, 0xeb, 0x1f, 0xe0, 0xc7, 0xb7, 0x27, - 0x8d, 0xd8, 0x9b, 0x30, 0x6e, 0xed, 0x05, 0x8d, 0xc4, 0xd3, 0xe0, 0x1d, 0x4d, 0xeb, 0xd7, 0xf1, - 0x8d, 0xaa, 0x80, 0x6e, 0x59, 0x4d, 0x9f, 0x79, 0x43, 0x20, 0x7f, 0xa4, 0xde, 0xca, 0x80, 0x16, - 0x42, 0xa7, 0x70, 0x31, 0xa4, 0xfd, 0x3d, 0x79, 0x96, 0xf1, 0x68, 0xa2, 0x56, 0x7a, 0x8f, 0x26, - 0x6e, 0x7d, 0xca, 0x89, 0x6e, 0xe8, 0x5f, 0xe4, 0x60, 0x2a, 0xf6, 0xbd, 0x23, 0x2f, 0xc2, 0x59, - 0xfc, 0xe0, 0x31, 0x4f, 0xa2, 0xce, 0xa8, 0x21, 0x3d, 0xd1, 0xff, 0x84, 0x6d, 0xd2, 0x86, 0x31, - 0xc7, 0xb5, 0xe9, 0xfd, 0xc2, 0xa8, 0xf0, 0x61, 0x24, 0x90, 0x71, 0x3b, 0xf8, 0x42, 0xc5, 0x88, - 0x0d, 0xeb, 0xc9, 0x22, 0x7a, 0x9e, 0xcd, 0x92, 0xe2, 0xa6, 0x74, 0xa2, 0xbf, 0x06, 0x33, 0x59, - 0x72, 0x29, 0x05, 0x38, 0x0f, 0x63, 0xfb, 0x56, 0xbb, 0x4b, 0x65, 0x01, 0x36, 0xe5, 0x42, 0xff, - 0x2c, 0x07, 0x93, 0xd1, 0x22, 0x46, 0x6e, 0xc0, 0x04, 0x3e, 0xde, 0xe1, 0x44, 0x87, 0x92, 0xa7, - 0x86, 0x67, 0x19, 0xcc, 0x30, 0x9e, 0xb3, 0xa4, 0xfa, 0x79, 0xce, 0x92, 0xfb, 0x47, 0x3c, 0x1f, - 0x6a, 0x70, 0x39, 0xa5, 0xce, 0xa4, 0xd8, 0xa9, 0x41, 0x5e, 0x74, 0x35, 0x07, 0xdb, 0x91, 0x4a, - 0x87, 0x66, 0x09, 0x8f, 0x64, 0x80, 0xb0, 0x53, 0x83, 0xbc, 0xbc, 0x8e, 0x98, 0xc6, 0xa8, 0xd4, - 0x68, 0x44, 0x62, 0x09, 0x34, 0xf4, 0x4f, 0x34, 0x98, 0x8c, 0x06, 0x97, 0x02, 0xe6, 0x06, 0x5c, - 0x8a, 0x9b, 0x96, 0xef, 0x1f, 0xe1, 0xe4, 0x1b, 0x09, 0x44, 0x05, 0x5a, 0xf1, 0x10, 0x50, 0x4b, - 0x42, 0xca, 0xf3, 0x84, 0x34, 0xde, 0xf8, 0xf9, 0x3c, 0x8c, 0x89, 0x2a, 0x44, 0xde, 0x87, 0x71, - 0x39, 0xf6, 0x91, 0xc5, 0x84, 0x9b, 0x1e, 0x9c, 0x2f, 0x4b, 0x4b, 0xc3, 0xc4, 0xe4, 0xcd, 0xe9, - 0xf3, 0x0f, 0x7e, 0xfd, 0xeb, 0x30, 0x37, 0x4d, 0x8a, 0xc6, 0xe0, 0x10, 0x2b, 0x47, 0x4b, 0xf2, - 0x40, 0x83, 0x09, 0x35, 0x3e, 0x92, 0xe5, 0x34, 0xbb, 0xb1, 0xc1, 0xb3, 0xb4, 0x32, 0x5c, 0x10, - 0x21, 0x2c, 0x08, 0x08, 0xb3, 0x64, 0x3a, 0x01, 0x82, 0x1a, 0x34, 0x05, 0x08, 0x35, 0x48, 0xa4, - 0x83, 0x88, 0x4d, 0x46, 0xe9, 0x20, 0xe2, 0x33, 0x49, 0x26, 0x88, 0x70, 0xbc, 0x78, 0xa4, 0xc1, - 0xc5, 0xf8, 0x54, 0x43, 0x8c, 0x34, 0x1f, 0x29, 0xe3, 0x5a, 0xa9, 0x76, 0x72, 0x05, 0x04, 0xb7, - 0x26, 0xc0, 0x2d, 0x91, 0xab, 0x09, 0xe0, 0xba, 0xa8, 0x54, 0x09, 0x51, 0x7e, 0xae, 0xc1, 0x64, - 0x74, 0x04, 0x21, 0x95, 0x34, 0x97, 0x89, 0xf3, 0x4d, 0xa9, 0x7a, 0x52, 0x71, 0xc4, 0xb7, 0x2a, - 0xf0, 0x5d, 0x25, 0x7a, 0x02, 0x3e, 0x3f, 0x50, 0x51, 0xe0, 0xa8, 0x4d, 0x3e, 0x84, 0x33, 0xd8, - 0x77, 0x92, 0xd4, 0x1c, 0x8d, 0xb6, 0xd1, 0xa5, 0xe5, 0xa1, 0x72, 0x88, 0x43, 0x17, 0x38, 0x66, - 0x48, 0x29, 0x01, 0x87, 0x6a, 0x47, 0xbf, 0xd4, 0x60, 0x2a, 0xd6, 0x00, 0x93, 0xea, 0xb0, 0x1b, - 0x89, 0x01, 0x32, 0x4e, 0x2c, 0x8f, 0xc0, 0xae, 0x09, 0x60, 0x8b, 0x64, 0x21, 0xeb, 0x02, 0x15, - 0xc2, 0x4f, 0x35, 0xb8, 0x10, 0xe9, 0x57, 0xc9, 0x5a, 0xe6, 0x7d, 0xc4, 0x5a, 0xe1, 0x52, 0xe5, - 0x84, 0xd2, 0x88, 0xed, 0x05, 0x81, 0x6d, 0x81, 0xcc, 0xa7, 0x5e, 0x9e, 0x6a, 0x60, 0xc9, 0xa1, - 0x06, 0xe7, 0x23, 0x75, 0xf6, 0x5a, 0x9a, 0xab, 0x84, 0xee, 0xb6, 0xb4, 0x76, 0x32, 0x61, 0x84, - 0xb5, 0x22, 0x60, 0xe9, 0x64, 0x2e, 0x01, 0x96, 0xaa, 0xa1, 0x95, 0xa0, 0xa8, 0x8b, 0xd2, 0xa0, - 0x5a, 0xcb, 0xf4, 0xd2, 0x10, 0x6b, 0x55, 0xd3, 0x4b, 0x43, 0xbc, 0x4b, 0xcd, 0x2c, 0x0d, 0x9e, - 0xf2, 0x1b, 0xa4, 0x55, 0xac, 0x9b, 0x4b, 0x4f, 0xab, 0xe4, 0x56, 0x34, 0x3d, 0xad, 0x52, 0x9a, - 0xd0, 0xcc, 0xb4, 0x0a, 0x39, 0xc2, 0xee, 0xb4, 0xbe, 0xf9, 0xf8, 0xa8, 0xac, 0x3d, 0x39, 0x2a, - 0x6b, 0x7f, 0x1e, 0x95, 0xb5, 0x87, 0xc7, 0xe5, 0x91, 0x27, 0xc7, 0xe5, 0x91, 0xdf, 0x8e, 0xcb, - 0x23, 0xef, 0x2c, 0xf7, 0x75, 0x1f, 0xb5, 0x56, 0xdb, 0x6a, 0x70, 0xa3, 0xd6, 0xaa, 0x34, 0x77, - 0x2c, 0xc7, 0x35, 0xee, 0x4b, 0xab, 0xa2, 0x05, 0x69, 0x8c, 0x8b, 0x5f, 0x34, 0xaf, 0xff, 0x1d, - 0x00, 0x00, 0xff, 0xff, 0x0f, 0xa8, 0x5f, 0x41, 0xde, 0x15, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - // Params queries module params. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Accounts queries module accounts. - Accounts(ctx context.Context, in *QueryAccountsRequest, opts ...grpc.CallOption) (*QueryAccountsResponse, error) - // Deposits queries hard deposits. - Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, error) - // UnsyncedDeposits queries unsynced deposits. - UnsyncedDeposits(ctx context.Context, in *QueryUnsyncedDepositsRequest, opts ...grpc.CallOption) (*QueryUnsyncedDepositsResponse, error) - // TotalDeposited queries total coins deposited to hard liquidity pools. - TotalDeposited(ctx context.Context, in *QueryTotalDepositedRequest, opts ...grpc.CallOption) (*QueryTotalDepositedResponse, error) - // Borrows queries hard borrows. - Borrows(ctx context.Context, in *QueryBorrowsRequest, opts ...grpc.CallOption) (*QueryBorrowsResponse, error) - // UnsyncedBorrows queries unsynced borrows. - UnsyncedBorrows(ctx context.Context, in *QueryUnsyncedBorrowsRequest, opts ...grpc.CallOption) (*QueryUnsyncedBorrowsResponse, error) - // TotalBorrowed queries total coins borrowed from hard liquidity pools. - TotalBorrowed(ctx context.Context, in *QueryTotalBorrowedRequest, opts ...grpc.CallOption) (*QueryTotalBorrowedResponse, error) - // InterestRate queries the hard module interest rates. - InterestRate(ctx context.Context, in *QueryInterestRateRequest, opts ...grpc.CallOption) (*QueryInterestRateResponse, error) - // Reserves queries total hard reserve coins. - Reserves(ctx context.Context, in *QueryReservesRequest, opts ...grpc.CallOption) (*QueryReservesResponse, error) - // InterestFactors queries hard module interest factors. - InterestFactors(ctx context.Context, in *QueryInterestFactorsRequest, opts ...grpc.CallOption) (*QueryInterestFactorsResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { - out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Accounts(ctx context.Context, in *QueryAccountsRequest, opts ...grpc.CallOption) (*QueryAccountsResponse, error) { - out := new(QueryAccountsResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/Accounts", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, error) { - out := new(QueryDepositsResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/Deposits", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) UnsyncedDeposits(ctx context.Context, in *QueryUnsyncedDepositsRequest, opts ...grpc.CallOption) (*QueryUnsyncedDepositsResponse, error) { - out := new(QueryUnsyncedDepositsResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/UnsyncedDeposits", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalDeposited(ctx context.Context, in *QueryTotalDepositedRequest, opts ...grpc.CallOption) (*QueryTotalDepositedResponse, error) { - out := new(QueryTotalDepositedResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/TotalDeposited", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Borrows(ctx context.Context, in *QueryBorrowsRequest, opts ...grpc.CallOption) (*QueryBorrowsResponse, error) { - out := new(QueryBorrowsResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/Borrows", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) UnsyncedBorrows(ctx context.Context, in *QueryUnsyncedBorrowsRequest, opts ...grpc.CallOption) (*QueryUnsyncedBorrowsResponse, error) { - out := new(QueryUnsyncedBorrowsResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/UnsyncedBorrows", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalBorrowed(ctx context.Context, in *QueryTotalBorrowedRequest, opts ...grpc.CallOption) (*QueryTotalBorrowedResponse, error) { - out := new(QueryTotalBorrowedResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/TotalBorrowed", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) InterestRate(ctx context.Context, in *QueryInterestRateRequest, opts ...grpc.CallOption) (*QueryInterestRateResponse, error) { - out := new(QueryInterestRateResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/InterestRate", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Reserves(ctx context.Context, in *QueryReservesRequest, opts ...grpc.CallOption) (*QueryReservesResponse, error) { - out := new(QueryReservesResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/Reserves", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) InterestFactors(ctx context.Context, in *QueryInterestFactorsRequest, opts ...grpc.CallOption) (*QueryInterestFactorsResponse, error) { - out := new(QueryInterestFactorsResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Query/InterestFactors", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries module params. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Accounts queries module accounts. - Accounts(context.Context, *QueryAccountsRequest) (*QueryAccountsResponse, error) - // Deposits queries hard deposits. - Deposits(context.Context, *QueryDepositsRequest) (*QueryDepositsResponse, error) - // UnsyncedDeposits queries unsynced deposits. - UnsyncedDeposits(context.Context, *QueryUnsyncedDepositsRequest) (*QueryUnsyncedDepositsResponse, error) - // TotalDeposited queries total coins deposited to hard liquidity pools. - TotalDeposited(context.Context, *QueryTotalDepositedRequest) (*QueryTotalDepositedResponse, error) - // Borrows queries hard borrows. - Borrows(context.Context, *QueryBorrowsRequest) (*QueryBorrowsResponse, error) - // UnsyncedBorrows queries unsynced borrows. - UnsyncedBorrows(context.Context, *QueryUnsyncedBorrowsRequest) (*QueryUnsyncedBorrowsResponse, error) - // TotalBorrowed queries total coins borrowed from hard liquidity pools. - TotalBorrowed(context.Context, *QueryTotalBorrowedRequest) (*QueryTotalBorrowedResponse, error) - // InterestRate queries the hard module interest rates. - InterestRate(context.Context, *QueryInterestRateRequest) (*QueryInterestRateResponse, error) - // Reserves queries total hard reserve coins. - Reserves(context.Context, *QueryReservesRequest) (*QueryReservesResponse, error) - // InterestFactors queries hard module interest factors. - InterestFactors(context.Context, *QueryInterestFactorsRequest) (*QueryInterestFactorsResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") -} -func (*UnimplementedQueryServer) Accounts(ctx context.Context, req *QueryAccountsRequest) (*QueryAccountsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Accounts not implemented") -} -func (*UnimplementedQueryServer) Deposits(ctx context.Context, req *QueryDepositsRequest) (*QueryDepositsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposits not implemented") -} -func (*UnimplementedQueryServer) UnsyncedDeposits(ctx context.Context, req *QueryUnsyncedDepositsRequest) (*QueryUnsyncedDepositsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UnsyncedDeposits not implemented") -} -func (*UnimplementedQueryServer) TotalDeposited(ctx context.Context, req *QueryTotalDepositedRequest) (*QueryTotalDepositedResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalDeposited not implemented") -} -func (*UnimplementedQueryServer) Borrows(ctx context.Context, req *QueryBorrowsRequest) (*QueryBorrowsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Borrows not implemented") -} -func (*UnimplementedQueryServer) UnsyncedBorrows(ctx context.Context, req *QueryUnsyncedBorrowsRequest) (*QueryUnsyncedBorrowsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UnsyncedBorrows not implemented") -} -func (*UnimplementedQueryServer) TotalBorrowed(ctx context.Context, req *QueryTotalBorrowedRequest) (*QueryTotalBorrowedResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalBorrowed not implemented") -} -func (*UnimplementedQueryServer) InterestRate(ctx context.Context, req *QueryInterestRateRequest) (*QueryInterestRateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method InterestRate not implemented") -} -func (*UnimplementedQueryServer) Reserves(ctx context.Context, req *QueryReservesRequest) (*QueryReservesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Reserves not implemented") -} -func (*UnimplementedQueryServer) InterestFactors(ctx context.Context, req *QueryInterestFactorsRequest) (*QueryInterestFactorsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method InterestFactors not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryParamsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Params(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/Params", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Accounts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAccountsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Accounts(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/Accounts", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Accounts(ctx, req.(*QueryAccountsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Deposits_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryDepositsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Deposits(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/Deposits", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Deposits(ctx, req.(*QueryDepositsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_UnsyncedDeposits_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryUnsyncedDepositsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).UnsyncedDeposits(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/UnsyncedDeposits", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).UnsyncedDeposits(ctx, req.(*QueryUnsyncedDepositsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalDeposited_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalDepositedRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalDeposited(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/TotalDeposited", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalDeposited(ctx, req.(*QueryTotalDepositedRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Borrows_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryBorrowsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Borrows(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/Borrows", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Borrows(ctx, req.(*QueryBorrowsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_UnsyncedBorrows_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryUnsyncedBorrowsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).UnsyncedBorrows(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/UnsyncedBorrows", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).UnsyncedBorrows(ctx, req.(*QueryUnsyncedBorrowsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalBorrowed_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalBorrowedRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalBorrowed(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/TotalBorrowed", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalBorrowed(ctx, req.(*QueryTotalBorrowedRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_InterestRate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryInterestRateRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).InterestRate(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/InterestRate", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).InterestRate(ctx, req.(*QueryInterestRateRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Reserves_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryReservesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Reserves(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/Reserves", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Reserves(ctx, req.(*QueryReservesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_InterestFactors_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryInterestFactorsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).InterestFactors(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Query/InterestFactors", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).InterestFactors(ctx, req.(*QueryInterestFactorsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.hard.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Accounts", - Handler: _Query_Accounts_Handler, - }, - { - MethodName: "Deposits", - Handler: _Query_Deposits_Handler, - }, - { - MethodName: "UnsyncedDeposits", - Handler: _Query_UnsyncedDeposits_Handler, - }, - { - MethodName: "TotalDeposited", - Handler: _Query_TotalDeposited_Handler, - }, - { - MethodName: "Borrows", - Handler: _Query_Borrows_Handler, - }, - { - MethodName: "UnsyncedBorrows", - Handler: _Query_UnsyncedBorrows_Handler, - }, - { - MethodName: "TotalBorrowed", - Handler: _Query_TotalBorrowed_Handler, - }, - { - MethodName: "InterestRate", - Handler: _Query_InterestRate_Handler, - }, - { - MethodName: "Reserves", - Handler: _Query_Reserves_Handler, - }, - { - MethodName: "InterestFactors", - Handler: _Query_InterestFactors_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/hard/v1beta1/query.proto", -} - -func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryAccountsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryAccountsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAccountsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryAccountsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryAccountsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAccountsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Accounts) > 0 { - for iNdEx := len(m.Accounts) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Accounts[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryDepositsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryDepositsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDepositsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryDepositsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Deposits) > 0 { - for iNdEx := len(m.Deposits) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposits[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryUnsyncedDepositsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryUnsyncedDepositsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryUnsyncedDepositsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryUnsyncedDepositsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryUnsyncedDepositsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryUnsyncedDepositsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Deposits) > 0 { - for iNdEx := len(m.Deposits) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposits[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalDepositedRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryTotalDepositedRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalDepositedRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalDepositedResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryTotalDepositedResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalDepositedResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.SuppliedCoins) > 0 { - for iNdEx := len(m.SuppliedCoins) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SuppliedCoins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - return len(dAtA) - i, nil -} - -func (m *QueryBorrowsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryBorrowsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryBorrowsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryBorrowsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryBorrowsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryBorrowsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Borrows) > 0 { - for iNdEx := len(m.Borrows) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Borrows[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryUnsyncedBorrowsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryUnsyncedBorrowsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryUnsyncedBorrowsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryUnsyncedBorrowsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryUnsyncedBorrowsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryUnsyncedBorrowsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Borrows) > 0 { - for iNdEx := len(m.Borrows) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Borrows[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalBorrowedRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryTotalBorrowedRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalBorrowedRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalBorrowedResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryTotalBorrowedResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalBorrowedResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.BorrowedCoins) > 0 { - for iNdEx := len(m.BorrowedCoins) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.BorrowedCoins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - return len(dAtA) - i, nil -} - -func (m *QueryInterestRateRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryInterestRateRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryInterestRateRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryInterestRateResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryInterestRateResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryInterestRateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.InterestRates) > 0 { - for iNdEx := len(m.InterestRates) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.InterestRates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryReservesRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryReservesRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryReservesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryReservesResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryReservesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryReservesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - return len(dAtA) - i, nil -} - -func (m *QueryInterestFactorsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryInterestFactorsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryInterestFactorsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryInterestFactorsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryInterestFactorsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryInterestFactorsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.InterestFactors) > 0 { - for iNdEx := len(m.InterestFactors) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.InterestFactors[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *DepositResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *DepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Index) > 0 { - for iNdEx := len(m.Index) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Index[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *SupplyInterestFactorResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *SupplyInterestFactorResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SupplyInterestFactorResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Value) > 0 { - i -= len(m.Value) - copy(dAtA[i:], m.Value) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Value))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *BorrowResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *BorrowResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *BorrowResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Index) > 0 { - for iNdEx := len(m.Index) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Index[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Borrower) > 0 { - i -= len(m.Borrower) - copy(dAtA[i:], m.Borrower) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Borrower))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *BorrowInterestFactorResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *BorrowInterestFactorResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *BorrowInterestFactorResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Value) > 0 { - i -= len(m.Value) - copy(dAtA[i:], m.Value) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Value))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MoneyMarketInterestRate) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MoneyMarketInterestRate) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MoneyMarketInterestRate) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.BorrowInterestRate) > 0 { - i -= len(m.BorrowInterestRate) - copy(dAtA[i:], m.BorrowInterestRate) - i = encodeVarintQuery(dAtA, i, uint64(len(m.BorrowInterestRate))) - i-- - dAtA[i] = 0x1a - } - if len(m.SupplyInterestRate) > 0 { - i -= len(m.SupplyInterestRate) - copy(dAtA[i:], m.SupplyInterestRate) - i = encodeVarintQuery(dAtA, i, uint64(len(m.SupplyInterestRate))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *InterestFactor) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *InterestFactor) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *InterestFactor) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.SupplyInterestFactor) > 0 { - i -= len(m.SupplyInterestFactor) - copy(dAtA[i:], m.SupplyInterestFactor) - i = encodeVarintQuery(dAtA, i, uint64(len(m.SupplyInterestFactor))) - i-- - dAtA[i] = 0x1a - } - if len(m.BorrowInterestFactor) > 0 { - i -= len(m.BorrowInterestFactor) - copy(dAtA[i:], m.BorrowInterestFactor) - i = encodeVarintQuery(dAtA, i, uint64(len(m.BorrowInterestFactor))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryParamsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryAccountsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryAccountsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Accounts) > 0 { - for _, e := range m.Accounts { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryDepositsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDepositsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Deposits) > 0 { - for _, e := range m.Deposits { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryUnsyncedDepositsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryUnsyncedDepositsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Deposits) > 0 { - for _, e := range m.Deposits { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryTotalDepositedRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryTotalDepositedResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.SuppliedCoins) > 0 { - for _, e := range m.SuppliedCoins { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryBorrowsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryBorrowsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Borrows) > 0 { - for _, e := range m.Borrows { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryUnsyncedBorrowsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryUnsyncedBorrowsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Borrows) > 0 { - for _, e := range m.Borrows { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryTotalBorrowedRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryTotalBorrowedResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.BorrowedCoins) > 0 { - for _, e := range m.BorrowedCoins { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryInterestRateRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryInterestRateResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.InterestRates) > 0 { - for _, e := range m.InterestRates { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryReservesRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryReservesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryInterestFactorsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryInterestFactorsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.InterestFactors) > 0 { - for _, e := range m.InterestFactors { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *DepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.Index) > 0 { - for _, e := range m.Index { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *SupplyInterestFactorResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Value) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *BorrowResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Borrower) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.Index) > 0 { - for _, e := range m.Index { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *BorrowInterestFactorResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Value) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *MoneyMarketInterestRate) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.SupplyInterestRate) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.BorrowInterestRate) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *InterestFactor) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.BorrowInterestFactor) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.SupplyInterestFactor) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryAccountsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryAccountsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAccountsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryAccountsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryAccountsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAccountsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Accounts", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Accounts = append(m.Accounts, types.ModuleAccount{}) - if err := m.Accounts[len(m.Accounts)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDepositsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryDepositsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDepositsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryDepositsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposits", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Deposits = append(m.Deposits, DepositResponse{}) - if err := m.Deposits[len(m.Deposits)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryUnsyncedDepositsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryUnsyncedDepositsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryUnsyncedDepositsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryUnsyncedDepositsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryUnsyncedDepositsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryUnsyncedDepositsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposits", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Deposits = append(m.Deposits, DepositResponse{}) - if err := m.Deposits[len(m.Deposits)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTotalDepositedRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTotalDepositedRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalDepositedRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTotalDepositedResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTotalDepositedResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalDepositedResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SuppliedCoins", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SuppliedCoins = append(m.SuppliedCoins, types1.Coin{}) - if err := m.SuppliedCoins[len(m.SuppliedCoins)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryBorrowsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryBorrowsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryBorrowsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryBorrowsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryBorrowsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryBorrowsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Borrows", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Borrows = append(m.Borrows, BorrowResponse{}) - if err := m.Borrows[len(m.Borrows)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryUnsyncedBorrowsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryUnsyncedBorrowsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryUnsyncedBorrowsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryUnsyncedBorrowsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryUnsyncedBorrowsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryUnsyncedBorrowsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Borrows", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Borrows = append(m.Borrows, BorrowResponse{}) - if err := m.Borrows[len(m.Borrows)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTotalBorrowedRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTotalBorrowedRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalBorrowedRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTotalBorrowedResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTotalBorrowedResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalBorrowedResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BorrowedCoins", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.BorrowedCoins = append(m.BorrowedCoins, types1.Coin{}) - if err := m.BorrowedCoins[len(m.BorrowedCoins)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryInterestRateRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryInterestRateRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryInterestRateRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryInterestRateResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryInterestRateResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryInterestRateResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InterestRates", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.InterestRates = append(m.InterestRates, MoneyMarketInterestRate{}) - if err := m.InterestRates[len(m.InterestRates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryReservesRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryReservesRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryReservesRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryReservesResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryReservesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryReservesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types1.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryInterestFactorsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryInterestFactorsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryInterestFactorsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryInterestFactorsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryInterestFactorsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryInterestFactorsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InterestFactors", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.InterestFactors = append(m.InterestFactors, InterestFactor{}) - if err := m.InterestFactors[len(m.InterestFactors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DepositResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types1.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Index = append(m.Index, SupplyInterestFactorResponse{}) - if err := m.Index[len(m.Index)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *SupplyInterestFactorResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: SupplyInterestFactorResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SupplyInterestFactorResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Value = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *BorrowResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: BorrowResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BorrowResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Borrower", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Borrower = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types1.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Index", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Index = append(m.Index, BorrowInterestFactorResponse{}) - if err := m.Index[len(m.Index)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *BorrowInterestFactorResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: BorrowInterestFactorResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BorrowInterestFactorResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Value = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MoneyMarketInterestRate) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MoneyMarketInterestRate: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MoneyMarketInterestRate: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SupplyInterestRate", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SupplyInterestRate = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BorrowInterestRate", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.BorrowInterestRate = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *InterestFactor) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: InterestFactor: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: InterestFactor: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BorrowInterestFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.BorrowInterestFactor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SupplyInterestFactor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SupplyInterestFactor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/hard/types/query.pb.gw.go b/x/hard/types/query.pb.gw.go deleted file mode 100644 index 725144d6..00000000 --- a/x/hard/types/query.pb.gw.go +++ /dev/null @@ -1,965 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/hard/v1beta1/query.proto - -/* -Package types is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package types - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join - -func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Params(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Accounts_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAccountsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Accounts(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Accounts_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAccountsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Accounts(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Deposits_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Deposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Deposits(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Deposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Deposits(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_UnsyncedDeposits_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_UnsyncedDeposits_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryUnsyncedDepositsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_UnsyncedDeposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.UnsyncedDeposits(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_UnsyncedDeposits_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryUnsyncedDepositsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_UnsyncedDeposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.UnsyncedDeposits(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_TotalDeposited_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_TotalDeposited_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalDepositedRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_TotalDeposited_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.TotalDeposited(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TotalDeposited_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalDepositedRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_TotalDeposited_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.TotalDeposited(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Borrows_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Borrows_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryBorrowsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Borrows_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Borrows(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Borrows_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryBorrowsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Borrows_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Borrows(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_UnsyncedBorrows_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_UnsyncedBorrows_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryUnsyncedBorrowsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_UnsyncedBorrows_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.UnsyncedBorrows(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_UnsyncedBorrows_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryUnsyncedBorrowsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_UnsyncedBorrows_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.UnsyncedBorrows(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_TotalBorrowed_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_TotalBorrowed_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalBorrowedRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_TotalBorrowed_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.TotalBorrowed(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TotalBorrowed_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalBorrowedRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_TotalBorrowed_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.TotalBorrowed(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_InterestRate_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_InterestRate_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryInterestRateRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_InterestRate_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.InterestRate(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_InterestRate_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryInterestRateRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_InterestRate_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.InterestRate(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Reserves_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Reserves_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryReservesRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Reserves_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Reserves(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Reserves_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryReservesRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Reserves_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Reserves(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_InterestFactors_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_InterestFactors_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryInterestFactorsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_InterestFactors_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.InterestFactors(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_InterestFactors_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryInterestFactorsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_InterestFactors_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.InterestFactors(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Accounts_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Accounts_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Accounts_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Deposits_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Deposits_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Deposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_UnsyncedDeposits_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_UnsyncedDeposits_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_UnsyncedDeposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalDeposited_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_TotalDeposited_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TotalDeposited_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Borrows_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Borrows_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Borrows_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_UnsyncedBorrows_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_UnsyncedBorrows_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_UnsyncedBorrows_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalBorrowed_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_TotalBorrowed_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TotalBorrowed_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_InterestRate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_InterestRate_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_InterestRate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Reserves_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Reserves_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Reserves_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_InterestFactors_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_InterestFactors_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_InterestFactors_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Accounts_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Accounts_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Accounts_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Deposits_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Deposits_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Deposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_UnsyncedDeposits_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_UnsyncedDeposits_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_UnsyncedDeposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalDeposited_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_TotalDeposited_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TotalDeposited_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Borrows_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Borrows_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Borrows_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_UnsyncedBorrows_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_UnsyncedBorrows_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_UnsyncedBorrows_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalBorrowed_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_TotalBorrowed_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TotalBorrowed_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_InterestRate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_InterestRate_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_InterestRate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Reserves_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Reserves_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Reserves_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_InterestFactors_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_InterestFactors_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_InterestFactors_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Accounts_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "accounts"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Deposits_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "deposits"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_UnsyncedDeposits_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "unsynced-deposits"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TotalDeposited_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "total-deposited"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Borrows_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "borrows"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_UnsyncedBorrows_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "unsynced-borrows"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TotalBorrowed_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "total-borrowed"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_InterestRate_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "interest-rate"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Reserves_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "reserves"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_InterestFactors_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "hard", "v1beta1", "interest-factors"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Accounts_0 = runtime.ForwardResponseMessage - - forward_Query_Deposits_0 = runtime.ForwardResponseMessage - - forward_Query_UnsyncedDeposits_0 = runtime.ForwardResponseMessage - - forward_Query_TotalDeposited_0 = runtime.ForwardResponseMessage - - forward_Query_Borrows_0 = runtime.ForwardResponseMessage - - forward_Query_UnsyncedBorrows_0 = runtime.ForwardResponseMessage - - forward_Query_TotalBorrowed_0 = runtime.ForwardResponseMessage - - forward_Query_InterestRate_0 = runtime.ForwardResponseMessage - - forward_Query_Reserves_0 = runtime.ForwardResponseMessage - - forward_Query_InterestFactors_0 = runtime.ForwardResponseMessage -) diff --git a/x/hard/types/tx.pb.go b/x/hard/types/tx.pb.go deleted file mode 100644 index 4d7a417f..00000000 --- a/x/hard/types/tx.pb.go +++ /dev/null @@ -1,2216 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/hard/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// MsgDeposit defines the Msg/Deposit request type. -type MsgDeposit struct { - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *MsgDeposit) Reset() { *m = MsgDeposit{} } -func (m *MsgDeposit) String() string { return proto.CompactTextString(m) } -func (*MsgDeposit) ProtoMessage() {} -func (*MsgDeposit) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{0} -} -func (m *MsgDeposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDeposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDeposit.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgDeposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDeposit.Merge(m, src) -} -func (m *MsgDeposit) XXX_Size() int { - return m.Size() -} -func (m *MsgDeposit) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDeposit.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDeposit proto.InternalMessageInfo - -func (m *MsgDeposit) GetDepositor() string { - if m != nil { - return m.Depositor - } - return "" -} - -func (m *MsgDeposit) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -// MsgDepositResponse defines the Msg/Deposit response type. -type MsgDepositResponse struct { -} - -func (m *MsgDepositResponse) Reset() { *m = MsgDepositResponse{} } -func (m *MsgDepositResponse) String() string { return proto.CompactTextString(m) } -func (*MsgDepositResponse) ProtoMessage() {} -func (*MsgDepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{1} -} -func (m *MsgDepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDepositResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgDepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDepositResponse.Merge(m, src) -} -func (m *MsgDepositResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgDepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDepositResponse proto.InternalMessageInfo - -// MsgWithdraw defines the Msg/Withdraw request type. -type MsgWithdraw struct { - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *MsgWithdraw) Reset() { *m = MsgWithdraw{} } -func (m *MsgWithdraw) String() string { return proto.CompactTextString(m) } -func (*MsgWithdraw) ProtoMessage() {} -func (*MsgWithdraw) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{2} -} -func (m *MsgWithdraw) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdraw) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdraw.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgWithdraw) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdraw.Merge(m, src) -} -func (m *MsgWithdraw) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdraw) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdraw.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdraw proto.InternalMessageInfo - -func (m *MsgWithdraw) GetDepositor() string { - if m != nil { - return m.Depositor - } - return "" -} - -func (m *MsgWithdraw) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -type MsgWithdrawResponse struct { -} - -func (m *MsgWithdrawResponse) Reset() { *m = MsgWithdrawResponse{} } -func (m *MsgWithdrawResponse) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawResponse) ProtoMessage() {} -func (*MsgWithdrawResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{3} -} -func (m *MsgWithdrawResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgWithdrawResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawResponse.Merge(m, src) -} -func (m *MsgWithdrawResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawResponse proto.InternalMessageInfo - -// MsgBorrow defines the Msg/Borrow request type. -type MsgBorrow struct { - Borrower string `protobuf:"bytes,1,opt,name=borrower,proto3" json:"borrower,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *MsgBorrow) Reset() { *m = MsgBorrow{} } -func (m *MsgBorrow) String() string { return proto.CompactTextString(m) } -func (*MsgBorrow) ProtoMessage() {} -func (*MsgBorrow) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{4} -} -func (m *MsgBorrow) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgBorrow) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgBorrow.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgBorrow) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgBorrow.Merge(m, src) -} -func (m *MsgBorrow) XXX_Size() int { - return m.Size() -} -func (m *MsgBorrow) XXX_DiscardUnknown() { - xxx_messageInfo_MsgBorrow.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgBorrow proto.InternalMessageInfo - -func (m *MsgBorrow) GetBorrower() string { - if m != nil { - return m.Borrower - } - return "" -} - -func (m *MsgBorrow) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -// MsgBorrowResponse defines the Msg/Borrow response type. -type MsgBorrowResponse struct { -} - -func (m *MsgBorrowResponse) Reset() { *m = MsgBorrowResponse{} } -func (m *MsgBorrowResponse) String() string { return proto.CompactTextString(m) } -func (*MsgBorrowResponse) ProtoMessage() {} -func (*MsgBorrowResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{5} -} -func (m *MsgBorrowResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgBorrowResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgBorrowResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgBorrowResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgBorrowResponse.Merge(m, src) -} -func (m *MsgBorrowResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgBorrowResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgBorrowResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgBorrowResponse proto.InternalMessageInfo - -// MsgRepay defines the Msg/Repay request type. -type MsgRepay struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,3,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *MsgRepay) Reset() { *m = MsgRepay{} } -func (m *MsgRepay) String() string { return proto.CompactTextString(m) } -func (*MsgRepay) ProtoMessage() {} -func (*MsgRepay) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{6} -} -func (m *MsgRepay) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgRepay) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgRepay.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgRepay) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgRepay.Merge(m, src) -} -func (m *MsgRepay) XXX_Size() int { - return m.Size() -} -func (m *MsgRepay) XXX_DiscardUnknown() { - xxx_messageInfo_MsgRepay.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgRepay proto.InternalMessageInfo - -func (m *MsgRepay) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgRepay) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *MsgRepay) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -// MsgRepayResponse defines the Msg/Repay response type. -type MsgRepayResponse struct { -} - -func (m *MsgRepayResponse) Reset() { *m = MsgRepayResponse{} } -func (m *MsgRepayResponse) String() string { return proto.CompactTextString(m) } -func (*MsgRepayResponse) ProtoMessage() {} -func (*MsgRepayResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{7} -} -func (m *MsgRepayResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgRepayResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgRepayResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgRepayResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgRepayResponse.Merge(m, src) -} -func (m *MsgRepayResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgRepayResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgRepayResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgRepayResponse proto.InternalMessageInfo - -// MsgLiquidate defines the Msg/Liquidate request type. -type MsgLiquidate struct { - Keeper string `protobuf:"bytes,1,opt,name=keeper,proto3" json:"keeper,omitempty"` - Borrower string `protobuf:"bytes,2,opt,name=borrower,proto3" json:"borrower,omitempty"` -} - -func (m *MsgLiquidate) Reset() { *m = MsgLiquidate{} } -func (m *MsgLiquidate) String() string { return proto.CompactTextString(m) } -func (*MsgLiquidate) ProtoMessage() {} -func (*MsgLiquidate) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{8} -} -func (m *MsgLiquidate) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgLiquidate) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgLiquidate.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgLiquidate) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgLiquidate.Merge(m, src) -} -func (m *MsgLiquidate) XXX_Size() int { - return m.Size() -} -func (m *MsgLiquidate) XXX_DiscardUnknown() { - xxx_messageInfo_MsgLiquidate.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgLiquidate proto.InternalMessageInfo - -func (m *MsgLiquidate) GetKeeper() string { - if m != nil { - return m.Keeper - } - return "" -} - -func (m *MsgLiquidate) GetBorrower() string { - if m != nil { - return m.Borrower - } - return "" -} - -// MsgLiquidateResponse defines the Msg/Liquidate response type. -type MsgLiquidateResponse struct { -} - -func (m *MsgLiquidateResponse) Reset() { *m = MsgLiquidateResponse{} } -func (m *MsgLiquidateResponse) String() string { return proto.CompactTextString(m) } -func (*MsgLiquidateResponse) ProtoMessage() {} -func (*MsgLiquidateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_72cf8eb667c23b8a, []int{9} -} -func (m *MsgLiquidateResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgLiquidateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgLiquidateResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgLiquidateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgLiquidateResponse.Merge(m, src) -} -func (m *MsgLiquidateResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgLiquidateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgLiquidateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgLiquidateResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgDeposit)(nil), "kava.hard.v1beta1.MsgDeposit") - proto.RegisterType((*MsgDepositResponse)(nil), "kava.hard.v1beta1.MsgDepositResponse") - proto.RegisterType((*MsgWithdraw)(nil), "kava.hard.v1beta1.MsgWithdraw") - proto.RegisterType((*MsgWithdrawResponse)(nil), "kava.hard.v1beta1.MsgWithdrawResponse") - proto.RegisterType((*MsgBorrow)(nil), "kava.hard.v1beta1.MsgBorrow") - proto.RegisterType((*MsgBorrowResponse)(nil), "kava.hard.v1beta1.MsgBorrowResponse") - proto.RegisterType((*MsgRepay)(nil), "kava.hard.v1beta1.MsgRepay") - proto.RegisterType((*MsgRepayResponse)(nil), "kava.hard.v1beta1.MsgRepayResponse") - proto.RegisterType((*MsgLiquidate)(nil), "kava.hard.v1beta1.MsgLiquidate") - proto.RegisterType((*MsgLiquidateResponse)(nil), "kava.hard.v1beta1.MsgLiquidateResponse") -} - -func init() { proto.RegisterFile("kava/hard/v1beta1/tx.proto", fileDescriptor_72cf8eb667c23b8a) } - -var fileDescriptor_72cf8eb667c23b8a = []byte{ - // 536 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x55, 0x4d, 0x8f, 0xd2, 0x40, - 0x18, 0xa6, 0x90, 0x45, 0x78, 0xd7, 0x83, 0x3b, 0x8b, 0x86, 0xad, 0x5a, 0x36, 0xf8, 0xb1, 0x5c, - 0x68, 0xd9, 0xd5, 0x78, 0x5f, 0xf4, 0x62, 0xb2, 0x8d, 0x09, 0xc6, 0x98, 0x78, 0x31, 0x53, 0x3a, - 0x19, 0x1a, 0xa4, 0x53, 0xfb, 0x0e, 0xb0, 0xfb, 0x2f, 0x3c, 0xfb, 0x03, 0x4c, 0xdc, 0xb3, 0x3f, - 0x62, 0x8f, 0xab, 0x27, 0x4f, 0x6a, 0xe0, 0x8f, 0x18, 0x3a, 0xed, 0x80, 0x91, 0x00, 0x17, 0xcd, - 0x9e, 0x98, 0xf6, 0xf9, 0xe0, 0x79, 0x32, 0xef, 0x4c, 0xc1, 0xec, 0xd3, 0x11, 0x75, 0x7a, 0x34, - 0xf6, 0x9d, 0xd1, 0xa1, 0xc7, 0x24, 0x3d, 0x74, 0xe4, 0xa9, 0x1d, 0xc5, 0x42, 0x0a, 0xb2, 0x33, - 0xc3, 0xec, 0x19, 0x66, 0xa7, 0x98, 0x69, 0x75, 0x05, 0x0e, 0x04, 0x3a, 0x1e, 0x45, 0xa6, 0x05, - 0x5d, 0x11, 0x84, 0x4a, 0x62, 0xee, 0x29, 0xfc, 0x6d, 0xf2, 0xe4, 0xa8, 0x87, 0x14, 0xaa, 0x70, - 0xc1, 0x85, 0x7a, 0x3f, 0x5b, 0xa9, 0xb7, 0xf5, 0xcf, 0x06, 0x80, 0x8b, 0xfc, 0x19, 0x8b, 0x04, - 0x06, 0x92, 0x3c, 0x81, 0xb2, 0xaf, 0x96, 0x22, 0xae, 0x1a, 0xfb, 0x46, 0xa3, 0xdc, 0xae, 0x7e, - 0xfb, 0xd2, 0xac, 0xa4, 0x4e, 0xc7, 0xbe, 0x1f, 0x33, 0xc4, 0x97, 0x32, 0x0e, 0x42, 0xde, 0x99, - 0x53, 0x49, 0x17, 0x8a, 0x74, 0x20, 0x86, 0xa1, 0xac, 0xe6, 0xf7, 0x0b, 0x8d, 0xed, 0xa3, 0x3d, - 0x3b, 0x55, 0xcc, 0x82, 0x66, 0xe9, 0xed, 0xa7, 0x22, 0x08, 0xdb, 0xad, 0x8b, 0x1f, 0xb5, 0xdc, - 0xf9, 0xcf, 0x5a, 0x83, 0x07, 0xb2, 0x37, 0xf4, 0xec, 0xae, 0x18, 0xa4, 0x41, 0xd3, 0x9f, 0x26, - 0xfa, 0x7d, 0x47, 0x9e, 0x45, 0x0c, 0x13, 0x01, 0x76, 0x52, 0xeb, 0x7a, 0x05, 0xc8, 0x3c, 0x6a, - 0x87, 0x61, 0x24, 0x42, 0x64, 0xf5, 0x73, 0x03, 0xb6, 0x5d, 0xe4, 0xaf, 0x03, 0xd9, 0xf3, 0x63, - 0x3a, 0xbe, 0xda, 0x15, 0x6e, 0xc2, 0xee, 0x42, 0x56, 0xdd, 0xe1, 0x93, 0x01, 0x65, 0x17, 0x79, - 0x5b, 0xc4, 0xb1, 0x18, 0x93, 0xc7, 0x50, 0xf2, 0x92, 0x15, 0x5b, 0x5f, 0x40, 0x33, 0xff, 0x4f, - 0xfe, 0x5d, 0xd8, 0xd1, 0x39, 0x75, 0xfa, 0xaf, 0x06, 0x94, 0x5c, 0xe4, 0x1d, 0x16, 0xd1, 0x33, - 0xd2, 0x82, 0x22, 0xb2, 0xd0, 0xdf, 0x20, 0x7a, 0xca, 0x23, 0x36, 0x6c, 0x89, 0x71, 0xc8, 0xe2, - 0x6a, 0x7e, 0x8d, 0x40, 0xd1, 0x16, 0x8a, 0x16, 0xfe, 0x5d, 0x51, 0x02, 0x37, 0xb2, 0x4a, 0xba, - 0xe7, 0x08, 0xae, 0xbb, 0xc8, 0x4f, 0x82, 0xf7, 0xc3, 0xc0, 0xa7, 0x92, 0xcd, 0xaa, 0xf6, 0x19, - 0x8b, 0x36, 0xa9, 0xaa, 0x78, 0x7f, 0xec, 0x6c, 0x7e, 0xd3, 0x9d, 0xad, 0xdf, 0x82, 0xca, 0xe2, - 0xff, 0x66, 0x79, 0x8e, 0x3e, 0x16, 0xa0, 0xe0, 0x22, 0x27, 0x2f, 0xe0, 0x5a, 0x76, 0x7e, 0xef, - 0xda, 0x7f, 0xdd, 0x19, 0xf6, 0xfc, 0xcc, 0x98, 0x0f, 0x56, 0xc2, 0x99, 0x31, 0xe9, 0x40, 0x49, - 0x1f, 0x27, 0x6b, 0xb9, 0x24, 0xc3, 0xcd, 0x87, 0xab, 0x71, 0xed, 0x79, 0x02, 0xc5, 0x74, 0xbc, - 0xef, 0x2c, 0x57, 0x28, 0xd4, 0xbc, 0xbf, 0x0a, 0xd5, 0x6e, 0xcf, 0x61, 0x4b, 0x8d, 0xdb, 0xed, - 0xe5, 0xf4, 0x04, 0x34, 0xef, 0xad, 0x00, 0xb5, 0xd5, 0x2b, 0x28, 0xcf, 0xb7, 0xb4, 0xb6, 0x5c, - 0xa1, 0x09, 0xe6, 0xc1, 0x1a, 0x42, 0x66, 0xdb, 0x3e, 0xbe, 0x98, 0x58, 0xc6, 0xe5, 0xc4, 0x32, - 0x7e, 0x4d, 0x2c, 0xe3, 0xc3, 0xd4, 0xca, 0x5d, 0x4e, 0xad, 0xdc, 0xf7, 0xa9, 0x95, 0x7b, 0x73, - 0xb0, 0x30, 0x8c, 0x2d, 0xfe, 0x8e, 0x7a, 0xe8, 0xb4, 0x78, 0xb3, 0xdb, 0xa3, 0x41, 0xe8, 0x9c, - 0xaa, 0x4f, 0x41, 0x32, 0x91, 0x5e, 0x31, 0xb9, 0xa2, 0x1f, 0xfd, 0x0e, 0x00, 0x00, 0xff, 0xff, - 0x21, 0x79, 0xa2, 0xad, 0x24, 0x06, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - // Deposit defines a method for depositing funds to hard liquidity pool. - Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) - // Withdraw defines a method for withdrawing funds from hard liquidity pool. - Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) - // Borrow defines a method for borrowing funds from hard liquidity pool. - Borrow(ctx context.Context, in *MsgBorrow, opts ...grpc.CallOption) (*MsgBorrowResponse, error) - // Repay defines a method for repaying funds borrowed from hard liquidity pool. - Repay(ctx context.Context, in *MsgRepay, opts ...grpc.CallOption) (*MsgRepayResponse, error) - // Liquidate defines a method for attempting to liquidate a borrower that is over their loan-to-value. - Liquidate(ctx context.Context, in *MsgLiquidate, opts ...grpc.CallOption) (*MsgLiquidateResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) { - out := new(MsgDepositResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Msg/Deposit", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) { - out := new(MsgWithdrawResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Msg/Withdraw", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Borrow(ctx context.Context, in *MsgBorrow, opts ...grpc.CallOption) (*MsgBorrowResponse, error) { - out := new(MsgBorrowResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Msg/Borrow", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Repay(ctx context.Context, in *MsgRepay, opts ...grpc.CallOption) (*MsgRepayResponse, error) { - out := new(MsgRepayResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Msg/Repay", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Liquidate(ctx context.Context, in *MsgLiquidate, opts ...grpc.CallOption) (*MsgLiquidateResponse, error) { - out := new(MsgLiquidateResponse) - err := c.cc.Invoke(ctx, "/kava.hard.v1beta1.Msg/Liquidate", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // Deposit defines a method for depositing funds to hard liquidity pool. - Deposit(context.Context, *MsgDeposit) (*MsgDepositResponse, error) - // Withdraw defines a method for withdrawing funds from hard liquidity pool. - Withdraw(context.Context, *MsgWithdraw) (*MsgWithdrawResponse, error) - // Borrow defines a method for borrowing funds from hard liquidity pool. - Borrow(context.Context, *MsgBorrow) (*MsgBorrowResponse, error) - // Repay defines a method for repaying funds borrowed from hard liquidity pool. - Repay(context.Context, *MsgRepay) (*MsgRepayResponse, error) - // Liquidate defines a method for attempting to liquidate a borrower that is over their loan-to-value. - Liquidate(context.Context, *MsgLiquidate) (*MsgLiquidateResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Deposit(ctx context.Context, req *MsgDeposit) (*MsgDepositResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposit not implemented") -} -func (*UnimplementedMsgServer) Withdraw(ctx context.Context, req *MsgWithdraw) (*MsgWithdrawResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Withdraw not implemented") -} -func (*UnimplementedMsgServer) Borrow(ctx context.Context, req *MsgBorrow) (*MsgBorrowResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Borrow not implemented") -} -func (*UnimplementedMsgServer) Repay(ctx context.Context, req *MsgRepay) (*MsgRepayResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Repay not implemented") -} -func (*UnimplementedMsgServer) Liquidate(ctx context.Context, req *MsgLiquidate) (*MsgLiquidateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Liquidate not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Deposit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgDeposit) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Deposit(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Msg/Deposit", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Deposit(ctx, req.(*MsgDeposit)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Withdraw_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgWithdraw) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Withdraw(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Msg/Withdraw", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Withdraw(ctx, req.(*MsgWithdraw)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Borrow_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgBorrow) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Borrow(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Msg/Borrow", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Borrow(ctx, req.(*MsgBorrow)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Repay_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgRepay) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Repay(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Msg/Repay", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Repay(ctx, req.(*MsgRepay)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Liquidate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgLiquidate) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Liquidate(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.hard.v1beta1.Msg/Liquidate", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Liquidate(ctx, req.(*MsgLiquidate)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.hard.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Deposit", - Handler: _Msg_Deposit_Handler, - }, - { - MethodName: "Withdraw", - Handler: _Msg_Withdraw_Handler, - }, - { - MethodName: "Borrow", - Handler: _Msg_Borrow_Handler, - }, - { - MethodName: "Repay", - Handler: _Msg_Repay_Handler, - }, - { - MethodName: "Liquidate", - Handler: _Msg_Liquidate_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/hard/v1beta1/tx.proto", -} - -func (m *MsgDeposit) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgDeposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDeposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgDepositResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgDepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgWithdraw) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgWithdraw) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdraw) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgWithdrawResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgBorrow) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgBorrow) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgBorrow) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Borrower) > 0 { - i -= len(m.Borrower) - copy(dAtA[i:], m.Borrower) - i = encodeVarintTx(dAtA, i, uint64(len(m.Borrower))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgBorrowResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgBorrowResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgBorrowResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgRepay) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgRepay) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgRepay) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintTx(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgRepayResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgRepayResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgRepayResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgLiquidate) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgLiquidate) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgLiquidate) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Borrower) > 0 { - i -= len(m.Borrower) - copy(dAtA[i:], m.Borrower) - i = encodeVarintTx(dAtA, i, uint64(len(m.Borrower))) - i-- - dAtA[i] = 0x12 - } - if len(m.Keeper) > 0 { - i -= len(m.Keeper) - copy(dAtA[i:], m.Keeper) - i = encodeVarintTx(dAtA, i, uint64(len(m.Keeper))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgLiquidateResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgLiquidateResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgLiquidateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgDeposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgDepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgWithdraw) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgWithdrawResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgBorrow) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Borrower) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgBorrowResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgRepay) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgRepayResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgLiquidate) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Keeper) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Borrower) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgLiquidateResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgDeposit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDeposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDeposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDepositResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdraw) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdraw: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdraw: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgBorrow) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgBorrow: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgBorrow: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Borrower", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Borrower = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgBorrowResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgBorrowResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgBorrowResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgRepay) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgRepay: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgRepay: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgRepayResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgRepayResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgRepayResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgLiquidate) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgLiquidate: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgLiquidate: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Keeper", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Keeper = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Borrower", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Borrower = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgLiquidateResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgLiquidateResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgLiquidateResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/incentive/abci.go b/x/incentive/abci.go deleted file mode 100644 index bbf0a4c6..00000000 --- a/x/incentive/abci.go +++ /dev/null @@ -1,43 +0,0 @@ -package incentive - -import ( - "fmt" - "time" - - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/incentive/keeper" - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// BeginBlocker runs at the start of every block -func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { - defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) - - params := k.GetParams(ctx) - - for _, rp := range params.USDXMintingRewardPeriods { - k.AccumulateUSDXMintingRewards(ctx, rp) - } - for _, rp := range params.HardSupplyRewardPeriods { - k.AccumulateHardSupplyRewards(ctx, rp) - } - for _, rp := range params.HardBorrowRewardPeriods { - k.AccumulateHardBorrowRewards(ctx, rp) - } - for _, rp := range params.DelegatorRewardPeriods { - k.AccumulateDelegatorRewards(ctx, rp) - } - for _, rp := range params.SwapRewardPeriods { - k.AccumulateSwapRewards(ctx, rp) - } - for _, rp := range params.SavingsRewardPeriods { - k.AccumulateSavingsRewards(ctx, rp) - } - for _, rp := range params.EarnRewardPeriods { - if err := k.AccumulateEarnRewards(ctx, rp); err != nil { - panic(fmt.Sprintf("failed to accumulate earn rewards: %s", err)) - } - } -} diff --git a/x/incentive/client/cli/query.go b/x/incentive/client/cli/query.go deleted file mode 100644 index a52336a2..00000000 --- a/x/incentive/client/cli/query.go +++ /dev/null @@ -1,185 +0,0 @@ -package cli - -import ( - "context" - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/0glabs/0g-chain/x/incentive/keeper" - "github.com/0glabs/0g-chain/x/incentive/types" -) - -const ( - flagOwner = "owner" - flagType = "type" - flagUnsynced = "unsynced" - flagDenom = "denom" -) - -var rewardTypes = []string{ - keeper.RewardTypeHard, - keeper.RewardTypeUSDXMinting, - keeper.RewardTypeDelegator, - keeper.RewardTypeSwap, - keeper.RewardTypeSavings, - keeper.RewardTypeEarn, -} - -// GetQueryCmd returns the cli query commands for the incentive module -func GetQueryCmd() *cobra.Command { - incentiveQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the incentive module", - } - - cmds := []*cobra.Command{ - queryParamsCmd(), - queryRewardsCmd(), - queryRewardFactorsCmd(), - queryApyCmd(), - } - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - incentiveQueryCmd.AddCommand(cmds...) - - return incentiveQueryCmd -} - -func queryRewardsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "rewards", - Short: "query claimable rewards", - Long: strings.TrimSpace( - fmt.Sprintf(`Query rewards with optional flags for owner and type - - Example: - $ %[1]s query %[2]s rewards - $ %[1]s query %[2]s rewards --owner kava15qdefkmwswysgg4qxgqpqr35k3m49pkx2jdfnw - $ %[1]s query %[2]s rewards --type hard - $ %[1]s query %[2]s rewards --type usdx-minting - $ %[1]s query %[2]s rewards --type delegator - $ %[1]s query %[2]s rewards --type swap - $ %[1]s query %[2]s rewards --type savings - $ %[1]s query %[2]s rewards --type earn - $ %[1]s query %[2]s rewards --type hard --owner kava15qdefkmwswysgg4qxgqpqr35k3m49pkx2jdfnw - $ %[1]s query %[2]s rewards --type hard --unsynced - `, - version.AppName, types.ModuleName)), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - strOwner, _ := cmd.Flags().GetString(flagOwner) - strType, _ := cmd.Flags().GetString(flagType) - boolUnsynced, _ := cmd.Flags().GetBool(flagUnsynced) - - // Prepare params for querier - var owner sdk.AccAddress - if strOwner != "" { - if owner, err = sdk.AccAddressFromBech32(strOwner); err != nil { - return err - } - } - - rewardType := strings.ToLower(strType) - queryClient := types.NewQueryClient(cliCtx) - request := types.QueryRewardsRequest{ - RewardType: rewardType, - Owner: owner.String(), - Unsynchronized: boolUnsynced, - } - rewards, err := queryClient.Rewards(context.Background(), &request) - if err != nil { - return err - } - return cliCtx.PrintProto(rewards) - }, - } - cmd.Flags().String(flagOwner, "", "(optional) filter by owner address") - cmd.Flags().String(flagType, "", fmt.Sprintf("(optional) filter by a reward type: %s", strings.Join(rewardTypes, "|"))) - cmd.Flags().Bool(flagUnsynced, false, "(optional) get unsynced claims") - cmd.Flags().Int(flags.FlagPage, 1, "pagination page rewards of to query for") - cmd.Flags().Int(flags.FlagLimit, 100, "pagination limit of rewards to query for") - return cmd -} - -func queryParamsCmd() *cobra.Command { - return &cobra.Command{ - Use: "params", - Short: "get the incentive module parameters", - Long: "Get the current global incentive module parameters.", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(cliCtx) - res, err := queryClient.Params(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - return cliCtx.PrintProto(res) - }, - } -} - -func queryRewardFactorsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "reward-factors", - Short: "get current global reward factors", - Long: `Get current global reward factors for all reward types.`, - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(cliCtx) - res, err := queryClient.RewardFactors(context.Background(), &types.QueryRewardFactorsRequest{}) - if err != nil { - return err - } - return cliCtx.PrintProto(res) - }, - } - cmd.Flags().String(flagDenom, "", "(optional) filter reward factors by denom") - return cmd -} - -func queryApyCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "apy", - Short: "queries incentive reward apy for a reward", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(cliCtx) - res, err := queryClient.Apy(context.Background(), &types.QueryApyRequest{}) - if err != nil { - return err - } - return cliCtx.PrintProto(res) - }, - } - return cmd -} diff --git a/x/incentive/client/cli/tx.go b/x/incentive/client/cli/tx.go deleted file mode 100644 index 5707bd5b..00000000 --- a/x/incentive/client/cli/tx.go +++ /dev/null @@ -1,244 +0,0 @@ -package cli - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -const ( - multiplierFlag = "multiplier" - multiplierFlagShort = "m" -) - -// GetTxCmd returns the transaction cli commands for the incentive module -func GetTxCmd() *cobra.Command { - incentiveTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "transaction commands for the incentive module", - } - - cmds := []*cobra.Command{ - getCmdClaimCdp(), - getCmdClaimHard(), - getCmdClaimDelegator(), - getCmdClaimSwap(), - getCmdClaimSavings(), - getCmdClaimEarn(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - incentiveTxCmd.AddCommand(cmds...) - - return incentiveTxCmd -} - -func getCmdClaimCdp() *cobra.Command { - cmd := &cobra.Command{ - Use: "claim-cdp [multiplier]", - Short: "claim USDX minting rewards using a given multiplier", - Long: `Claim sender's outstanding USDX minting rewards using a given multiplier.`, - Example: fmt.Sprintf(` $ %s tx %s claim-cdp large`, version.AppName, types.ModuleName), - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - sender := cliCtx.GetFromAddress() - multiplier := args[0] - - msg := types.NewMsgClaimUSDXMintingReward(sender.String(), multiplier) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), &msg) - }, - } - - return cmd -} - -func getCmdClaimHard() *cobra.Command { - var denomsToClaim map[string]string - - cmd := &cobra.Command{ - Use: "claim-hard", - Short: "claim sender's Hard module rewards using given multipliers", - Long: `Claim sender's outstanding Hard rewards for deposit/borrow using given multipliers`, - Example: strings.Join([]string{ - fmt.Sprintf(` $ %s tx %s claim-hard --%s hard=large --%s ukava=small`, version.AppName, types.ModuleName, multiplierFlag, multiplierFlag), - fmt.Sprintf(` $ %s tx %s claim-hard --%s hard=large,ukava=small`, version.AppName, types.ModuleName, multiplierFlag), - }, "\n"), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - sender := cliCtx.GetFromAddress() - selections := types.NewSelectionsFromMap(denomsToClaim) - - msg := types.NewMsgClaimHardReward(sender.String(), selections) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), &msg) - }, - } - cmd.Flags().StringToStringVarP(&denomsToClaim, multiplierFlag, multiplierFlagShort, nil, "specify the denoms to claim, each with a multiplier lockup") - if err := cmd.MarkFlagRequired(multiplierFlag); err != nil { - panic(err) - } - return cmd -} - -func getCmdClaimDelegator() *cobra.Command { - var denomsToClaim map[string]string - - cmd := &cobra.Command{ - Use: "claim-delegator", - Short: "claim sender's non-sdk delegator rewards using given multipliers", - Long: `Claim sender's outstanding delegator rewards using given multipliers`, - Example: strings.Join([]string{ - fmt.Sprintf(` $ %s tx %s claim-delegator --%s hard=large --%s swp=small`, version.AppName, types.ModuleName, multiplierFlag, multiplierFlag), - fmt.Sprintf(` $ %s tx %s claim-delegator --%s hard=large,swp=small`, version.AppName, types.ModuleName, multiplierFlag), - }, "\n"), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - sender := cliCtx.GetFromAddress() - selections := types.NewSelectionsFromMap(denomsToClaim) - - msg := types.NewMsgClaimDelegatorReward(sender.String(), selections) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), &msg) - }, - } - cmd.Flags().StringToStringVarP(&denomsToClaim, multiplierFlag, multiplierFlagShort, nil, "specify the denoms to claim, each with a multiplier lockup") - if err := cmd.MarkFlagRequired(multiplierFlag); err != nil { - panic(err) - } - return cmd -} - -func getCmdClaimSwap() *cobra.Command { - var denomsToClaim map[string]string - - cmd := &cobra.Command{ - Use: "claim-swap", - Short: "claim sender's swap rewards using given multipliers", - Long: `Claim sender's outstanding swap rewards using given multipliers`, - Example: strings.Join([]string{ - fmt.Sprintf(` $ %s tx %s claim-swap --%s swp=large --%s ukava=small`, version.AppName, types.ModuleName, multiplierFlag, multiplierFlag), - fmt.Sprintf(` $ %s tx %s claim-swap --%s swp=large,ukava=small`, version.AppName, types.ModuleName, multiplierFlag), - }, "\n"), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - sender := cliCtx.GetFromAddress() - selections := types.NewSelectionsFromMap(denomsToClaim) - - msg := types.NewMsgClaimSwapReward(sender.String(), selections) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), &msg) - }, - } - cmd.Flags().StringToStringVarP(&denomsToClaim, multiplierFlag, multiplierFlagShort, nil, "specify the denoms to claim, each with a multiplier lockup") - if err := cmd.MarkFlagRequired(multiplierFlag); err != nil { - panic(err) - } - return cmd -} - -func getCmdClaimSavings() *cobra.Command { - var denomsToClaim map[string]string - - cmd := &cobra.Command{ - Use: "claim-savings", - Short: "claim sender's savings rewards using given multipliers", - Long: `Claim sender's outstanding savings rewards using given multipliers`, - Example: strings.Join([]string{ - fmt.Sprintf(` $ %s tx %s claim-savings --%s swp=large --%s ukava=small`, version.AppName, types.ModuleName, multiplierFlag, multiplierFlag), - fmt.Sprintf(` $ %s tx %s claim-savings --%s swp=large,ukava=small`, version.AppName, types.ModuleName, multiplierFlag), - }, "\n"), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - sender := cliCtx.GetFromAddress() - selections := types.NewSelectionsFromMap(denomsToClaim) - - msg := types.NewMsgClaimSavingsReward(sender.String(), selections) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), &msg) - }, - } - cmd.Flags().StringToStringVarP(&denomsToClaim, multiplierFlag, multiplierFlagShort, nil, "specify the denoms to claim, each with a multiplier lockup") - if err := cmd.MarkFlagRequired(multiplierFlag); err != nil { - panic(err) - } - return cmd -} - -func getCmdClaimEarn() *cobra.Command { - var denomsToClaim map[string]string - - cmd := &cobra.Command{ - Use: "claim-earn", - Short: "claim sender's earn rewards using given multipliers", - Long: `Claim sender's outstanding earn rewards using given multipliers`, - Example: fmt.Sprintf(` $ %s tx %s claim-earn --%s ukava=large`, version.AppName, types.ModuleName, multiplierFlag), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - sender := cliCtx.GetFromAddress() - selections := types.NewSelectionsFromMap(denomsToClaim) - - msg := types.NewMsgClaimEarnReward(sender.String(), selections) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), &msg) - }, - } - cmd.Flags().StringToStringVarP(&denomsToClaim, multiplierFlag, multiplierFlagShort, nil, "specify the denoms to claim, each with a multiplier lockup") - if err := cmd.MarkFlagRequired(multiplierFlag); err != nil { - panic(err) - } - return cmd -} diff --git a/x/incentive/genesis.go b/x/incentive/genesis.go deleted file mode 100644 index 78387b29..00000000 --- a/x/incentive/genesis.go +++ /dev/null @@ -1,294 +0,0 @@ -package incentive - -import ( - "fmt" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/incentive/keeper" - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// InitGenesis initializes the store state from a genesis state. -func InitGenesis( - ctx sdk.Context, - k keeper.Keeper, - accountKeeper types.AccountKeeper, - bankKeeper types.BankKeeper, - cdpKeeper types.CdpKeeper, - gs types.GenesisState, -) { - // check if the module account exists - moduleAcc := accountKeeper.GetModuleAccount(ctx, types.IncentiveMacc) - if moduleAcc == nil { - panic(fmt.Sprintf("%s module account has not been set", types.IncentiveMacc)) - } - - if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) - } - - for _, rp := range gs.Params.USDXMintingRewardPeriods { - if _, found := cdpKeeper.GetCollateral(ctx, rp.CollateralType); !found { - panic(fmt.Sprintf("incentive params contain collateral not found in cdp params: %s", rp.CollateralType)) - } - } - // TODO more param validation? - - k.SetParams(ctx, gs.Params) - - // USDX Minting - for _, claim := range gs.USDXMintingClaims { - k.SetUSDXMintingClaim(ctx, claim) - } - for _, gat := range gs.USDXRewardState.AccumulationTimes { - if err := ValidateAccumulationTime(gat.PreviousAccumulationTime); err != nil { - panic(err.Error()) - } - k.SetPreviousUSDXMintingAccrualTime(ctx, gat.CollateralType, gat.PreviousAccumulationTime) - } - for _, mri := range gs.USDXRewardState.MultiRewardIndexes { - factor, found := mri.RewardIndexes.Get(types.USDXMintingRewardDenom) - if !found || len(mri.RewardIndexes) != 1 { - panic(fmt.Sprintf("USDX Minting reward factors must only have denom %s", types.USDXMintingRewardDenom)) - } - k.SetUSDXMintingRewardFactor(ctx, mri.CollateralType, factor) - } - - // Hard Supply / Borrow - for _, claim := range gs.HardLiquidityProviderClaims { - k.SetHardLiquidityProviderClaim(ctx, claim) - } - for _, gat := range gs.HardSupplyRewardState.AccumulationTimes { - if err := ValidateAccumulationTime(gat.PreviousAccumulationTime); err != nil { - panic(err.Error()) - } - k.SetPreviousHardSupplyRewardAccrualTime(ctx, gat.CollateralType, gat.PreviousAccumulationTime) - } - for _, mri := range gs.HardSupplyRewardState.MultiRewardIndexes { - k.SetHardSupplyRewardIndexes(ctx, mri.CollateralType, mri.RewardIndexes) - } - for _, gat := range gs.HardBorrowRewardState.AccumulationTimes { - if err := ValidateAccumulationTime(gat.PreviousAccumulationTime); err != nil { - panic(err.Error()) - } - k.SetPreviousHardBorrowRewardAccrualTime(ctx, gat.CollateralType, gat.PreviousAccumulationTime) - } - for _, mri := range gs.HardBorrowRewardState.MultiRewardIndexes { - k.SetHardBorrowRewardIndexes(ctx, mri.CollateralType, mri.RewardIndexes) - } - - // Delegator - for _, claim := range gs.DelegatorClaims { - k.SetDelegatorClaim(ctx, claim) - } - for _, gat := range gs.DelegatorRewardState.AccumulationTimes { - if err := ValidateAccumulationTime(gat.PreviousAccumulationTime); err != nil { - panic(err.Error()) - } - k.SetPreviousDelegatorRewardAccrualTime(ctx, gat.CollateralType, gat.PreviousAccumulationTime) - } - for _, mri := range gs.DelegatorRewardState.MultiRewardIndexes { - k.SetDelegatorRewardIndexes(ctx, mri.CollateralType, mri.RewardIndexes) - } - - // Swap - for _, claim := range gs.SwapClaims { - k.SetSwapClaim(ctx, claim) - } - for _, gat := range gs.SwapRewardState.AccumulationTimes { - if err := ValidateAccumulationTime(gat.PreviousAccumulationTime); err != nil { - panic(err.Error()) - } - k.SetSwapRewardAccrualTime(ctx, gat.CollateralType, gat.PreviousAccumulationTime) - } - for _, mri := range gs.SwapRewardState.MultiRewardIndexes { - k.SetSwapRewardIndexes(ctx, mri.CollateralType, mri.RewardIndexes) - } - - // Savings - for _, claim := range gs.SavingsClaims { - k.SetSavingsClaim(ctx, claim) - } - for _, gat := range gs.SavingsRewardState.AccumulationTimes { - if err := ValidateAccumulationTime(gat.PreviousAccumulationTime); err != nil { - panic(err.Error()) - } - k.SetSavingsRewardAccrualTime(ctx, gat.CollateralType, gat.PreviousAccumulationTime) - } - for _, mri := range gs.SavingsRewardState.MultiRewardIndexes { - k.SetSavingsRewardIndexes(ctx, mri.CollateralType, mri.RewardIndexes) - } - - // Earn - for _, claim := range gs.EarnClaims { - k.SetEarnClaim(ctx, claim) - } - for _, gat := range gs.EarnRewardState.AccumulationTimes { - if err := ValidateAccumulationTime(gat.PreviousAccumulationTime); err != nil { - panic(err.Error()) - } - k.SetEarnRewardAccrualTime(ctx, gat.CollateralType, gat.PreviousAccumulationTime) - } - for _, mri := range gs.EarnRewardState.MultiRewardIndexes { - k.SetEarnRewardIndexes(ctx, mri.CollateralType, mri.RewardIndexes) - } -} - -// ExportGenesis export genesis state for incentive module -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { - params := k.GetParams(ctx) - - usdxClaims := k.GetAllUSDXMintingClaims(ctx) - usdxRewardState := getUSDXMintingGenesisRewardState(ctx, k) - - hardClaims := k.GetAllHardLiquidityProviderClaims(ctx) - hardSupplyRewardState := getHardSupplyGenesisRewardState(ctx, k) - hardBorrowRewardState := getHardBorrowGenesisRewardState(ctx, k) - - delegatorClaims := k.GetAllDelegatorClaims(ctx) - delegatorRewardState := getDelegatorGenesisRewardState(ctx, k) - - swapClaims := k.GetAllSwapClaims(ctx) - swapRewardState := getSwapGenesisRewardState(ctx, k) - - savingsClaims := k.GetAllSavingsClaims(ctx) - savingsRewardState := getSavingsGenesisRewardState(ctx, k) - - earnClaims := k.GetAllEarnClaims(ctx) - earnRewardState := getEarnGenesisRewardState(ctx, k) - - return types.NewGenesisState( - params, - // Reward states - usdxRewardState, hardSupplyRewardState, hardBorrowRewardState, delegatorRewardState, swapRewardState, savingsRewardState, earnRewardState, - // Claims - usdxClaims, hardClaims, delegatorClaims, swapClaims, savingsClaims, earnClaims, - ) -} - -func getUSDXMintingGenesisRewardState(ctx sdk.Context, keeper keeper.Keeper) types.GenesisRewardState { - var ats types.AccumulationTimes - keeper.IterateUSDXMintingAccrualTimes(ctx, func(ctype string, accTime time.Time) bool { - ats = append(ats, types.NewAccumulationTime(ctype, accTime)) - return false - }) - - var mris types.MultiRewardIndexes - keeper.IterateUSDXMintingRewardFactors(ctx, func(ctype string, factor sdk.Dec) bool { - mris = append( - mris, - types.NewMultiRewardIndex( - ctype, - types.RewardIndexes{types.NewRewardIndex(types.USDXMintingRewardDenom, factor)}, - ), - ) - return false - }) - - return types.NewGenesisRewardState(ats, mris) -} - -func getHardSupplyGenesisRewardState(ctx sdk.Context, keeper keeper.Keeper) types.GenesisRewardState { - var ats types.AccumulationTimes - keeper.IterateHardSupplyRewardAccrualTimes(ctx, func(ctype string, accTime time.Time) bool { - ats = append(ats, types.NewAccumulationTime(ctype, accTime)) - return false - }) - - var mris types.MultiRewardIndexes - keeper.IterateHardSupplyRewardIndexes(ctx, func(ctype string, indexes types.RewardIndexes) bool { - mris = append(mris, types.NewMultiRewardIndex(ctype, indexes)) - return false - }) - - return types.NewGenesisRewardState(ats, mris) -} - -func getHardBorrowGenesisRewardState(ctx sdk.Context, keeper keeper.Keeper) types.GenesisRewardState { - var ats types.AccumulationTimes - keeper.IterateHardBorrowRewardAccrualTimes(ctx, func(ctype string, accTime time.Time) bool { - ats = append(ats, types.NewAccumulationTime(ctype, accTime)) - return false - }) - - var mris types.MultiRewardIndexes - keeper.IterateHardBorrowRewardIndexes(ctx, func(ctype string, indexes types.RewardIndexes) bool { - mris = append(mris, types.NewMultiRewardIndex(ctype, indexes)) - return false - }) - - return types.NewGenesisRewardState(ats, mris) -} - -func getDelegatorGenesisRewardState(ctx sdk.Context, keeper keeper.Keeper) types.GenesisRewardState { - var ats types.AccumulationTimes - keeper.IterateDelegatorRewardAccrualTimes(ctx, func(ctype string, accTime time.Time) bool { - ats = append(ats, types.NewAccumulationTime(ctype, accTime)) - return false - }) - - var mris types.MultiRewardIndexes - keeper.IterateDelegatorRewardIndexes(ctx, func(ctype string, indexes types.RewardIndexes) bool { - mris = append(mris, types.NewMultiRewardIndex(ctype, indexes)) - return false - }) - - return types.NewGenesisRewardState(ats, mris) -} - -func getSwapGenesisRewardState(ctx sdk.Context, keeper keeper.Keeper) types.GenesisRewardState { - var ats types.AccumulationTimes - keeper.IterateSwapRewardAccrualTimes(ctx, func(ctype string, accTime time.Time) bool { - ats = append(ats, types.NewAccumulationTime(ctype, accTime)) - return false - }) - - var mris types.MultiRewardIndexes - keeper.IterateSwapRewardIndexes(ctx, func(ctype string, indexes types.RewardIndexes) bool { - mris = append(mris, types.NewMultiRewardIndex(ctype, indexes)) - return false - }) - - return types.NewGenesisRewardState(ats, mris) -} - -func getSavingsGenesisRewardState(ctx sdk.Context, keeper keeper.Keeper) types.GenesisRewardState { - var ats types.AccumulationTimes - keeper.IterateSavingsRewardAccrualTimes(ctx, func(ctype string, accTime time.Time) bool { - ats = append(ats, types.NewAccumulationTime(ctype, accTime)) - return false - }) - - var mris types.MultiRewardIndexes - keeper.IterateSavingsRewardIndexes(ctx, func(ctype string, indexes types.RewardIndexes) bool { - mris = append(mris, types.NewMultiRewardIndex(ctype, indexes)) - return false - }) - - return types.NewGenesisRewardState(ats, mris) -} - -func getEarnGenesisRewardState(ctx sdk.Context, keeper keeper.Keeper) types.GenesisRewardState { - var ats types.AccumulationTimes - keeper.IterateEarnRewardAccrualTimes(ctx, func(ctype string, accTime time.Time) bool { - ats = append(ats, types.NewAccumulationTime(ctype, accTime)) - return false - }) - - var mris types.MultiRewardIndexes - keeper.IterateEarnRewardIndexes(ctx, func(ctype string, indexes types.RewardIndexes) bool { - mris = append(mris, types.NewMultiRewardIndex(ctype, indexes)) - return false - }) - - return types.NewGenesisRewardState(ats, mris) -} - -func ValidateAccumulationTime(previousAccumulationTime time.Time) error { - if previousAccumulationTime.Equal(time.Time{}) { - return fmt.Errorf("accumulation time is not set") - } - return nil -} diff --git a/x/incentive/genesis_test.go b/x/incentive/genesis_test.go deleted file mode 100644 index bf4aa411..00000000 --- a/x/incentive/genesis_test.go +++ /dev/null @@ -1,401 +0,0 @@ -package incentive_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - - "github.com/0glabs/0g-chain/app" - hardtypes "github.com/0glabs/0g-chain/x/hard/types" - "github.com/0glabs/0g-chain/x/incentive" - "github.com/0glabs/0g-chain/x/incentive/keeper" - "github.com/0glabs/0g-chain/x/incentive/types" - kavadisttypes "github.com/0glabs/0g-chain/x/kavadist/types" -) - -const ( - oneYear time.Duration = 365 * 24 * time.Hour -) - -type GenesisTestSuite struct { - suite.Suite - - ctx sdk.Context - app app.TestApp - keeper keeper.Keeper - addrs []sdk.AccAddress - - genesisTime time.Time -} - -func (suite *GenesisTestSuite) SetupTest() { - tApp := app.NewTestApp() - suite.app = tApp - keeper := tApp.GetIncentiveKeeper() - suite.genesisTime = time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - - _, addrs := app.GeneratePrivKeyAddressPairs(5) - - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(addrs[0], cs(c("bnb", 1e10), c("ukava", 1e10))). - WithSimpleModuleAccount(kavadisttypes.KavaDistMacc, cs(c("hard", 1e15), c("ukava", 1e15))) - - loanToValue, _ := sdk.NewDecFromStr("0.6") - borrowLimit := sdk.NewDec(1000000000000000) - hardGS := hardtypes.NewGenesisState( - hardtypes.NewParams( - hardtypes.MoneyMarkets{ - hardtypes.NewMoneyMarket("ukava", hardtypes.NewBorrowLimit(false, borrowLimit, loanToValue), "kava:usd", sdkmath.NewInt(1000000), hardtypes.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - hardtypes.NewMoneyMarket("bnb", hardtypes.NewBorrowLimit(false, borrowLimit, loanToValue), "bnb:usd", sdkmath.NewInt(1000000), hardtypes.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - }, - sdk.NewDec(10), - ), - hardtypes.DefaultAccumulationTimes, - hardtypes.DefaultDeposits, - hardtypes.DefaultBorrows, - hardtypes.DefaultTotalSupplied, - hardtypes.DefaultTotalBorrowed, - hardtypes.DefaultTotalReserves, - ) - incentiveGS := types.NewGenesisState( - types.NewParams( - types.RewardPeriods{types.NewRewardPeriod(true, "bnb-a", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), c("ukava", 122354))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "bnb", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "bnb", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "ukava", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "btcb/usdx", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("swp", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "ukava", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "ukava", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultipliersPerDenoms{ - { - Denom: "ukava", - Multipliers: types.Multipliers{ - types.NewMultiplier("large", 12, d("1.0")), - }, - }, - { - Denom: "hard", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.25")), - types.NewMultiplier("large", 12, d("1.0")), - }, - }, - { - Denom: "swp", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.25")), - types.NewMultiplier("medium", 6, d("0.8")), - }, - }, - }, - suite.genesisTime.Add(5*oneYear), - ), - types.DefaultGenesisRewardState, - types.DefaultGenesisRewardState, - types.DefaultGenesisRewardState, - types.DefaultGenesisRewardState, - types.DefaultGenesisRewardState, - types.DefaultGenesisRewardState, - types.DefaultGenesisRewardState, - types.DefaultUSDXClaims, - types.DefaultHardClaims, - types.DefaultDelegatorClaims, - types.DefaultSwapClaims, - types.DefaultSavingsClaims, - types.DefaultEarnClaims, - ) - - cdc := suite.app.AppCodec() - - tApp.InitializeFromGenesisStatesWithTime( - suite.genesisTime, - authBuilder.BuildMarshalled(cdc), - app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&incentiveGS)}, - app.GenesisState{hardtypes.ModuleName: cdc.MustMarshalJSON(&hardGS)}, - NewCDPGenStateMulti(cdc), - NewPricefeedGenStateMultiFromTime(cdc, suite.genesisTime), - ) - - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: suite.genesisTime}) - - suite.addrs = addrs - suite.keeper = keeper - suite.ctx = ctx -} - -func (suite *GenesisTestSuite) TestExportedGenesisMatchesImported() { - genesisTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - genesisState := types.NewGenesisState( - types.NewParams( - types.RewardPeriods{types.NewRewardPeriod(true, "bnb-a", genesisTime.Add(-1*oneYear), genesisTime.Add(oneYear), c("ukava", 122354))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "bnb", genesisTime.Add(-1*oneYear), genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "bnb", genesisTime.Add(-1*oneYear), genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "ukava", genesisTime.Add(-1*oneYear), genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "btcb/usdx", genesisTime.Add(-1*oneYear), genesisTime.Add(oneYear), cs(c("swp", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "ukava", genesisTime.Add(-1*oneYear), genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "ukava", genesisTime.Add(-1*oneYear), genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultipliersPerDenoms{ - { - Denom: "ukava", - Multipliers: types.Multipliers{ - types.NewMultiplier("large", 12, d("1.0")), - }, - }, - { - Denom: "hard", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.25")), - types.NewMultiplier("large", 12, d("1.0")), - }, - }, - { - Denom: "swp", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.25")), - types.NewMultiplier("medium", 6, d("0.8")), - }, - }, - }, - genesisTime.Add(5*oneYear), - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("bnb-a", genesisTime), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("bnb-a", types.RewardIndexes{{CollateralType: "ukava", RewardFactor: d("0.3")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("bnb", genesisTime.Add(-1*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("bnb", types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.1")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("bnb", genesisTime.Add(-2*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("bnb", types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.05")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("ukava", genesisTime.Add(-3*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("ukava", types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.2")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("bctb/usdx", genesisTime.Add(-4*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("btcb/usdx", types.RewardIndexes{{CollateralType: "swap", RewardFactor: d("0.001")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("ukava", genesisTime.Add(-3*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("ukava", types.RewardIndexes{{CollateralType: "ukava", RewardFactor: d("0.2")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("usdx", genesisTime.Add(-3*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("usdx", types.RewardIndexes{{CollateralType: "usdx", RewardFactor: d("0.2")}}), - }, - ), - types.USDXMintingClaims{ - types.NewUSDXMintingClaim( - suite.addrs[0], - c("ukava", 1e9), - types.RewardIndexes{{CollateralType: "bnb-a", RewardFactor: d("0.3")}}, - ), - types.NewUSDXMintingClaim( - suite.addrs[1], - c("ukava", 1), - types.RewardIndexes{{CollateralType: "bnb-a", RewardFactor: d("0.001")}}, - ), - }, - types.HardLiquidityProviderClaims{ - types.NewHardLiquidityProviderClaim( - suite.addrs[0], - cs(c("ukava", 1e9), c("hard", 1e9)), - types.MultiRewardIndexes{{CollateralType: "bnb", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.01")}}}}, - types.MultiRewardIndexes{{CollateralType: "bnb", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.0")}}}}, - ), - types.NewHardLiquidityProviderClaim( - suite.addrs[1], - cs(c("hard", 1)), - types.MultiRewardIndexes{{CollateralType: "bnb", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.1")}}}}, - types.MultiRewardIndexes{{CollateralType: "bnb", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.0")}}}}, - ), - }, - types.DelegatorClaims{ - types.NewDelegatorClaim( - suite.addrs[2], - cs(c("hard", 5)), - types.MultiRewardIndexes{{CollateralType: "ukava", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.2")}}}}, - ), - }, - types.SwapClaims{ - types.NewSwapClaim( - suite.addrs[3], - nil, - types.MultiRewardIndexes{{CollateralType: "btcb/usdx", RewardIndexes: types.RewardIndexes{{CollateralType: "swap", RewardFactor: d("0.0")}}}}, - ), - }, - types.SavingsClaims{ - types.NewSavingsClaim( - suite.addrs[3], - nil, - types.MultiRewardIndexes{{CollateralType: "ukava", RewardIndexes: types.RewardIndexes{{CollateralType: "ukava", RewardFactor: d("0.0")}}}}, - ), - }, - types.EarnClaims{ - types.NewEarnClaim( - suite.addrs[3], - nil, - types.MultiRewardIndexes{{CollateralType: "usdx", RewardIndexes: types.RewardIndexes{{CollateralType: "earn", RewardFactor: d("0.0")}}}}, - ), - }, - ) - - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 0, Time: genesisTime}) - - // Incentive init genesis reads from the cdp keeper to check params are ok. So it needs to be initialized first. - // Then the cdp keeper reads from pricefeed keeper to check its params are ok. So it also need initialization. - tApp = tApp.InitializeFromGenesisStates( - NewCDPGenStateMulti(tApp.AppCodec()), - NewPricefeedGenStateMultiFromTime(tApp.AppCodec(), genesisTime), - ) - - // Clear genesis validator and genesis delegator incentive state to start empty. - ik := tApp.GetIncentiveKeeper() - suite.app.DeleteGenesisValidator(suite.T(), suite.ctx) - ik.DeleteDelegatorClaim(ctx, tApp.GenesisAddrs[0]) - - incentive.InitGenesis( - ctx, - tApp.GetIncentiveKeeper(), - tApp.GetAccountKeeper(), - tApp.GetBankKeeper(), - tApp.GetCDPKeeper(), - genesisState, - ) - - exportedGenesisState := incentive.ExportGenesis(ctx, tApp.GetIncentiveKeeper()) - - suite.Equal(genesisState, exportedGenesisState) -} - -func (suite *GenesisTestSuite) TestInitGenesisPanicsWhenAccumulationTimesTooLongAgo() { - genesisTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - invalidRewardState := types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime( - "bnb", - time.Time{}, - ), - }, - types.MultiRewardIndexes{}, - ) - minimalParams := types.Params{ - ClaimEnd: genesisTime.Add(5 * oneYear), - } - - testCases := []struct { - genesisState types.GenesisState - }{ - { - types.GenesisState{ - Params: minimalParams, - USDXRewardState: invalidRewardState, - }, - }, - { - types.GenesisState{ - Params: minimalParams, - HardSupplyRewardState: invalidRewardState, - }, - }, - { - types.GenesisState{ - Params: minimalParams, - HardBorrowRewardState: invalidRewardState, - }, - }, - { - types.GenesisState{ - Params: minimalParams, - DelegatorRewardState: invalidRewardState, - }, - }, - { - types.GenesisState{ - Params: minimalParams, - SwapRewardState: invalidRewardState, - }, - }, - { - types.GenesisState{ - Params: minimalParams, - SavingsRewardState: invalidRewardState, - }, - }, - } - - for _, tc := range testCases { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 0, Time: genesisTime}) - - // Incentive init genesis reads from the cdp keeper to check params are ok. So it needs to be initialized first. - // Then the cdp keeper reads from pricefeed keeper to check its params are ok. So it also need initialization. - tApp.InitializeFromGenesisStates( - NewCDPGenStateMulti(tApp.AppCodec()), - NewPricefeedGenStateMultiFromTime(tApp.AppCodec(), genesisTime), - ) - - suite.PanicsWithValue( - "accumulation time is not set", - func() { - incentive.InitGenesis( - ctx, tApp.GetIncentiveKeeper(), - tApp.GetAccountKeeper(), - tApp.GetBankKeeper(), - tApp.GetCDPKeeper(), - tc.genesisState, - ) - }, - ) - } -} - -func (suite *GenesisTestSuite) TestValidateAccumulationTime() { - // valid when set - accTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.NoError(incentive.ValidateAccumulationTime(accTime)) - - // invalid when nil value - suite.Error(incentive.ValidateAccumulationTime(time.Time{})) -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(GenesisTestSuite)) -} diff --git a/x/incentive/integration_test.go b/x/incentive/integration_test.go deleted file mode 100644 index e1708528..00000000 --- a/x/incentive/integration_test.go +++ /dev/null @@ -1,185 +0,0 @@ -package incentive_test - -import ( - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - "github.com/0glabs/0g-chain/app" - cdptypes "github.com/0glabs/0g-chain/x/cdp/types" - "github.com/0glabs/0g-chain/x/incentive/testutil" - pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" -) - -// Avoid cluttering test cases with long function names -func i(in int64) sdkmath.Int { return sdkmath.NewInt(in) } -func d(str string) sdk.Dec { return sdk.MustNewDecFromStr(str) } -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } - -func NewCDPGenStateMulti(cdc codec.JSONCodec) app.GenesisState { - cdpGenesis := cdptypes.GenesisState{ - Params: cdptypes.Params{ - GlobalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - SurplusAuctionThreshold: cdptypes.DefaultSurplusThreshold, - SurplusAuctionLot: cdptypes.DefaultSurplusLot, - DebtAuctionThreshold: cdptypes.DefaultDebtThreshold, - DebtAuctionLot: cdptypes.DefaultDebtLot, - LiquidationBlockInterval: cdptypes.DefaultBeginBlockerExecutionBlockInterval, - CollateralParams: cdptypes.CollateralParams{ - { - Denom: "xrp", - Type: "xrp-a", - LiquidationRatio: sdk.MustNewDecFromStr("2.0"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(7000000000), - SpotMarketID: "xrp:usd", - LiquidationMarketID: "xrp:usd", - ConversionFactor: i(6), - }, - { - Denom: "btc", - Type: "btc-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000000782997609"), // %2.5 apr - LiquidationPenalty: d("0.025"), - AuctionSize: i(10000000), - SpotMarketID: "btc:usd", - LiquidationMarketID: "btc:usd", - ConversionFactor: i(8), - }, - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - ConversionFactor: i(8), - }, - { - Denom: "busd", - Type: "busd-a", - LiquidationRatio: d("1.01"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.OneDec(), // %0 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(10000000000), - SpotMarketID: "busd:usd", - LiquidationMarketID: "busd:usd", - ConversionFactor: i(8), - }, - }, - DebtParam: cdptypes.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: i(6), - DebtFloor: i(10000000), - }, - }, - StartingCdpID: cdptypes.DefaultCdpStartingID, - DebtDenom: cdptypes.DefaultDebtDenom, - GovDenom: cdptypes.DefaultGovDenom, - CDPs: cdptypes.CDPs{}, - PreviousAccumulationTimes: cdptypes.GenesisAccumulationTimes{ - cdptypes.NewGenesisAccumulationTime("btc-a", time.Time{}, sdk.OneDec()), - cdptypes.NewGenesisAccumulationTime("xrp-a", time.Time{}, sdk.OneDec()), - cdptypes.NewGenesisAccumulationTime("busd-a", time.Time{}, sdk.OneDec()), - cdptypes.NewGenesisAccumulationTime("bnb-a", time.Time{}, sdk.OneDec()), - }, - TotalPrincipals: cdptypes.GenesisTotalPrincipals{ - cdptypes.NewGenesisTotalPrincipal("btc-a", sdk.ZeroInt()), - cdptypes.NewGenesisTotalPrincipal("xrp-a", sdk.ZeroInt()), - cdptypes.NewGenesisTotalPrincipal("busd-a", sdk.ZeroInt()), - cdptypes.NewGenesisTotalPrincipal("bnb-a", sdk.ZeroInt()), - }, - } - return app.GenesisState{cdptypes.ModuleName: cdc.MustMarshalJSON(&cdpGenesis)} -} - -func NewPricefeedGenStateMultiFromTime(cdc codec.JSONCodec, t time.Time) app.GenesisState { - pfGenesis := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "btc:usd", BaseAsset: "btc", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "xrp:usd", BaseAsset: "xrp", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "busd:usd", BaseAsset: "busd", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "zzz:usd", BaseAsset: "zzz", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: t.Add(1 * time.Hour), - }, - { - MarketID: "btc:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("8000.00"), - Expiry: t.Add(1 * time.Hour), - }, - { - MarketID: "xrp:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("0.25"), - Expiry: t.Add(1 * time.Hour), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("17.25"), - Expiry: t.Add(1 * time.Hour), - }, - { - MarketID: "busd:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.OneDec(), - Expiry: t.Add(1 * time.Hour), - }, - { - MarketID: "zzz:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: t.Add(1 * time.Hour), - }, - }, - } - return app.GenesisState{pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pfGenesis)} -} - -func NewHardGenStateMulti(genTime time.Time) testutil.HardGenesisBuilder { - kavaMM := testutil.NewStandardMoneyMarket("ukava") - kavaMM.SpotMarketID = "kava:usd" - btcMM := testutil.NewStandardMoneyMarket("btcb") - btcMM.SpotMarketID = "btc:usd" - - builder := testutil.NewHardGenesisBuilder().WithGenesisTime(genTime). - WithInitializedMoneyMarket(testutil.NewStandardMoneyMarket("usdx")). - WithInitializedMoneyMarket(kavaMM). - WithInitializedMoneyMarket(testutil.NewStandardMoneyMarket("bnb")). - WithInitializedMoneyMarket(btcMM). - WithInitializedMoneyMarket(testutil.NewStandardMoneyMarket("xrp")). - WithInitializedMoneyMarket(testutil.NewStandardMoneyMarket("zzz")) - return builder -} - -func NewStakingGenesisState(cdc codec.JSONCodec) app.GenesisState { - genState := stakingtypes.DefaultGenesisState() - genState.Params.BondDenom = "ukava" - return app.GenesisState{ - stakingtypes.ModuleName: cdc.MustMarshalJSON(genState), - } -} diff --git a/x/incentive/keeper/claim.go b/x/incentive/keeper/claim.go deleted file mode 100644 index e84941c7..00000000 --- a/x/incentive/keeper/claim.go +++ /dev/null @@ -1,306 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// ClaimUSDXMintingReward pays out funds from a claim to a receiver account. -// Rewards are removed from a claim and paid out according to the multiplier, which reduces the reward amount in exchange for shorter vesting times. -func (k Keeper) ClaimUSDXMintingReward(ctx sdk.Context, owner, receiver sdk.AccAddress, multiplierName string) error { - claim, found := k.GetUSDXMintingClaim(ctx, owner) - if !found { - return errorsmod.Wrapf(types.ErrClaimNotFound, "address: %s", owner) - } - - multiplier, found := k.GetMultiplierByDenom(ctx, types.USDXMintingRewardDenom, multiplierName) - if !found { - return errorsmod.Wrapf(types.ErrInvalidMultiplier, "denom '%s' has no multiplier '%s'", types.USDXMintingRewardDenom, multiplierName) - } - - claimEnd := k.GetClaimEnd(ctx) - - if ctx.BlockTime().After(claimEnd) { - return errorsmod.Wrapf(types.ErrClaimExpired, "block time %s > claim end time %s", ctx.BlockTime(), claimEnd) - } - - claim, err := k.SynchronizeUSDXMintingClaim(ctx, claim) - if err != nil { - return err - } - - rewardAmount := sdk.NewDecFromInt(claim.Reward.Amount).Mul(multiplier.Factor).RoundInt() - if rewardAmount.IsZero() { - return types.ErrZeroClaim - } - rewardCoin := sdk.NewCoin(claim.Reward.Denom, rewardAmount) - length := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup) - - err = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, sdk.NewCoins(rewardCoin), length) - if err != nil { - return err - } - - k.ZeroUSDXMintingClaim(ctx, claim) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeClaim, - sdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()), - sdk.NewAttribute(types.AttributeKeyClaimAmount, claim.Reward.String()), - sdk.NewAttribute(types.AttributeKeyClaimType, claim.GetType()), - ), - ) - return nil -} - -// ClaimHardReward pays out funds from a claim to a receiver account. -// Rewards are removed from a claim and paid out according to the multiplier, which reduces the reward amount in exchange for shorter vesting times. -func (k Keeper) ClaimHardReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error { - multiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName) - if !found { - return errorsmod.Wrapf(types.ErrInvalidMultiplier, "denom '%s' has no multiplier '%s'", denom, multiplierName) - } - - claimEnd := k.GetClaimEnd(ctx) - - if ctx.BlockTime().After(claimEnd) { - return errorsmod.Wrapf(types.ErrClaimExpired, "block time %s > claim end time %s", ctx.BlockTime(), claimEnd) - } - - k.SynchronizeHardLiquidityProviderClaim(ctx, owner) - - syncedClaim, found := k.GetHardLiquidityProviderClaim(ctx, owner) - if !found { - return errorsmod.Wrapf(types.ErrClaimNotFound, "address: %s", owner) - } - - amt := syncedClaim.Reward.AmountOf(denom) - - claimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt)) - rewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt())) - if rewardCoins.IsZero() { - return types.ErrZeroClaim - } - length := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup) - - err := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length) - if err != nil { - return err - } - - // remove claimed coins (NOT reward coins) - syncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...) - k.SetHardLiquidityProviderClaim(ctx, syncedClaim) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeClaim, - sdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()), - sdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()), - sdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()), - ), - ) - return nil -} - -// ClaimDelegatorReward pays out funds from a claim to a receiver account. -// Rewards are removed from a claim and paid out according to the multiplier, which reduces the reward amount in exchange for shorter vesting times. -func (k Keeper) ClaimDelegatorReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error { - claim, found := k.GetDelegatorClaim(ctx, owner) - if !found { - return errorsmod.Wrapf(types.ErrClaimNotFound, "address: %s", owner) - } - - multiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName) - if !found { - return errorsmod.Wrapf(types.ErrInvalidMultiplier, "denom '%s' has no multiplier '%s'", denom, multiplierName) - } - - claimEnd := k.GetClaimEnd(ctx) - - if ctx.BlockTime().After(claimEnd) { - return errorsmod.Wrapf(types.ErrClaimExpired, "block time %s > claim end time %s", ctx.BlockTime(), claimEnd) - } - - syncedClaim, err := k.SynchronizeDelegatorClaim(ctx, claim) - if err != nil { - return errorsmod.Wrapf(types.ErrClaimNotFound, "address: %s", owner) - } - - amt := syncedClaim.Reward.AmountOf(denom) - - claimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt)) - rewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt())) - if rewardCoins.IsZero() { - return types.ErrZeroClaim - } - - length := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup) - - err = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length) - if err != nil { - return err - } - - // remove claimed coins (NOT reward coins) - syncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...) - k.SetDelegatorClaim(ctx, syncedClaim) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeClaim, - sdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()), - sdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()), - sdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()), - ), - ) - return nil -} - -// ClaimSwapReward pays out funds from a claim to a receiver account. -// Rewards are removed from a claim and paid out according to the multiplier, which reduces the reward amount in exchange for shorter vesting times. -func (k Keeper) ClaimSwapReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error { - multiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName) - if !found { - return errorsmod.Wrapf(types.ErrInvalidMultiplier, "denom '%s' has no multiplier '%s'", denom, multiplierName) - } - - claimEnd := k.GetClaimEnd(ctx) - - if ctx.BlockTime().After(claimEnd) { - return errorsmod.Wrapf(types.ErrClaimExpired, "block time %s > claim end time %s", ctx.BlockTime(), claimEnd) - } - - syncedClaim, found := k.GetSynchronizedSwapClaim(ctx, owner) - if !found { - return errorsmod.Wrapf(types.ErrClaimNotFound, "address: %s", owner) - } - - amt := syncedClaim.Reward.AmountOf(denom) - - claimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt)) - rewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt())) - if rewardCoins.IsZero() { - return types.ErrZeroClaim - } - length := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup) - - err := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length) - if err != nil { - return err - } - - // remove claimed coins (NOT reward coins) - syncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...) - k.SetSwapClaim(ctx, syncedClaim) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeClaim, - sdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()), - sdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()), - sdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()), - ), - ) - return nil -} - -// ClaimSavingsReward is a stub method for MsgServer interface compliance -func (k Keeper) ClaimSavingsReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error { - multiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName) - if !found { - return errorsmod.Wrapf(types.ErrInvalidMultiplier, "denom '%s' has no multiplier '%s'", denom, multiplierName) - } - - claimEnd := k.GetClaimEnd(ctx) - - if ctx.BlockTime().After(claimEnd) { - return errorsmod.Wrapf(types.ErrClaimExpired, "block time %s > claim end time %s", ctx.BlockTime(), claimEnd) - } - - k.SynchronizeSavingsClaim(ctx, owner) - - syncedClaim, found := k.GetSavingsClaim(ctx, owner) - if !found { - return errorsmod.Wrapf(types.ErrClaimNotFound, "address: %s", owner) - } - - amt := syncedClaim.Reward.AmountOf(denom) - - claimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt)) - rewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt())) - if rewardCoins.IsZero() { - return types.ErrZeroClaim - } - length := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup) - - err := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length) - if err != nil { - return err - } - - // remove claimed coins (NOT reward coins) - syncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...) - k.SetSavingsClaim(ctx, syncedClaim) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeClaim, - sdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()), - sdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()), - sdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()), - ), - ) - return nil -} - -// ClaimEarnReward pays out funds from a claim to a receiver account. -// Rewards are removed from a claim and paid out according to the multiplier, which reduces the reward amount in exchange for shorter vesting times. -func (k Keeper) ClaimEarnReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error { - multiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName) - if !found { - return errorsmod.Wrapf(types.ErrInvalidMultiplier, "denom '%s' has no multiplier '%s'", denom, multiplierName) - } - - claimEnd := k.GetClaimEnd(ctx) - - if ctx.BlockTime().After(claimEnd) { - return errorsmod.Wrapf(types.ErrClaimExpired, "block time %s > claim end time %s", ctx.BlockTime(), claimEnd) - } - - syncedClaim, found := k.GetSynchronizedEarnClaim(ctx, owner) - if !found { - return errorsmod.Wrapf(types.ErrClaimNotFound, "address: %s", owner) - } - - amt := syncedClaim.Reward.AmountOf(denom) - - claimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt)) - rewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt())) - if rewardCoins.IsZero() { - return types.ErrZeroClaim - } - length := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup) - - err := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length) - if err != nil { - return err - } - - // remove claimed coins (NOT reward coins) - syncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...) - k.SetEarnClaim(ctx, syncedClaim) - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeClaim, - sdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()), - sdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()), - sdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()), - ), - ) - return nil -} diff --git a/x/incentive/keeper/claim_test.go b/x/incentive/keeper/claim_test.go deleted file mode 100644 index ba60c50c..00000000 --- a/x/incentive/keeper/claim_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package keeper_test - -import ( - "errors" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// ClaimTests runs unit tests for the keeper Claim methods -type ClaimTests struct { - unitTester -} - -func TestClaim(t *testing.T) { - suite.Run(t, new(ClaimTests)) -} - -func (suite *ClaimTests) ErrorIs(err, target error) bool { - return suite.Truef(errors.Is(err, target), "err didn't match: %s, it was: %s", target, err) -} - -func (suite *ClaimTests) TestCannotClaimWhenMultiplierNotRecognised() { - subspace := &fakeParamSubspace{ - params: types.Params{ - ClaimMultipliers: types.MultipliersPerDenoms{ - { - Denom: "hard", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.2")), - }, - }, - }, - }, - } - suite.keeper = suite.NewKeeper(subspace, nil, nil, nil, nil, nil, nil, nil, nil, nil) - - claim := types.DelegatorClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - } - suite.storeDelegatorClaim(claim) - - // multiplier not in params - err := suite.keeper.ClaimDelegatorReward(suite.ctx, claim.Owner, claim.Owner, "hard", "large") - suite.ErrorIs(err, types.ErrInvalidMultiplier) - - // invalid multiplier name - err = suite.keeper.ClaimDelegatorReward(suite.ctx, claim.Owner, claim.Owner, "hard", "") - suite.ErrorIs(err, types.ErrInvalidMultiplier) -} - -func (suite *ClaimTests) TestCannotClaimAfterEndTime() { - endTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - - subspace := &fakeParamSubspace{ - params: types.Params{ - ClaimMultipliers: types.MultipliersPerDenoms{ - { - Denom: "hard", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.2")), - }, - }, - }, - ClaimEnd: endTime, - }, - } - suite.keeper = suite.NewKeeper(subspace, nil, nil, nil, nil, nil, nil, nil, nil, nil) - - suite.ctx = suite.ctx.WithBlockTime(endTime.Add(time.Nanosecond)) - - claim := types.DelegatorClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - } - suite.storeDelegatorClaim(claim) - - err := suite.keeper.ClaimDelegatorReward(suite.ctx, claim.Owner, claim.Owner, "hard", "small") - suite.ErrorIs(err, types.ErrClaimExpired) -} diff --git a/x/incentive/keeper/diff_test.go b/x/incentive/keeper/diff_test.go deleted file mode 100644 index a032a06c..00000000 --- a/x/incentive/keeper/diff_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestSetDiff(t *testing.T) { - tests := []struct { - name string - setA []string - setB []string - expected []string - }{ - {"empty", []string{}, []string{}, []string(nil)}, - {"diff equal sets", []string{"busd", "usdx"}, []string{"busd", "usdx"}, []string(nil)}, - {"diff set empty", []string{"bnb", "ukava", "usdx"}, []string{}, []string{"bnb", "ukava", "usdx"}}, - {"input set empty", []string{}, []string{"bnb", "ukava", "usdx"}, []string(nil)}, - {"diff set with common elements", []string{"bnb", "btcb", "usdx", "xrpb"}, []string{"bnb", "usdx"}, []string{"btcb", "xrpb"}}, - {"diff set with all common elements", []string{"bnb", "usdx"}, []string{"bnb", "btcb", "usdx", "xrpb"}, []string(nil)}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - require.Equal(t, tt.expected, setDifference(tt.setA, tt.setB)) - }) - } -} diff --git a/x/incentive/keeper/grpc_query.go b/x/incentive/keeper/grpc_query.go deleted file mode 100644 index 7cfe71bb..00000000 --- a/x/incentive/keeper/grpc_query.go +++ /dev/null @@ -1,342 +0,0 @@ -package keeper - -import ( - "context" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/0glabs/0g-chain/x/incentive/types" - liquidtypes "github.com/0glabs/0g-chain/x/liquid/types" -) - -const ( - RewardTypeHard = "hard" - RewardTypeUSDXMinting = "usdx_minting" - RewardTypeDelegator = "delegator" - RewardTypeSwap = "swap" - RewardTypeSavings = "savings" - RewardTypeEarn = "earn" -) - -type queryServer struct { - keeper Keeper -} - -var _ types.QueryServer = queryServer{} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(keeper Keeper) types.QueryServer { - return &queryServer{ - keeper: keeper, - } -} - -func (s queryServer) Params( - ctx context.Context, - req *types.QueryParamsRequest, -) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - return &types.QueryParamsResponse{ - Params: s.keeper.GetParams(sdkCtx), - }, nil -} - -func (s queryServer) Rewards( - ctx context.Context, - req *types.QueryRewardsRequest, -) (*types.QueryRewardsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - res := types.QueryRewardsResponse{} - - hasOwner := req.Owner != "" - - var owner sdk.AccAddress - if hasOwner { - addr, err := sdk.AccAddressFromBech32(req.Owner) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid address: %s", err) - } - - owner = addr - } - - if err := s.queryRewards(sdkCtx, &res, owner, hasOwner, req.RewardType); err != nil { - return nil, err - } - - if !req.Unsynchronized { - if err := s.synchronizeRewards(sdkCtx, &res); err != nil { - return nil, err - } - } - - return &res, nil -} - -func (s queryServer) RewardFactors( - ctx context.Context, - req *types.QueryRewardFactorsRequest, -) (*types.QueryRewardFactorsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - var usdxFactors types.RewardIndexes - s.keeper.IterateUSDXMintingRewardFactors(sdkCtx, func(collateralType string, factor sdk.Dec) (stop bool) { - usdxFactors = usdxFactors.With(collateralType, factor) - return false - }) - - var supplyFactors types.MultiRewardIndexes - s.keeper.IterateHardSupplyRewardIndexes(sdkCtx, func(denom string, indexes types.RewardIndexes) (stop bool) { - supplyFactors = supplyFactors.With(denom, indexes) - return false - }) - - var borrowFactors types.MultiRewardIndexes - s.keeper.IterateHardBorrowRewardIndexes(sdkCtx, func(denom string, indexes types.RewardIndexes) (stop bool) { - borrowFactors = borrowFactors.With(denom, indexes) - return false - }) - - var delegatorFactors types.MultiRewardIndexes - s.keeper.IterateDelegatorRewardIndexes(sdkCtx, func(denom string, indexes types.RewardIndexes) (stop bool) { - delegatorFactors = delegatorFactors.With(denom, indexes) - return false - }) - - var swapFactors types.MultiRewardIndexes - s.keeper.IterateSwapRewardIndexes(sdkCtx, func(poolID string, indexes types.RewardIndexes) (stop bool) { - swapFactors = swapFactors.With(poolID, indexes) - return false - }) - - var savingsFactors types.MultiRewardIndexes - s.keeper.IterateSavingsRewardIndexes(sdkCtx, func(denom string, indexes types.RewardIndexes) (stop bool) { - savingsFactors = savingsFactors.With(denom, indexes) - return false - }) - - var earnFactors types.MultiRewardIndexes - s.keeper.IterateEarnRewardIndexes(sdkCtx, func(denom string, indexes types.RewardIndexes) (stop bool) { - earnFactors = earnFactors.With(denom, indexes) - return false - }) - - return &types.QueryRewardFactorsResponse{ - UsdxMintingRewardFactors: usdxFactors, - HardSupplyRewardFactors: supplyFactors, - HardBorrowRewardFactors: borrowFactors, - DelegatorRewardFactors: delegatorFactors, - SwapRewardFactors: swapFactors, - SavingsRewardFactors: savingsFactors, - EarnRewardFactors: earnFactors, - }, nil -} - -func (s queryServer) Apy( - ctx context.Context, - req *types.QueryApyRequest, -) (*types.QueryApyResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - params := s.keeper.GetParams(sdkCtx) - var apys types.APYs - - // bkava APY (staking + incentive rewards) - stakingAPR, err := GetStakingAPR(sdkCtx, s.keeper, params) - if err != nil { - return nil, err - } - - apys = append(apys, types.NewAPY(liquidtypes.DefaultDerivativeDenom, stakingAPR)) - - // Incentive only APYs - for _, param := range params.EarnRewardPeriods { - // Skip bkava as it's calculated earlier with staking rewards - if param.CollateralType == liquidtypes.DefaultDerivativeDenom { - continue - } - - // Value in the vault in the same denom as CollateralType - vaultTotalValue, err := s.keeper.earnKeeper.GetVaultTotalValue(sdkCtx, param.CollateralType) - if err != nil { - return nil, err - } - apy, err := GetAPYFromMultiRewardPeriod(sdkCtx, s.keeper, param.CollateralType, param, vaultTotalValue.Amount) - if err != nil { - return nil, err - } - - apys = append(apys, types.NewAPY(param.CollateralType, apy)) - } - - return &types.QueryApyResponse{ - Earn: apys, - }, nil -} - -// queryRewards queries the rewards for a given owner and reward type, updating -// the response with the results in place. -func (s queryServer) queryRewards( - ctx sdk.Context, - res *types.QueryRewardsResponse, - owner sdk.AccAddress, - hasOwner bool, - rewardType string, -) error { - rewardType = strings.ToLower(rewardType) - isAllRewards := rewardType == "" - - if !rewardTypeIsValid(rewardType) { - return status.Errorf(codes.InvalidArgument, "invalid reward type for owner %s: %s", owner, rewardType) - } - - if isAllRewards || rewardType == RewardTypeUSDXMinting { - if hasOwner { - usdxMintingClaim, foundUsdxMintingClaim := s.keeper.GetUSDXMintingClaim(ctx, owner) - if foundUsdxMintingClaim { - res.USDXMintingClaims = append(res.USDXMintingClaims, usdxMintingClaim) - } - } else { - usdxMintingClaims := s.keeper.GetAllUSDXMintingClaims(ctx) - res.USDXMintingClaims = append(res.USDXMintingClaims, usdxMintingClaims...) - } - } - - if isAllRewards || rewardType == RewardTypeHard { - if hasOwner { - hardClaim, foundHardClaim := s.keeper.GetHardLiquidityProviderClaim(ctx, owner) - if foundHardClaim { - res.HardLiquidityProviderClaims = append(res.HardLiquidityProviderClaims, hardClaim) - } - } else { - hardClaims := s.keeper.GetAllHardLiquidityProviderClaims(ctx) - res.HardLiquidityProviderClaims = append(res.HardLiquidityProviderClaims, hardClaims...) - } - } - - if isAllRewards || rewardType == RewardTypeDelegator { - if hasOwner { - delegatorClaim, foundDelegatorClaim := s.keeper.GetDelegatorClaim(ctx, owner) - if foundDelegatorClaim { - res.DelegatorClaims = append(res.DelegatorClaims, delegatorClaim) - } - } else { - delegatorClaims := s.keeper.GetAllDelegatorClaims(ctx) - res.DelegatorClaims = append(res.DelegatorClaims, delegatorClaims...) - } - } - - if isAllRewards || rewardType == RewardTypeSwap { - if hasOwner { - swapClaim, foundSwapClaim := s.keeper.GetSwapClaim(ctx, owner) - if foundSwapClaim { - res.SwapClaims = append(res.SwapClaims, swapClaim) - } - } else { - swapClaims := s.keeper.GetAllSwapClaims(ctx) - res.SwapClaims = append(res.SwapClaims, swapClaims...) - } - } - - if isAllRewards || rewardType == RewardTypeSavings { - if hasOwner { - savingsClaim, foundSavingsClaim := s.keeper.GetSavingsClaim(ctx, owner) - if foundSavingsClaim { - res.SavingsClaims = append(res.SavingsClaims, savingsClaim) - } - } else { - savingsClaims := s.keeper.GetAllSavingsClaims(ctx) - res.SavingsClaims = append(res.SavingsClaims, savingsClaims...) - } - } - - if isAllRewards || rewardType == RewardTypeEarn { - if hasOwner { - earnClaim, foundEarnClaim := s.keeper.GetEarnClaim(ctx, owner) - if foundEarnClaim { - res.EarnClaims = append(res.EarnClaims, earnClaim) - } - } else { - earnClaims := s.keeper.GetAllEarnClaims(ctx) - res.EarnClaims = append(res.EarnClaims, earnClaims...) - } - } - - return nil -} - -// synchronizeRewards synchronizes all non-empty rewards in place. -func (s queryServer) synchronizeRewards( - ctx sdk.Context, - res *types.QueryRewardsResponse, -) error { - // Synchronize all non-empty rewards - for i, claim := range res.USDXMintingClaims { - res.USDXMintingClaims[i] = s.keeper.SimulateUSDXMintingSynchronization(ctx, claim) - } - - for i, claim := range res.HardLiquidityProviderClaims { - res.HardLiquidityProviderClaims[i] = s.keeper.SimulateHardSynchronization(ctx, claim) - } - - for i, claim := range res.DelegatorClaims { - res.DelegatorClaims[i] = s.keeper.SimulateDelegatorSynchronization(ctx, claim) - } - - for i, claim := range res.SwapClaims { - syncedClaim, found := s.keeper.GetSynchronizedSwapClaim(ctx, claim.Owner) - if !found { - return status.Errorf(codes.Internal, "previously found swap claim for owner %s should still be found", claim.Owner) - } - res.SwapClaims[i] = syncedClaim - } - - for i, claim := range res.SavingsClaims { - syncedClaim, found := s.keeper.GetSynchronizedSavingsClaim(ctx, claim.Owner) - if !found { - return status.Errorf(codes.Internal, "previously found savings claim for owner %s should still be found", claim.Owner) - } - res.SavingsClaims[i] = syncedClaim - } - - for i, claim := range res.EarnClaims { - syncedClaim, found := s.keeper.GetSynchronizedEarnClaim(ctx, claim.Owner) - if !found { - return status.Errorf(codes.Internal, "previously found earn claim for owner %s should still be found", claim.Owner) - } - res.EarnClaims[i] = syncedClaim - } - - return nil -} - -func rewardTypeIsValid(rewardType string) bool { - return rewardType == "" || - rewardType == RewardTypeHard || - rewardType == RewardTypeUSDXMinting || - rewardType == RewardTypeDelegator || - rewardType == RewardTypeSwap || - rewardType == RewardTypeSavings || - rewardType == RewardTypeEarn -} diff --git a/x/incentive/keeper/grpc_query_test.go b/x/incentive/keeper/grpc_query_test.go deleted file mode 100644 index abc0b484..00000000 --- a/x/incentive/keeper/grpc_query_test.go +++ /dev/null @@ -1,328 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/0glabs/0g-chain/app" - hardtypes "github.com/0glabs/0g-chain/x/hard/types" - "github.com/0glabs/0g-chain/x/incentive/keeper" - "github.com/0glabs/0g-chain/x/incentive/types" - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" -) - -const ( - oneYear time.Duration = 365 * 24 * time.Hour -) - -type grpcQueryTestSuite struct { - suite.Suite - - tApp app.TestApp - ctx sdk.Context - keeper keeper.Keeper - queryClient types.QueryClient - addrs []sdk.AccAddress - - genesisTime time.Time - genesisState types.GenesisState -} - -func (suite *grpcQueryTestSuite) SetupTest() { - suite.tApp = app.NewTestApp() - cdc := suite.tApp.AppCodec() - - _, addrs := app.GeneratePrivKeyAddressPairs(5) - suite.genesisTime = time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - - suite.addrs = addrs - - suite.ctx = suite.tApp.NewContext(true, tmprototypes.Header{}). - WithBlockTime(time.Now().UTC()) - suite.keeper = suite.tApp.GetIncentiveKeeper() - - queryHelper := baseapp.NewQueryServerTestHelper(suite.ctx, suite.tApp.InterfaceRegistry()) - types.RegisterQueryServer(queryHelper, keeper.NewQueryServerImpl(suite.keeper)) - - suite.queryClient = types.NewQueryClient(queryHelper) - - loanToValue, _ := sdk.NewDecFromStr("0.6") - borrowLimit := sdk.NewDec(1000000000000000) - hardGS := hardtypes.NewGenesisState( - hardtypes.NewParams( - hardtypes.MoneyMarkets{ - hardtypes.NewMoneyMarket("ukava", hardtypes.NewBorrowLimit(false, borrowLimit, loanToValue), "kava:usd", sdkmath.NewInt(1000000), hardtypes.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - hardtypes.NewMoneyMarket("bnb", hardtypes.NewBorrowLimit(false, borrowLimit, loanToValue), "bnb:usd", sdkmath.NewInt(1000000), hardtypes.NewInterestRateModel(sdk.MustNewDecFromStr("0.05"), sdk.MustNewDecFromStr("2"), sdk.MustNewDecFromStr("0.8"), sdk.MustNewDecFromStr("10")), sdk.MustNewDecFromStr("0.05"), sdk.ZeroDec()), - }, - sdk.NewDec(10), - ), - hardtypes.DefaultAccumulationTimes, - hardtypes.DefaultDeposits, - hardtypes.DefaultBorrows, - hardtypes.DefaultTotalSupplied, - hardtypes.DefaultTotalBorrowed, - hardtypes.DefaultTotalReserves, - ) - - suite.genesisState = types.NewGenesisState( - types.NewParams( - types.RewardPeriods{types.NewRewardPeriod(true, "bnb-a", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), c("ukava", 122354))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "bnb", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "bnb", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "ukava", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "btcb/usdx", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("swp", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "ukava", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultiRewardPeriods{types.NewMultiRewardPeriod(true, "ukava", suite.genesisTime.Add(-1*oneYear), suite.genesisTime.Add(oneYear), cs(c("hard", 122354)))}, - types.MultipliersPerDenoms{ - { - Denom: "ukava", - Multipliers: types.Multipliers{ - types.NewMultiplier("large", 12, d("1.0")), - }, - }, - { - Denom: "hard", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.25")), - types.NewMultiplier("large", 12, d("1.0")), - }, - }, - { - Denom: "swp", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.25")), - types.NewMultiplier("medium", 6, d("0.8")), - }, - }, - }, - suite.genesisTime.Add(5*oneYear), - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("bnb-a", suite.genesisTime), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("bnb-a", types.RewardIndexes{{CollateralType: "ukava", RewardFactor: d("0.3")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("bnb", suite.genesisTime.Add(-1*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("bnb", types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.1")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("bnb", suite.genesisTime.Add(-2*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("bnb", types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.05")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("ukava", suite.genesisTime.Add(-3*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("ukava", types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.2")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("bctb/usdx", suite.genesisTime.Add(-4*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("btcb/usdx", types.RewardIndexes{{CollateralType: "swap", RewardFactor: d("0.001")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("ukava", suite.genesisTime.Add(-3*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("ukava", types.RewardIndexes{{CollateralType: "ukava", RewardFactor: d("0.2")}}), - }, - ), - types.NewGenesisRewardState( - types.AccumulationTimes{ - types.NewAccumulationTime("usdx", suite.genesisTime.Add(-3*time.Hour)), - }, - types.MultiRewardIndexes{ - types.NewMultiRewardIndex("usdx", types.RewardIndexes{{CollateralType: "usdx", RewardFactor: d("0.2")}}), - }, - ), - types.USDXMintingClaims{ - types.NewUSDXMintingClaim( - suite.addrs[0], - c("ukava", 1e9), - types.RewardIndexes{{CollateralType: "bnb-a", RewardFactor: d("0.3")}}, - ), - types.NewUSDXMintingClaim( - suite.addrs[1], - c("ukava", 1), - types.RewardIndexes{{CollateralType: "bnb-a", RewardFactor: d("0.001")}}, - ), - }, - types.HardLiquidityProviderClaims{ - types.NewHardLiquidityProviderClaim( - suite.addrs[0], - cs(c("ukava", 1e9), c("hard", 1e9)), - types.MultiRewardIndexes{{CollateralType: "bnb", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.01")}}}}, - types.MultiRewardIndexes{{CollateralType: "bnb", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.0")}}}}, - ), - types.NewHardLiquidityProviderClaim( - suite.addrs[1], - cs(c("hard", 1)), - types.MultiRewardIndexes{{CollateralType: "bnb", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.1")}}}}, - types.MultiRewardIndexes{{CollateralType: "bnb", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.0")}}}}, - ), - }, - types.DelegatorClaims{ - types.NewDelegatorClaim( - suite.addrs[2], - cs(c("hard", 5)), - types.MultiRewardIndexes{{CollateralType: "ukava", RewardIndexes: types.RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.2")}}}}, - ), - }, - types.SwapClaims{ - types.NewSwapClaim( - suite.addrs[3], - nil, - types.MultiRewardIndexes{{CollateralType: "btcb/usdx", RewardIndexes: types.RewardIndexes{{CollateralType: "swap", RewardFactor: d("0.0")}}}}, - ), - }, - types.SavingsClaims{ - types.NewSavingsClaim( - suite.addrs[3], - nil, - types.MultiRewardIndexes{{CollateralType: "ukava", RewardIndexes: types.RewardIndexes{{CollateralType: "ukava", RewardFactor: d("0.0")}}}}, - ), - }, - types.EarnClaims{ - types.NewEarnClaim( - suite.addrs[3], - nil, - types.MultiRewardIndexes{{CollateralType: "usdx", RewardIndexes: types.RewardIndexes{{CollateralType: "usdx", RewardFactor: d("0.0")}}}}, - ), - }, - ) - - err := suite.genesisState.Validate() - suite.Require().NoError(err) - - suite.tApp = suite.tApp.InitializeFromGenesisStatesWithTime( - suite.genesisTime, - app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&suite.genesisState)}, - app.GenesisState{hardtypes.ModuleName: cdc.MustMarshalJSON(&hardGS)}, - NewCDPGenStateMulti(cdc), - NewPricefeedGenStateMultiFromTime(cdc, suite.genesisTime), - ) - - suite.tApp.DeleteGenesisValidator(suite.T(), suite.ctx) - claims := suite.keeper.GetAllDelegatorClaims(suite.ctx) - for _, claim := range claims { - // Delete the InitGenesis validator's claim - if !claim.Owner.Equals(suite.addrs[2]) { - suite.keeper.DeleteDelegatorClaim(suite.ctx, claim.Owner) - } - } -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryParams() { - res, err := suite.queryClient.Params(sdk.WrapSDKContext(suite.ctx), &types.QueryParamsRequest{}) - suite.Require().NoError(err) - - expected := suite.keeper.GetParams(suite.ctx) - - suite.Equal(expected, res.Params, "params should equal default params") -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryRewards() { - res, err := suite.queryClient.Rewards(sdk.WrapSDKContext(suite.ctx), &types.QueryRewardsRequest{ - Unsynchronized: true, - }) - suite.Require().NoError(err) - - suite.Equal(suite.genesisState.USDXMintingClaims, res.USDXMintingClaims) - suite.Equal(suite.genesisState.HardLiquidityProviderClaims, res.HardLiquidityProviderClaims) - suite.Equal(suite.genesisState.DelegatorClaims, res.DelegatorClaims) - suite.Equal(suite.genesisState.SwapClaims, res.SwapClaims) - suite.Equal(suite.genesisState.SavingsClaims, res.SavingsClaims) - suite.Equal(suite.genesisState.EarnClaims, res.EarnClaims) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryRewards_Owner() { - res, err := suite.queryClient.Rewards(sdk.WrapSDKContext(suite.ctx), &types.QueryRewardsRequest{ - Owner: suite.addrs[0].String(), - }) - suite.Require().NoError(err) - - suite.Len(res.USDXMintingClaims, 1) - suite.Len(res.HardLiquidityProviderClaims, 1) - - suite.Equal(suite.genesisState.USDXMintingClaims[0], res.USDXMintingClaims[0]) - suite.Equal(suite.genesisState.HardLiquidityProviderClaims[0], res.HardLiquidityProviderClaims[0]) - - // No other claims - owner has none - suite.Empty(res.DelegatorClaims) - suite.Empty(res.SwapClaims) - suite.Empty(res.SavingsClaims) - suite.Empty(res.EarnClaims) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryRewards_RewardType() { - res, err := suite.queryClient.Rewards(sdk.WrapSDKContext(suite.ctx), &types.QueryRewardsRequest{ - RewardType: keeper.RewardTypeHard, - Unsynchronized: true, - }) - suite.Require().NoError(err) - - suite.Equal(suite.genesisState.HardLiquidityProviderClaims, res.HardLiquidityProviderClaims) - - // No other reward types when specifying rewardType - suite.Empty(res.USDXMintingClaims) - suite.Empty(res.DelegatorClaims) - suite.Empty(res.SwapClaims) - suite.Empty(res.SavingsClaims) - suite.Empty(res.EarnClaims) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryRewards_RewardType_and_Owner() { - res, err := suite.queryClient.Rewards(sdk.WrapSDKContext(suite.ctx), &types.QueryRewardsRequest{ - Owner: suite.addrs[0].String(), - RewardType: keeper.RewardTypeHard, - }) - suite.Require().NoError(err) - - suite.Len(res.HardLiquidityProviderClaims, 1) - suite.Equal(suite.genesisState.HardLiquidityProviderClaims[0], res.HardLiquidityProviderClaims[0]) - - suite.Empty(res.USDXMintingClaims) - suite.Empty(res.DelegatorClaims) - suite.Empty(res.SwapClaims) - suite.Empty(res.SavingsClaims) - suite.Empty(res.EarnClaims) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryRewardFactors() { - res, err := suite.queryClient.RewardFactors(sdk.WrapSDKContext(suite.ctx), &types.QueryRewardFactorsRequest{}) - suite.Require().NoError(err) - - suite.NotEmpty(res.UsdxMintingRewardFactors) - suite.NotEmpty(res.HardSupplyRewardFactors) - suite.NotEmpty(res.HardBorrowRewardFactors) - suite.NotEmpty(res.DelegatorRewardFactors) - suite.NotEmpty(res.SwapRewardFactors) - suite.NotEmpty(res.SavingsRewardFactors) - suite.NotEmpty(res.EarnRewardFactors) -} - -func TestGrpcQueryTestSuite(t *testing.T) { - suite.Run(t, new(grpcQueryTestSuite)) -} diff --git a/x/incentive/keeper/hooks.go b/x/incentive/keeper/hooks.go deleted file mode 100644 index 483c7dcc..00000000 --- a/x/incentive/keeper/hooks.go +++ /dev/null @@ -1,227 +0,0 @@ -package keeper - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - cdptypes "github.com/0glabs/0g-chain/x/cdp/types" - earntypes "github.com/0glabs/0g-chain/x/earn/types" - hardtypes "github.com/0glabs/0g-chain/x/hard/types" - savingstypes "github.com/0glabs/0g-chain/x/savings/types" - swaptypes "github.com/0glabs/0g-chain/x/swap/types" -) - -// Hooks wrapper struct for hooks -type Hooks struct { - k Keeper -} - -var ( - _ cdptypes.CDPHooks = Hooks{} - _ hardtypes.HARDHooks = Hooks{} - _ stakingtypes.StakingHooks = Hooks{} - _ swaptypes.SwapHooks = Hooks{} - _ savingstypes.SavingsHooks = Hooks{} - _ earntypes.EarnHooks = Hooks{} -) - -// Hooks create new incentive hooks -func (k Keeper) Hooks() Hooks { return Hooks{k} } - -// ------------------- Cdp Module Hooks ------------------- - -// AfterCDPCreated function that runs after a cdp is created -func (h Hooks) AfterCDPCreated(ctx sdk.Context, cdp cdptypes.CDP) { - h.k.InitializeUSDXMintingClaim(ctx, cdp) -} - -// BeforeCDPModified function that runs before a cdp is modified -// note that this is called immediately after interest is synchronized, and so could potentially -// be called AfterCDPInterestUpdated or something like that, if we we're to expand the scope of cdp hooks -func (h Hooks) BeforeCDPModified(ctx sdk.Context, cdp cdptypes.CDP) { - h.k.SynchronizeUSDXMintingReward(ctx, cdp) -} - -// ------------------- Hard Module Hooks ------------------- - -// AfterDepositCreated function that runs after a deposit is created -func (h Hooks) AfterDepositCreated(ctx sdk.Context, deposit hardtypes.Deposit) { - h.k.InitializeHardSupplyReward(ctx, deposit) -} - -// BeforeDepositModified function that runs before a deposit is modified -func (h Hooks) BeforeDepositModified(ctx sdk.Context, deposit hardtypes.Deposit) { - h.k.SynchronizeHardSupplyReward(ctx, deposit) -} - -// AfterDepositModified function that runs after a deposit is modified -func (h Hooks) AfterDepositModified(ctx sdk.Context, deposit hardtypes.Deposit) { - h.k.UpdateHardSupplyIndexDenoms(ctx, deposit) -} - -// AfterBorrowCreated function that runs after a borrow is created -func (h Hooks) AfterBorrowCreated(ctx sdk.Context, borrow hardtypes.Borrow) { - h.k.InitializeHardBorrowReward(ctx, borrow) -} - -// BeforeBorrowModified function that runs before a borrow is modified -func (h Hooks) BeforeBorrowModified(ctx sdk.Context, borrow hardtypes.Borrow) { - h.k.SynchronizeHardBorrowReward(ctx, borrow) -} - -// AfterBorrowModified function that runs after a borrow is modified -func (h Hooks) AfterBorrowModified(ctx sdk.Context, borrow hardtypes.Borrow) { - h.k.UpdateHardBorrowIndexDenoms(ctx, borrow) -} - -/* ------------------- Staking Module Hooks ------------------- - -Rewards are calculated based on total delegated tokens to bonded validators (not shares). -We need to sync the claim before the user's delegated tokens are changed. - -When delegated tokens (to bonded validators) are changed: -- user creates new delegation - - total bonded delegation increases -- user delegates or beginUnbonding or beginRedelegate an existing delegation - - total bonded delegation increases or decreases -- validator is slashed and Jailed/Tombstoned (tokens reduce, and validator is unbonded) - - slash: total bonded delegation decreases (less tokens) - - jail: total bonded delegation decreases (tokens no longer bonded (after end blocker runs)) -- validator becomes unbonded (ie when they drop out of the top 100) - - total bonded delegation decreases (tokens no longer bonded) -- validator becomes bonded (ie when they're promoted into the top 100) - - total bonded delegation increases (tokens become bonded) - -*/ - -// BeforeDelegationCreated runs before a delegation is created -func (h Hooks) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { - // Add a claim if one doesn't exist, otherwise sync the existing. - h.k.InitializeDelegatorReward(ctx, delAddr) - - return nil -} - -// BeforeDelegationSharesModified runs before an existing delegation is modified -func (h Hooks) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { - // Sync rewards based on total delegated to bonded validators. - h.k.SynchronizeDelegatorRewards(ctx, delAddr, nil, false) - - return nil -} - -// BeforeValidatorSlashed is called before a validator is slashed -// Validator status is not updated when Slash or Jail is called -func (h Hooks) BeforeValidatorSlashed(ctx sdk.Context, valAddr sdk.ValAddress, fraction sdk.Dec) error { - // Sync all claims for users delegated to this validator. - // For each claim, sync based on the total delegated to bonded validators. - for _, delegation := range h.k.stakingKeeper.GetValidatorDelegations(ctx, valAddr) { - h.k.SynchronizeDelegatorRewards(ctx, delegation.GetDelegatorAddr(), nil, false) - } - - return nil -} - -// AfterValidatorBeginUnbonding is called after a validator begins unbonding -// Validator status is set to Unbonding prior to hook running -func (h Hooks) AfterValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) error { - // Sync all claims for users delegated to this validator. - // For each claim, sync based on the total delegated to bonded validators, and also delegations to valAddr. - // valAddr's status has just been set to Unbonding, but we want to include delegations to it in the sync. - for _, delegation := range h.k.stakingKeeper.GetValidatorDelegations(ctx, valAddr) { - h.k.SynchronizeDelegatorRewards(ctx, delegation.GetDelegatorAddr(), valAddr, true) - } - - return nil -} - -// AfterValidatorBonded is called after a validator is bonded -// Validator status is set to Bonded prior to hook running -func (h Hooks) AfterValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) error { - // Sync all claims for users delegated to this validator. - // For each claim, sync based on the total delegated to bonded validators, except for delegations to valAddr. - // valAddr's status has just been set to Bonded, but we don't want to include delegations to it in the sync - for _, delegation := range h.k.stakingKeeper.GetValidatorDelegations(ctx, valAddr) { - h.k.SynchronizeDelegatorRewards(ctx, delegation.GetDelegatorAddr(), valAddr, false) - } - - return nil -} - -// NOTE: following hooks are just implemented to ensure StakingHooks interface compliance - -// AfterDelegationModified runs after a delegation is modified -func (h Hooks) AfterDelegationModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { - return nil -} - -// BeforeDelegationRemoved runs directly before a delegation is deleted. BeforeDelegationSharesModified is run prior to this. -func (h Hooks) BeforeDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { - return nil -} - -// AfterValidatorCreated runs after a validator is created -func (h Hooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) error { - return nil -} - -// BeforeValidatorModified runs before a validator is modified -func (h Hooks) BeforeValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) error { - return nil -} - -// AfterValidatorRemoved runs after a validator is removed -func (h Hooks) AfterValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) error { - return nil -} - -// AfterUnbondingInitiated is called when an unbonding operation -// (validator unbonding, unbonding delegation, redelegation) was initiated -func (h Hooks) AfterUnbondingInitiated(_ sdk.Context, _ uint64) error { - return nil -} - -// ------------------- Swap Module Hooks ------------------- - -func (h Hooks) AfterPoolDepositCreated(ctx sdk.Context, poolID string, depositor sdk.AccAddress, _ sdkmath.Int) { - h.k.InitializeSwapReward(ctx, poolID, depositor) -} - -func (h Hooks) BeforePoolDepositModified(ctx sdk.Context, poolID string, depositor sdk.AccAddress, sharesOwned sdkmath.Int) { - h.k.SynchronizeSwapReward(ctx, poolID, depositor, sharesOwned) -} - -// ------------------- Savings Module Hooks ------------------- - -// AfterSavingsDepositCreated function that runs after a deposit is created -func (h Hooks) AfterSavingsDepositCreated(ctx sdk.Context, deposit savingstypes.Deposit) { - // h.k.InitializeSavingsReward(ctx, deposit) -} - -// BeforeSavingsDepositModified function that runs before a deposit is modified -func (h Hooks) BeforeSavingsDepositModified(ctx sdk.Context, deposit savingstypes.Deposit, incomingDenoms []string) { - // h.k.SynchronizeSavingsReward(ctx, deposit, incomingDenoms) -} - -// ------------------- Earn Module Hooks ------------------- - -// AfterVaultDepositCreated function that runs after a vault deposit is created -func (h Hooks) AfterVaultDepositCreated( - ctx sdk.Context, - vaultDenom string, - depositor sdk.AccAddress, - _ sdk.Dec, -) { - h.k.InitializeEarnReward(ctx, vaultDenom, depositor) -} - -// BeforeVaultDepositModified function that runs before a vault deposit is modified -func (h Hooks) BeforeVaultDepositModified( - ctx sdk.Context, - vaultDenom string, - depositor sdk.AccAddress, - sharesOwned sdk.Dec, -) { - h.k.SynchronizeEarnReward(ctx, vaultDenom, depositor, sharesOwned) -} diff --git a/x/incentive/keeper/integration_test.go b/x/incentive/keeper/integration_test.go deleted file mode 100644 index ecd440b1..00000000 --- a/x/incentive/keeper/integration_test.go +++ /dev/null @@ -1,239 +0,0 @@ -package keeper_test - -import ( - "time" - - sdkmath "cosmossdk.io/math" - "github.com/0glabs/0g-chain/app" - cdptypes "github.com/0glabs/0g-chain/x/cdp/types" - committeetypes "github.com/0glabs/0g-chain/x/committee/types" - "github.com/0glabs/0g-chain/x/incentive/testutil" - pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" - swaptypes "github.com/0glabs/0g-chain/x/swap/types" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// Avoid cluttering test cases with long function names -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 dc(denom string, amount string) sdk.DecCoin { - return sdk.NewDecCoinFromDec(denom, sdk.MustNewDecFromStr(amount)) -} -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } -func toDcs(coins ...sdk.Coin) sdk.DecCoins { return sdk.NewDecCoinsFromCoins(coins...) } -func dcs(coins ...sdk.DecCoin) sdk.DecCoins { return sdk.NewDecCoins(coins...) } - -func NewCDPGenStateMulti(cdc codec.JSONCodec) app.GenesisState { - cdpGenesis := cdptypes.GenesisState{ - Params: cdptypes.Params{ - GlobalDebtLimit: sdk.NewInt64Coin("usdx", 2000000000000), - SurplusAuctionThreshold: cdptypes.DefaultSurplusThreshold, - SurplusAuctionLot: cdptypes.DefaultSurplusLot, - DebtAuctionThreshold: cdptypes.DefaultDebtThreshold, - DebtAuctionLot: cdptypes.DefaultDebtLot, - LiquidationBlockInterval: cdptypes.DefaultBeginBlockerExecutionBlockInterval, - CollateralParams: cdptypes.CollateralParams{ - { - Denom: "xrp", - Type: "xrp-a", - LiquidationRatio: sdk.MustNewDecFromStr("2.0"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(7000000000), - SpotMarketID: "xrp:usd", - LiquidationMarketID: "xrp:usd", - ConversionFactor: i(6), - }, - { - Denom: "btc", - Type: "btc-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000000782997609"), // %2.5 apr - LiquidationPenalty: d("0.025"), - AuctionSize: i(10000000), - SpotMarketID: "btc:usd", - LiquidationMarketID: "btc:usd", - ConversionFactor: i(8), - }, - { - Denom: "bnb", - Type: "bnb-a", - LiquidationRatio: sdk.MustNewDecFromStr("1.5"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"), // %5 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(50000000000), - SpotMarketID: "bnb:usd", - LiquidationMarketID: "bnb:usd", - ConversionFactor: i(8), - }, - { - Denom: "busd", - Type: "busd-a", - LiquidationRatio: d("1.01"), - DebtLimit: sdk.NewInt64Coin("usdx", 500000000000), - StabilityFee: sdk.OneDec(), // %0 apr - LiquidationPenalty: d("0.05"), - AuctionSize: i(10000000000), - SpotMarketID: "busd:usd", - LiquidationMarketID: "busd:usd", - ConversionFactor: i(8), - }, - }, - DebtParam: cdptypes.DebtParam{ - Denom: "usdx", - ReferenceAsset: "usd", - ConversionFactor: i(6), - DebtFloor: i(10000000), - }, - }, - StartingCdpID: cdptypes.DefaultCdpStartingID, - DebtDenom: cdptypes.DefaultDebtDenom, - GovDenom: cdptypes.DefaultGovDenom, - CDPs: cdptypes.CDPs{}, - PreviousAccumulationTimes: cdptypes.GenesisAccumulationTimes{ - cdptypes.NewGenesisAccumulationTime("btc-a", time.Time{}, sdk.OneDec()), - cdptypes.NewGenesisAccumulationTime("xrp-a", time.Time{}, sdk.OneDec()), - cdptypes.NewGenesisAccumulationTime("busd-a", time.Time{}, sdk.OneDec()), - cdptypes.NewGenesisAccumulationTime("bnb-a", time.Time{}, sdk.OneDec()), - }, - TotalPrincipals: cdptypes.GenesisTotalPrincipals{ - cdptypes.NewGenesisTotalPrincipal("btc-a", sdk.ZeroInt()), - cdptypes.NewGenesisTotalPrincipal("xrp-a", sdk.ZeroInt()), - cdptypes.NewGenesisTotalPrincipal("busd-a", sdk.ZeroInt()), - cdptypes.NewGenesisTotalPrincipal("bnb-a", sdk.ZeroInt()), - }, - } - return app.GenesisState{cdptypes.ModuleName: cdc.MustMarshalJSON(&cdpGenesis)} -} - -func NewPricefeedGenStateMultiFromTime(cdc codec.JSONCodec, t time.Time) app.GenesisState { - expiry := 100 * 365 * 24 * time.Hour // 100 years - - pfGenesis := pricefeedtypes.GenesisState{ - Params: pricefeedtypes.Params{ - Markets: []pricefeedtypes.Market{ - {MarketID: "kava:usd", BaseAsset: "kava", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "btc:usd", BaseAsset: "btc", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "xrp:usd", BaseAsset: "xrp", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "bnb:usd", BaseAsset: "bnb", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "busd:usd", BaseAsset: "busd", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - {MarketID: "zzz:usd", BaseAsset: "zzz", QuoteAsset: "usd", Oracles: []sdk.AccAddress{}, Active: true}, - }, - }, - PostedPrices: []pricefeedtypes.PostedPrice{ - { - MarketID: "kava:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: t.Add(expiry), - }, - { - MarketID: "btc:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("8000.00"), - Expiry: t.Add(expiry), - }, - { - MarketID: "xrp:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("0.25"), - Expiry: t.Add(expiry), - }, - { - MarketID: "bnb:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("17.25"), - Expiry: t.Add(expiry), - }, - { - MarketID: "busd:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.OneDec(), - Expiry: t.Add(expiry), - }, - { - MarketID: "zzz:usd", - OracleAddress: sdk.AccAddress{}, - Price: sdk.MustNewDecFromStr("2.00"), - Expiry: t.Add(expiry), - }, - }, - } - return app.GenesisState{pricefeedtypes.ModuleName: cdc.MustMarshalJSON(&pfGenesis)} -} - -func NewHardGenStateMulti(genTime time.Time) testutil.HardGenesisBuilder { - kavaMM := testutil.NewStandardMoneyMarket("ukava") - kavaMM.SpotMarketID = "kava:usd" - btcMM := testutil.NewStandardMoneyMarket("btcb") - btcMM.SpotMarketID = "btc:usd" - - builder := testutil.NewHardGenesisBuilder().WithGenesisTime(genTime). - WithInitializedMoneyMarket(testutil.NewStandardMoneyMarket("usdx")). - WithInitializedMoneyMarket(kavaMM). - WithInitializedMoneyMarket(testutil.NewStandardMoneyMarket("bnb")). - WithInitializedMoneyMarket(btcMM). - WithInitializedMoneyMarket(testutil.NewStandardMoneyMarket("xrp")). - WithInitializedMoneyMarket(testutil.NewStandardMoneyMarket("zzz")) - return builder -} - -func NewStakingGenesisState(cdc codec.JSONCodec) app.GenesisState { - genState := stakingtypes.DefaultGenesisState() - genState.Params.BondDenom = "ukava" - return app.GenesisState{ - stakingtypes.ModuleName: cdc.MustMarshalJSON(genState), - } -} - -func NewCommitteeGenesisState(cdc codec.Codec, committeeID uint64, members ...sdk.AccAddress) app.GenesisState { - genState := committeetypes.DefaultGenesisState() - - com := committeetypes.MustNewMemberCommittee( - committeeID, - "This committee is for testing.", - members, - []committeetypes.Permission{&committeetypes.GodPermission{}}, - sdk.MustNewDecFromStr("0.666666667"), - time.Hour*24*7, - committeetypes.TALLY_OPTION_FIRST_PAST_THE_POST, - ) - - genesisComms := committeetypes.Committees{com} - - err := genesisComms.UnpackInterfaces(cdc) - if err != nil { - panic(err) - } - - committeesAny, err := committeetypes.PackCommittees(genesisComms) - if err != nil { - panic(err) - } - - genState.Committees = committeesAny - - return app.GenesisState{ - committeetypes.ModuleName: cdc.MustMarshalJSON(genState), - } -} - -func NewSwapGenesisState(cdc codec.JSONCodec) app.GenesisState { - genesis := swaptypes.NewGenesisState( - swaptypes.NewParams( - swaptypes.NewAllowedPools(swaptypes.NewAllowedPool("busd", "ukava")), - d("0.0"), - ), - swaptypes.DefaultPoolRecords, - swaptypes.DefaultShareRecords, - ) - return app.GenesisState{ - swaptypes.ModuleName: cdc.MustMarshalJSON(&genesis), - } -} diff --git a/x/incentive/keeper/keeper.go b/x/incentive/keeper/keeper.go deleted file mode 100644 index 78a8981a..00000000 --- a/x/incentive/keeper/keeper.go +++ /dev/null @@ -1,885 +0,0 @@ -package keeper - -import ( - "time" - - "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" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// Keeper keeper for the incentive module -type Keeper struct { - cdc codec.Codec - key storetypes.StoreKey - paramSubspace types.ParamSubspace - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - cdpKeeper types.CdpKeeper - hardKeeper types.HardKeeper - stakingKeeper types.StakingKeeper - swapKeeper types.SwapKeeper - savingsKeeper types.SavingsKeeper - liquidKeeper types.LiquidKeeper - earnKeeper types.EarnKeeper - - // Keepers used for APY queries - mintKeeper types.MintKeeper - distrKeeper types.DistrKeeper - pricefeedKeeper types.PricefeedKeeper -} - -// NewKeeper creates a new keeper -func NewKeeper( - cdc codec.Codec, key storetypes.StoreKey, paramstore types.ParamSubspace, bk types.BankKeeper, - cdpk types.CdpKeeper, hk types.HardKeeper, ak types.AccountKeeper, stk types.StakingKeeper, - swpk types.SwapKeeper, svk types.SavingsKeeper, lqk types.LiquidKeeper, ek types.EarnKeeper, - mk types.MintKeeper, dk types.DistrKeeper, pfk types.PricefeedKeeper, -) Keeper { - if !paramstore.HasKeyTable() { - paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) - } - - return Keeper{ - accountKeeper: ak, - cdc: cdc, - key: key, - paramSubspace: paramstore, - bankKeeper: bk, - cdpKeeper: cdpk, - hardKeeper: hk, - stakingKeeper: stk, - swapKeeper: swpk, - savingsKeeper: svk, - liquidKeeper: lqk, - earnKeeper: ek, - - mintKeeper: mk, - distrKeeper: dk, - pricefeedKeeper: pfk, - } -} - -// GetUSDXMintingClaim returns the claim in the store corresponding the input address collateral type and id and a boolean for if the claim was found -func (k Keeper) GetUSDXMintingClaim(ctx sdk.Context, addr sdk.AccAddress) (types.USDXMintingClaim, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.USDXMintingClaimKeyPrefix) - bz := store.Get(addr) - if bz == nil { - return types.USDXMintingClaim{}, false - } - var c types.USDXMintingClaim - k.cdc.MustUnmarshal(bz, &c) - return c, true -} - -// SetUSDXMintingClaim sets the claim in the store corresponding to the input address, collateral type, and id -func (k Keeper) SetUSDXMintingClaim(ctx sdk.Context, c types.USDXMintingClaim) { - store := prefix.NewStore(ctx.KVStore(k.key), types.USDXMintingClaimKeyPrefix) - bz := k.cdc.MustMarshal(&c) - store.Set(c.Owner, bz) -} - -// DeleteUSDXMintingClaim deletes the claim in the store corresponding to the input address, collateral type, and id -func (k Keeper) DeleteUSDXMintingClaim(ctx sdk.Context, owner sdk.AccAddress) { - store := prefix.NewStore(ctx.KVStore(k.key), types.USDXMintingClaimKeyPrefix) - store.Delete(owner) -} - -// IterateUSDXMintingClaims iterates over all claim objects in the store and preforms a callback function -func (k Keeper) IterateUSDXMintingClaims(ctx sdk.Context, cb func(c types.USDXMintingClaim) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.USDXMintingClaimKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var c types.USDXMintingClaim - k.cdc.MustUnmarshal(iterator.Value(), &c) - if cb(c) { - break - } - } -} - -// GetAllUSDXMintingClaims returns all Claim objects in the store -func (k Keeper) GetAllUSDXMintingClaims(ctx sdk.Context) types.USDXMintingClaims { - cs := types.USDXMintingClaims{} - k.IterateUSDXMintingClaims(ctx, func(c types.USDXMintingClaim) (stop bool) { - cs = append(cs, c) - return false - }) - return cs -} - -// GetPreviousUSDXMintingAccrualTime returns the last time a collateral type accrued USDX minting rewards -func (k Keeper) GetPreviousUSDXMintingAccrualTime(ctx sdk.Context, ctype string) (blockTime time.Time, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousUSDXMintingRewardAccrualTimeKeyPrefix) - b := store.Get([]byte(ctype)) - if b == nil { - return time.Time{}, false - } - if err := blockTime.UnmarshalBinary(b); err != nil { - panic(err) - } - return blockTime, true -} - -// SetPreviousUSDXMintingAccrualTime sets the last time a collateral type accrued USDX minting rewards -func (k Keeper) SetPreviousUSDXMintingAccrualTime(ctx sdk.Context, ctype string, blockTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousUSDXMintingRewardAccrualTimeKeyPrefix) - bz, err := blockTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set([]byte(ctype), bz) -} - -// IterateUSDXMintingAccrualTimes iterates over all previous USDX minting accrual times and preforms a callback function -func (k Keeper) IterateUSDXMintingAccrualTimes(ctx sdk.Context, cb func(string, time.Time) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousUSDXMintingRewardAccrualTimeKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var accrualTime time.Time - if err := accrualTime.UnmarshalBinary(iterator.Value()); err != nil { - panic(err) - } - denom := string(iterator.Key()) - if cb(denom, accrualTime) { - break - } - } -} - -// GetUSDXMintingRewardFactor returns the current reward factor for an individual collateral type -func (k Keeper) GetUSDXMintingRewardFactor(ctx sdk.Context, ctype string) (factor sdk.Dec, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.USDXMintingRewardFactorKeyPrefix) - bz := store.Get([]byte(ctype)) - if bz == nil { - return sdk.ZeroDec(), false - } - if err := factor.Unmarshal(bz); err != nil { - panic(err) - } - return factor, true -} - -// SetUSDXMintingRewardFactor sets the current reward factor for an individual collateral type -func (k Keeper) SetUSDXMintingRewardFactor(ctx sdk.Context, ctype string, factor sdk.Dec) { - store := prefix.NewStore(ctx.KVStore(k.key), types.USDXMintingRewardFactorKeyPrefix) - bz, err := factor.Marshal() - if err != nil { - panic(err) - } - store.Set([]byte(ctype), bz) -} - -// IterateUSDXMintingRewardFactors iterates over all USDX Minting reward factor objects in the store and preforms a callback function -func (k Keeper) IterateUSDXMintingRewardFactors(ctx sdk.Context, cb func(denom string, factor sdk.Dec) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.USDXMintingRewardFactorKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var factor sdk.Dec - if err := factor.Unmarshal(iterator.Value()); err != nil { - panic(err) - } - if cb(string(iterator.Key()), factor) { - break - } - } -} - -// GetHardLiquidityProviderClaim returns the claim in the store corresponding the input address collateral type and id and a boolean for if the claim was found -func (k Keeper) GetHardLiquidityProviderClaim(ctx sdk.Context, addr sdk.AccAddress) (types.HardLiquidityProviderClaim, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardLiquidityClaimKeyPrefix) - bz := store.Get(addr) - if bz == nil { - return types.HardLiquidityProviderClaim{}, false - } - var c types.HardLiquidityProviderClaim - k.cdc.MustUnmarshal(bz, &c) - return c, true -} - -// SetHardLiquidityProviderClaim sets the claim in the store corresponding to the input address, collateral type, and id -func (k Keeper) SetHardLiquidityProviderClaim(ctx sdk.Context, c types.HardLiquidityProviderClaim) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardLiquidityClaimKeyPrefix) - bz := k.cdc.MustMarshal(&c) - store.Set(c.Owner, bz) -} - -// DeleteHardLiquidityProviderClaim deletes the claim in the store corresponding to the input address, collateral type, and id -func (k Keeper) DeleteHardLiquidityProviderClaim(ctx sdk.Context, owner sdk.AccAddress) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardLiquidityClaimKeyPrefix) - store.Delete(owner) -} - -// IterateHardLiquidityProviderClaims iterates over all claim objects in the store and preforms a callback function -func (k Keeper) IterateHardLiquidityProviderClaims(ctx sdk.Context, cb func(c types.HardLiquidityProviderClaim) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardLiquidityClaimKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var c types.HardLiquidityProviderClaim - k.cdc.MustUnmarshal(iterator.Value(), &c) - if cb(c) { - break - } - } -} - -// GetAllHardLiquidityProviderClaims returns all Claim objects in the store -func (k Keeper) GetAllHardLiquidityProviderClaims(ctx sdk.Context) types.HardLiquidityProviderClaims { - cs := types.HardLiquidityProviderClaims{} - k.IterateHardLiquidityProviderClaims(ctx, func(c types.HardLiquidityProviderClaim) (stop bool) { - cs = append(cs, c) - return false - }) - return cs -} - -// GetDelegatorClaim returns the claim in the store corresponding the input address collateral type and id and a boolean for if the claim was found -func (k Keeper) GetDelegatorClaim(ctx sdk.Context, addr sdk.AccAddress) (types.DelegatorClaim, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DelegatorClaimKeyPrefix) - bz := store.Get(addr) - if bz == nil { - return types.DelegatorClaim{}, false - } - var c types.DelegatorClaim - k.cdc.MustUnmarshal(bz, &c) - return c, true -} - -// SetDelegatorClaim sets the claim in the store corresponding to the input address, collateral type, and id -func (k Keeper) SetDelegatorClaim(ctx sdk.Context, c types.DelegatorClaim) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DelegatorClaimKeyPrefix) - bz := k.cdc.MustMarshal(&c) - store.Set(c.Owner, bz) -} - -// DeleteDelegatorClaim deletes the claim in the store corresponding to the input address, collateral type, and id -func (k Keeper) DeleteDelegatorClaim(ctx sdk.Context, owner sdk.AccAddress) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DelegatorClaimKeyPrefix) - store.Delete(owner) -} - -// IterateDelegatorClaims iterates over all claim objects in the store and preforms a callback function -func (k Keeper) IterateDelegatorClaims(ctx sdk.Context, cb func(c types.DelegatorClaim) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DelegatorClaimKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var c types.DelegatorClaim - k.cdc.MustUnmarshal(iterator.Value(), &c) - if cb(c) { - break - } - } -} - -// GetAllDelegatorClaims returns all DelegatorClaim objects in the store -func (k Keeper) GetAllDelegatorClaims(ctx sdk.Context) types.DelegatorClaims { - cs := types.DelegatorClaims{} - k.IterateDelegatorClaims(ctx, func(c types.DelegatorClaim) (stop bool) { - cs = append(cs, c) - return false - }) - return cs -} - -// GetSwapClaim returns the claim in the store corresponding the input address. -func (k Keeper) GetSwapClaim(ctx sdk.Context, addr sdk.AccAddress) (types.SwapClaim, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SwapClaimKeyPrefix) - bz := store.Get(addr) - if bz == nil { - return types.SwapClaim{}, false - } - var c types.SwapClaim - k.cdc.MustUnmarshal(bz, &c) - return c, true -} - -// SetSwapClaim sets the claim in the store corresponding to the input address. -func (k Keeper) SetSwapClaim(ctx sdk.Context, c types.SwapClaim) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SwapClaimKeyPrefix) - bz := k.cdc.MustMarshal(&c) - store.Set(c.Owner, bz) -} - -// DeleteSwapClaim deletes the claim in the store corresponding to the input address. -func (k Keeper) DeleteSwapClaim(ctx sdk.Context, owner sdk.AccAddress) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SwapClaimKeyPrefix) - store.Delete(owner) -} - -// IterateSwapClaims iterates over all claim objects in the store and preforms a callback function -func (k Keeper) IterateSwapClaims(ctx sdk.Context, cb func(c types.SwapClaim) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SwapClaimKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var c types.SwapClaim - k.cdc.MustUnmarshal(iterator.Value(), &c) - if cb(c) { - break - } - } -} - -// GetAllSwapClaims returns all Claim objects in the store -func (k Keeper) GetAllSwapClaims(ctx sdk.Context) types.SwapClaims { - cs := types.SwapClaims{} - k.IterateSwapClaims(ctx, func(c types.SwapClaim) (stop bool) { - cs = append(cs, c) - return false - }) - return cs -} - -// GetSavingsClaim returns the claim in the store corresponding the input address. -func (k Keeper) GetSavingsClaim(ctx sdk.Context, addr sdk.AccAddress) (types.SavingsClaim, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SavingsClaimKeyPrefix) - bz := store.Get(addr) - if bz == nil { - return types.SavingsClaim{}, false - } - var c types.SavingsClaim - k.cdc.MustUnmarshal(bz, &c) - return c, true -} - -// SetSavingsClaim sets the claim in the store corresponding to the input address. -func (k Keeper) SetSavingsClaim(ctx sdk.Context, c types.SavingsClaim) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SavingsClaimKeyPrefix) - bz := k.cdc.MustMarshal(&c) - store.Set(c.Owner, bz) -} - -// DeleteSavingsClaim deletes the claim in the store corresponding to the input address. -func (k Keeper) DeleteSavingsClaim(ctx sdk.Context, owner sdk.AccAddress) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SavingsClaimKeyPrefix) - store.Delete(owner) -} - -// IterateSavingsClaims iterates over all savings claim objects in the store and preforms a callback function -func (k Keeper) IterateSavingsClaims(ctx sdk.Context, cb func(c types.SavingsClaim) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SavingsClaimKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var c types.SavingsClaim - k.cdc.MustUnmarshal(iterator.Value(), &c) - if cb(c) { - break - } - } -} - -// GetAllSavingsClaims returns all savings claim objects in the store -func (k Keeper) GetAllSavingsClaims(ctx sdk.Context) types.SavingsClaims { - cs := types.SavingsClaims{} - k.IterateSavingsClaims(ctx, func(c types.SavingsClaim) (stop bool) { - cs = append(cs, c) - return false - }) - return cs -} - -// GetEarnClaim returns the claim in the store corresponding the input address. -func (k Keeper) GetEarnClaim(ctx sdk.Context, addr sdk.AccAddress) (types.EarnClaim, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.EarnClaimKeyPrefix) - bz := store.Get(addr) - if bz == nil { - return types.EarnClaim{}, false - } - var c types.EarnClaim - k.cdc.MustUnmarshal(bz, &c) - return c, true -} - -// SetEarnClaim sets the claim in the store corresponding to the input address. -func (k Keeper) SetEarnClaim(ctx sdk.Context, c types.EarnClaim) { - store := prefix.NewStore(ctx.KVStore(k.key), types.EarnClaimKeyPrefix) - bz := k.cdc.MustMarshal(&c) - store.Set(c.Owner, bz) -} - -// DeleteEarnClaim deletes the claim in the store corresponding to the input address. -func (k Keeper) DeleteEarnClaim(ctx sdk.Context, owner sdk.AccAddress) { - store := prefix.NewStore(ctx.KVStore(k.key), types.EarnClaimKeyPrefix) - store.Delete(owner) -} - -// IterateEarnClaims iterates over all claim objects in the store and preforms a callback function -func (k Keeper) IterateEarnClaims(ctx sdk.Context, cb func(c types.EarnClaim) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.EarnClaimKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var c types.EarnClaim - k.cdc.MustUnmarshal(iterator.Value(), &c) - if cb(c) { - break - } - } -} - -// GetAllEarnClaims returns all Claim objects in the store -func (k Keeper) GetAllEarnClaims(ctx sdk.Context) types.EarnClaims { - cs := types.EarnClaims{} - k.IterateEarnClaims(ctx, func(c types.EarnClaim) (stop bool) { - cs = append(cs, c) - return false - }) - return cs -} - -// SetHardSupplyRewardIndexes sets the current reward indexes for an individual denom -func (k Keeper) SetHardSupplyRewardIndexes(ctx sdk.Context, denom string, indexes types.RewardIndexes) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardSupplyRewardIndexesKeyPrefix) - bz := k.cdc.MustMarshal(&types.RewardIndexesProto{ - RewardIndexes: indexes, - }) - store.Set([]byte(denom), bz) -} - -// GetHardSupplyRewardIndexes gets the current reward indexes for an individual denom -func (k Keeper) GetHardSupplyRewardIndexes(ctx sdk.Context, denom string) (types.RewardIndexes, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardSupplyRewardIndexesKeyPrefix) - bz := store.Get([]byte(denom)) - if bz == nil { - return types.RewardIndexes{}, false - } - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(bz, &proto) - - return proto.RewardIndexes, true -} - -// IterateHardSupplyRewardIndexes iterates over all Hard supply reward index objects in the store and preforms a callback function -func (k Keeper) IterateHardSupplyRewardIndexes(ctx sdk.Context, cb func(denom string, indexes types.RewardIndexes) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardSupplyRewardIndexesKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(iterator.Value(), &proto) - if cb(string(iterator.Key()), proto.RewardIndexes) { - break - } - } -} - -func (k Keeper) IterateHardSupplyRewardAccrualTimes(ctx sdk.Context, cb func(string, time.Time) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousHardSupplyRewardAccrualTimeKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var accrualTime time.Time - if err := accrualTime.UnmarshalBinary(iterator.Value()); err != nil { - panic(err) - } - denom := string(iterator.Key()) - if cb(denom, accrualTime) { - break - } - } -} - -// SetHardBorrowRewardIndexes sets the current reward indexes for an individual denom -func (k Keeper) SetHardBorrowRewardIndexes(ctx sdk.Context, denom string, indexes types.RewardIndexes) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardBorrowRewardIndexesKeyPrefix) - bz := k.cdc.MustMarshal(&types.RewardIndexesProto{ - RewardIndexes: indexes, - }) - store.Set([]byte(denom), bz) -} - -// GetHardBorrowRewardIndexes gets the current reward indexes for an individual denom -func (k Keeper) GetHardBorrowRewardIndexes(ctx sdk.Context, denom string) (types.RewardIndexes, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardBorrowRewardIndexesKeyPrefix) - bz := store.Get([]byte(denom)) - if bz == nil { - return types.RewardIndexes{}, false - } - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(bz, &proto) - - return proto.RewardIndexes, true -} - -// IterateHardBorrowRewardIndexes iterates over all Hard borrow reward index objects in the store and preforms a callback function -func (k Keeper) IterateHardBorrowRewardIndexes(ctx sdk.Context, cb func(denom string, indexes types.RewardIndexes) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.HardBorrowRewardIndexesKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(iterator.Value(), &proto) - if cb(string(iterator.Key()), proto.RewardIndexes) { - break - } - } -} - -func (k Keeper) IterateHardBorrowRewardAccrualTimes(ctx sdk.Context, cb func(string, time.Time) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousHardBorrowRewardAccrualTimeKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - denom := string(iterator.Key()) - var accrualTime time.Time - if err := accrualTime.UnmarshalBinary(iterator.Value()); err != nil { - panic(err) - } - if cb(denom, accrualTime) { - break - } - } -} - -// GetDelegatorRewardIndexes gets the current reward indexes for an individual denom -func (k Keeper) GetDelegatorRewardIndexes(ctx sdk.Context, denom string) (types.RewardIndexes, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DelegatorRewardIndexesKeyPrefix) - bz := store.Get([]byte(denom)) - if bz == nil { - return types.RewardIndexes{}, false - } - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(bz, &proto) - - return proto.RewardIndexes, true -} - -// SetDelegatorRewardIndexes sets the current reward indexes for an individual denom -func (k Keeper) SetDelegatorRewardIndexes(ctx sdk.Context, denom string, indexes types.RewardIndexes) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DelegatorRewardIndexesKeyPrefix) - bz := k.cdc.MustMarshal(&types.RewardIndexesProto{ - RewardIndexes: indexes, - }) - store.Set([]byte(denom), bz) -} - -// IterateDelegatorRewardIndexes iterates over all delegator reward index objects in the store and preforms a callback function -func (k Keeper) IterateDelegatorRewardIndexes(ctx sdk.Context, cb func(denom string, indexes types.RewardIndexes) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DelegatorRewardIndexesKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(iterator.Value(), &proto) - if cb(string(iterator.Key()), proto.RewardIndexes) { - break - } - } -} - -func (k Keeper) IterateDelegatorRewardAccrualTimes(ctx sdk.Context, cb func(string, time.Time) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousDelegatorRewardAccrualTimeKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - denom := string(iterator.Key()) - var accrualTime time.Time - if err := accrualTime.UnmarshalBinary(iterator.Value()); err != nil { - panic(err) - } - if cb(denom, accrualTime) { - break - } - } -} - -// GetPreviousHardSupplyRewardAccrualTime returns the last time a denom accrued Hard protocol supply-side rewards -func (k Keeper) GetPreviousHardSupplyRewardAccrualTime(ctx sdk.Context, denom string) (blockTime time.Time, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousHardSupplyRewardAccrualTimeKeyPrefix) - bz := store.Get([]byte(denom)) - if bz == nil { - return time.Time{}, false - } - if err := blockTime.UnmarshalBinary(bz); err != nil { - panic(err) - } - return blockTime, true -} - -// SetPreviousHardSupplyRewardAccrualTime sets the last time a denom accrued Hard protocol supply-side rewards -func (k Keeper) SetPreviousHardSupplyRewardAccrualTime(ctx sdk.Context, denom string, blockTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousHardSupplyRewardAccrualTimeKeyPrefix) - bz, err := blockTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set([]byte(denom), bz) -} - -// GetPreviousHardBorrowRewardAccrualTime returns the last time a denom accrued Hard protocol borrow-side rewards -func (k Keeper) GetPreviousHardBorrowRewardAccrualTime(ctx sdk.Context, denom string) (blockTime time.Time, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousHardBorrowRewardAccrualTimeKeyPrefix) - b := store.Get([]byte(denom)) - if b == nil { - return time.Time{}, false - } - if err := blockTime.UnmarshalBinary(b); err != nil { - panic(err) - } - return blockTime, true -} - -// SetPreviousHardBorrowRewardAccrualTime sets the last time a denom accrued Hard protocol borrow-side rewards -func (k Keeper) SetPreviousHardBorrowRewardAccrualTime(ctx sdk.Context, denom string, blockTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousHardBorrowRewardAccrualTimeKeyPrefix) - bz, err := blockTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set([]byte(denom), bz) -} - -// GetPreviousDelegatorRewardAccrualTime returns the last time a denom accrued protocol delegator rewards -func (k Keeper) GetPreviousDelegatorRewardAccrualTime(ctx sdk.Context, denom string) (blockTime time.Time, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousDelegatorRewardAccrualTimeKeyPrefix) - bz := store.Get([]byte(denom)) - if bz == nil { - return time.Time{}, false - } - if err := blockTime.UnmarshalBinary(bz); err != nil { - panic(err) - } - return blockTime, true -} - -// SetPreviousDelegatorRewardAccrualTime sets the last time a denom accrued protocol delegator rewards -func (k Keeper) SetPreviousDelegatorRewardAccrualTime(ctx sdk.Context, denom string, blockTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousDelegatorRewardAccrualTimeKeyPrefix) - bz, err := blockTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set([]byte(denom), bz) -} - -// SetSwapRewardIndexes stores the global reward indexes that track total rewards to a swap pool. -func (k Keeper) SetSwapRewardIndexes(ctx sdk.Context, poolID string, indexes types.RewardIndexes) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SwapRewardIndexesKeyPrefix) - bz := k.cdc.MustMarshal(&types.RewardIndexesProto{ - RewardIndexes: indexes, - }) - store.Set([]byte(poolID), bz) -} - -// GetSwapRewardIndexes fetches the global reward indexes that track total rewards to a swap pool. -func (k Keeper) GetSwapRewardIndexes(ctx sdk.Context, poolID string) (types.RewardIndexes, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SwapRewardIndexesKeyPrefix) - bz := store.Get([]byte(poolID)) - if bz == nil { - return types.RewardIndexes{}, false - } - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(bz, &proto) - return proto.RewardIndexes, true -} - -// IterateSwapRewardIndexes iterates over all swap reward index objects in the store and preforms a callback function -func (k Keeper) IterateSwapRewardIndexes(ctx sdk.Context, cb func(poolID string, indexes types.RewardIndexes) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SwapRewardIndexesKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(iterator.Value(), &proto) - if cb(string(iterator.Key()), proto.RewardIndexes) { - break - } - } -} - -// GetSwapRewardAccrualTime fetches the last time rewards were accrued for a swap pool. -func (k Keeper) GetSwapRewardAccrualTime(ctx sdk.Context, poolID string) (blockTime time.Time, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousSwapRewardAccrualTimeKeyPrefix) - b := store.Get([]byte(poolID)) - if b == nil { - return time.Time{}, false - } - if err := blockTime.UnmarshalBinary(b); err != nil { - panic(err) - } - return blockTime, true -} - -// SetSwapRewardAccrualTime stores the last time rewards were accrued for a swap pool. -func (k Keeper) SetSwapRewardAccrualTime(ctx sdk.Context, poolID string, blockTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousSwapRewardAccrualTimeKeyPrefix) - bz, err := blockTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set([]byte(poolID), bz) -} - -func (k Keeper) IterateSwapRewardAccrualTimes(ctx sdk.Context, cb func(string, time.Time) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousSwapRewardAccrualTimeKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - poolID := string(iterator.Key()) - var accrualTime time.Time - if err := accrualTime.UnmarshalBinary(iterator.Value()); err != nil { - panic(err) - } - if cb(poolID, accrualTime) { - break - } - } -} - -// SetSavingsRewardIndexes stores the global reward indexes that rewards for an individual denom type -func (k Keeper) SetSavingsRewardIndexes(ctx sdk.Context, denom string, indexes types.RewardIndexes) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SavingsRewardIndexesKeyPrefix) - bz := k.cdc.MustMarshal(&types.RewardIndexesProto{ - RewardIndexes: indexes, - }) - store.Set([]byte(denom), bz) -} - -// GetSavingsRewardIndexes fetches the global reward indexes that track rewards for an individual denom type -func (k Keeper) GetSavingsRewardIndexes(ctx sdk.Context, denom string) (types.RewardIndexes, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SavingsRewardIndexesKeyPrefix) - bz := store.Get([]byte(denom)) - if bz == nil { - return types.RewardIndexes{}, false - } - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(bz, &proto) - return proto.RewardIndexes, true -} - -// IterateSavingsRewardIndexes iterates over all savings reward index objects in the store and preforms a callback function -func (k Keeper) IterateSavingsRewardIndexes(ctx sdk.Context, cb func(poolID string, indexes types.RewardIndexes) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.SavingsRewardIndexesKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(iterator.Value(), &proto) - if cb(string(iterator.Key()), proto.RewardIndexes) { - break - } - } -} - -// GetSavingsRewardAccrualTime fetches the last time rewards were accrued for an individual denom type -func (k Keeper) GetSavingsRewardAccrualTime(ctx sdk.Context, poolID string) (blockTime time.Time, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousSavingsRewardAccrualTimeKeyPrefix) - b := store.Get([]byte(poolID)) - if b == nil { - return time.Time{}, false - } - if err := blockTime.UnmarshalBinary(b); err != nil { - panic(err) - } - return blockTime, true -} - -// SetSavingsRewardAccrualTime stores the last time rewards were accrued for a savings deposit denom type -func (k Keeper) SetSavingsRewardAccrualTime(ctx sdk.Context, poolID string, blockTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousSavingsRewardAccrualTimeKeyPrefix) - bz, err := blockTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set([]byte(poolID), bz) -} - -// IterateSavingsRewardAccrualTimesiterates over all the previous savings reward accrual times in the store -func (k Keeper) IterateSavingsRewardAccrualTimes(ctx sdk.Context, cb func(string, time.Time) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousSavingsRewardAccrualTimeKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - poolID := string(iterator.Key()) - var accrualTime time.Time - if err := accrualTime.UnmarshalBinary(iterator.Value()); err != nil { - panic(err) - } - if cb(poolID, accrualTime) { - break - } - } -} - -// SetEarnRewardIndexes stores the global reward indexes that track total rewards to a earn vault. -func (k Keeper) SetEarnRewardIndexes(ctx sdk.Context, vaultDenom string, indexes types.RewardIndexes) { - store := prefix.NewStore(ctx.KVStore(k.key), types.EarnRewardIndexesKeyPrefix) - bz := k.cdc.MustMarshal(&types.RewardIndexesProto{ - RewardIndexes: indexes, - }) - store.Set([]byte(vaultDenom), bz) -} - -// GetEarnRewardIndexes fetches the global reward indexes that track total rewards to a earn vault. -func (k Keeper) GetEarnRewardIndexes(ctx sdk.Context, vaultDenom string) (types.RewardIndexes, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.EarnRewardIndexesKeyPrefix) - bz := store.Get([]byte(vaultDenom)) - if bz == nil { - return types.RewardIndexes{}, false - } - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(bz, &proto) - return proto.RewardIndexes, true -} - -// IterateEarnRewardIndexes iterates over all earn reward index objects in the store and preforms a callback function -func (k Keeper) IterateEarnRewardIndexes(ctx sdk.Context, cb func(vaultDenom string, indexes types.RewardIndexes) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.EarnRewardIndexesKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var proto types.RewardIndexesProto - k.cdc.MustUnmarshal(iterator.Value(), &proto) - if cb(string(iterator.Key()), proto.RewardIndexes) { - break - } - } -} - -// GetEarnRewardAccrualTime fetches the last time rewards were accrued for an earn vault. -func (k Keeper) GetEarnRewardAccrualTime(ctx sdk.Context, vaultDenom string) (blockTime time.Time, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousEarnRewardAccrualTimeKeyPrefix) - b := store.Get([]byte(vaultDenom)) - if b == nil { - return time.Time{}, false - } - if err := blockTime.UnmarshalBinary(b); err != nil { - panic(err) - } - return blockTime, true -} - -// SetEarnRewardAccrualTime stores the last time rewards were accrued for a earn vault. -func (k Keeper) SetEarnRewardAccrualTime(ctx sdk.Context, vaultDenom string, blockTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousEarnRewardAccrualTimeKeyPrefix) - bz, err := blockTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set([]byte(vaultDenom), bz) -} - -func (k Keeper) IterateEarnRewardAccrualTimes(ctx sdk.Context, cb func(string, time.Time) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousEarnRewardAccrualTimeKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - poolID := string(iterator.Key()) - var accrualTime time.Time - if err := accrualTime.UnmarshalBinary(iterator.Value()); err != nil { - panic(err) - } - if cb(poolID, accrualTime) { - break - } - } -} diff --git a/x/incentive/keeper/keeper_test.go b/x/incentive/keeper/keeper_test.go deleted file mode 100644 index ac12f808..00000000 --- a/x/incentive/keeper/keeper_test.go +++ /dev/null @@ -1,629 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/incentive/keeper" - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// Test suite used for all keeper tests -type KeeperTestSuite struct { - suite.Suite - - keeper keeper.Keeper - - app app.TestApp - ctx sdk.Context - - genesisTime time.Time - addrs []sdk.AccAddress -} - -// SetupTest is run automatically before each suite test -func (suite *KeeperTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - _, suite.addrs = app.GeneratePrivKeyAddressPairs(5) - - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *KeeperTestSuite) SetupApp() { - suite.app = app.NewTestApp() - - suite.keeper = suite.app.GetIncentiveKeeper() - - suite.ctx = suite.app.NewContext(true, tmprototypes.Header{Time: suite.genesisTime}) -} - -func (suite *KeeperTestSuite) TestGetSetDeleteUSDXMintingClaim() { - suite.SetupApp() - c := types.NewUSDXMintingClaim(suite.addrs[0], c("ukava", 1000000), types.RewardIndexes{types.NewRewardIndex("bnb-a", sdk.ZeroDec())}) - _, found := suite.keeper.GetUSDXMintingClaim(suite.ctx, suite.addrs[0]) - suite.Require().False(found) - suite.Require().NotPanics(func() { - suite.keeper.SetUSDXMintingClaim(suite.ctx, c) - }) - testC, found := suite.keeper.GetUSDXMintingClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - suite.Require().Equal(c, testC) - suite.Require().NotPanics(func() { - suite.keeper.DeleteUSDXMintingClaim(suite.ctx, suite.addrs[0]) - }) - _, found = suite.keeper.GetUSDXMintingClaim(suite.ctx, suite.addrs[0]) - suite.Require().False(found) -} - -func (suite *KeeperTestSuite) TestIterateUSDXMintingClaims() { - suite.SetupApp() - for i := 0; i < len(suite.addrs); i++ { - c := types.NewUSDXMintingClaim(suite.addrs[i], c("ukava", 100000), types.RewardIndexes{types.NewRewardIndex("bnb-a", sdk.ZeroDec())}) - suite.Require().NotPanics(func() { - suite.keeper.SetUSDXMintingClaim(suite.ctx, c) - }) - } - claims := types.USDXMintingClaims{} - suite.keeper.IterateUSDXMintingClaims(suite.ctx, func(c types.USDXMintingClaim) bool { - claims = append(claims, c) - return false - }) - suite.Require().Equal(len(suite.addrs), len(claims)) - - claims = suite.keeper.GetAllUSDXMintingClaims(suite.ctx) - suite.Require().Equal(len(suite.addrs), len(claims)) -} - -func (suite *KeeperTestSuite) TestGetSetDeleteSwapClaims() { - suite.SetupApp() - c := types.NewSwapClaim(suite.addrs[0], arbitraryCoins(), nonEmptyMultiRewardIndexes) - - _, found := suite.keeper.GetSwapClaim(suite.ctx, suite.addrs[0]) - suite.Require().False(found) - - suite.Require().NotPanics(func() { - suite.keeper.SetSwapClaim(suite.ctx, c) - }) - testC, found := suite.keeper.GetSwapClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - suite.Require().Equal(c, testC) - - suite.Require().NotPanics(func() { - suite.keeper.DeleteSwapClaim(suite.ctx, suite.addrs[0]) - }) - _, found = suite.keeper.GetSwapClaim(suite.ctx, suite.addrs[0]) - suite.Require().False(found) -} - -func (suite *KeeperTestSuite) TestIterateSwapClaims() { - suite.SetupApp() - claims := types.SwapClaims{ - types.NewSwapClaim(suite.addrs[0], arbitraryCoins(), nonEmptyMultiRewardIndexes), - types.NewSwapClaim(suite.addrs[1], nil, nil), // different claim to the first - } - for _, claim := range claims { - suite.keeper.SetSwapClaim(suite.ctx, claim) - } - - var actualClaims types.SwapClaims - suite.keeper.IterateSwapClaims(suite.ctx, func(c types.SwapClaim) bool { - actualClaims = append(actualClaims, c) - return false - }) - - suite.Require().Equal(claims, actualClaims) -} - -func (suite *KeeperTestSuite) TestGetSetSwapRewardIndexes() { - testCases := []struct { - name string - poolName string - indexes types.RewardIndexes - wantIndex types.RewardIndexes - panics bool - }{ - { - name: "two factors can be written and read", - poolName: "btc/usdx", - indexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - wantIndex: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - name: "indexes with empty pool name panics", - poolName: "", - indexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - panics: true, - }, - { - // this test is to detect any changes in behavior - name: "setting empty indexes does not panic", - poolName: "btc/usdx", - // Marshalling empty slice results in [] bytes, unmarshalling the [] - // empty bytes results in a nil slice instead of an empty slice - indexes: types.RewardIndexes{}, - wantIndex: nil, - panics: false, - }, - { - // this test is to detect any changes in behavior - name: "setting nil indexes does not panic", - poolName: "btc/usdx", - indexes: nil, - wantIndex: nil, - panics: false, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupApp() - - _, found := suite.keeper.GetSwapRewardIndexes(suite.ctx, tc.poolName) - suite.False(found) - - setFunc := func() { suite.keeper.SetSwapRewardIndexes(suite.ctx, tc.poolName, tc.indexes) } - if tc.panics { - suite.Panics(setFunc) - return - } else { - suite.NotPanics(setFunc) - } - - storedIndexes, found := suite.keeper.GetSwapRewardIndexes(suite.ctx, tc.poolName) - suite.True(found) - suite.Equal(tc.wantIndex, storedIndexes) - }) - } -} - -func (suite *KeeperTestSuite) TestIterateSwapRewardIndexes() { - suite.SetupApp() - multiIndexes := types.MultiRewardIndexes{ - { - CollateralType: "bnb/usdx", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "swap", - RewardFactor: d("0.0000002"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: "btcb/usdx", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - }, - }, - } - for _, mi := range multiIndexes { - suite.keeper.SetSwapRewardIndexes(suite.ctx, mi.CollateralType, mi.RewardIndexes) - } - - var actualMultiIndexes types.MultiRewardIndexes - suite.keeper.IterateSwapRewardIndexes(suite.ctx, func(poolID string, i types.RewardIndexes) bool { - actualMultiIndexes = actualMultiIndexes.With(poolID, i) - return false - }) - - suite.Require().Equal(multiIndexes, actualMultiIndexes) -} - -func (suite *KeeperTestSuite) TestGetSetSwapRewardAccrualTimes() { - testCases := []struct { - name string - poolName string - accrualTime time.Time - panics bool - }{ - { - name: "normal time can be written and read", - poolName: "btc/usdx", - accrualTime: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - { - name: "zero time can be written and read", - poolName: "btc/usdx", - accrualTime: time.Time{}, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupApp() - - _, found := suite.keeper.GetSwapRewardAccrualTime(suite.ctx, tc.poolName) - suite.False(found) - - setFunc := func() { suite.keeper.SetSwapRewardAccrualTime(suite.ctx, tc.poolName, tc.accrualTime) } - if tc.panics { - suite.Panics(setFunc) - return - } else { - suite.NotPanics(setFunc) - } - - storedTime, found := suite.keeper.GetSwapRewardAccrualTime(suite.ctx, tc.poolName) - suite.True(found) - suite.Equal(tc.accrualTime, storedTime) - }) - } -} - -func (suite *KeeperTestSuite) TestGetSetDeleteEarnClaims() { - suite.SetupApp() - c := types.NewEarnClaim(suite.addrs[0], arbitraryCoins(), nonEmptyMultiRewardIndexes) - - _, found := suite.keeper.GetEarnClaim(suite.ctx, suite.addrs[0]) - suite.Require().False(found) - - suite.Require().NotPanics(func() { - suite.keeper.SetEarnClaim(suite.ctx, c) - }) - testC, found := suite.keeper.GetEarnClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - suite.Require().Equal(c, testC) - - suite.Require().NotPanics(func() { - suite.keeper.DeleteEarnClaim(suite.ctx, suite.addrs[0]) - }) - _, found = suite.keeper.GetEarnClaim(suite.ctx, suite.addrs[0]) - suite.Require().False(found) -} - -func (suite *KeeperTestSuite) TestIterateEarnClaims() { - suite.SetupApp() - claims := types.EarnClaims{ - types.NewEarnClaim(suite.addrs[0], arbitraryCoins(), nonEmptyMultiRewardIndexes), - types.NewEarnClaim(suite.addrs[1], nil, nil), // different claim to the first - } - for _, claim := range claims { - suite.keeper.SetEarnClaim(suite.ctx, claim) - } - - var actualClaims types.EarnClaims - suite.keeper.IterateEarnClaims(suite.ctx, func(c types.EarnClaim) bool { - actualClaims = append(actualClaims, c) - return false - }) - - suite.Require().Equal(claims, actualClaims) -} - -func (suite *KeeperTestSuite) TestGetSetEarnRewardIndexes() { - testCases := []struct { - name string - vaultDenom string - indexes types.RewardIndexes - wantIndex types.RewardIndexes - panics bool - }{ - { - name: "two factors can be written and read", - vaultDenom: "usdx", - indexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - wantIndex: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - name: "indexes with empty vault name panics", - vaultDenom: "", - indexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - panics: true, - }, - { - // this test is to detect any changes in behavior - name: "setting empty indexes does not panic", - vaultDenom: "usdx", - // Marshalling empty slice results in [] bytes, unmarshalling the [] - // empty bytes results in a nil slice instead of an empty slice - indexes: types.RewardIndexes{}, - wantIndex: nil, - panics: false, - }, - { - // this test is to detect any changes in behavior - name: "setting nil indexes does not panic", - vaultDenom: "usdx", - indexes: nil, - wantIndex: nil, - panics: false, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupApp() - - _, found := suite.keeper.GetEarnRewardIndexes(suite.ctx, tc.vaultDenom) - suite.False(found) - - setFunc := func() { suite.keeper.SetEarnRewardIndexes(suite.ctx, tc.vaultDenom, tc.indexes) } - if tc.panics { - suite.Panics(setFunc) - return - } else { - suite.NotPanics(setFunc) - } - - storedIndexes, found := suite.keeper.GetEarnRewardIndexes(suite.ctx, tc.vaultDenom) - suite.True(found) - suite.Equal(tc.wantIndex, storedIndexes) - }) - } -} - -func (suite *KeeperTestSuite) TestIterateEarnRewardIndexes() { - suite.SetupApp() - multiIndexes := types.MultiRewardIndexes{ - { - CollateralType: "ukava", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.0000002"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: "usdx", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - }, - }, - } - for _, mi := range multiIndexes { - suite.keeper.SetEarnRewardIndexes(suite.ctx, mi.CollateralType, mi.RewardIndexes) - } - - var actualMultiIndexes types.MultiRewardIndexes - suite.keeper.IterateEarnRewardIndexes(suite.ctx, func(vaultDenom string, i types.RewardIndexes) bool { - actualMultiIndexes = actualMultiIndexes.With(vaultDenom, i) - return false - }) - - suite.Require().Equal(multiIndexes, actualMultiIndexes) -} - -func (suite *KeeperTestSuite) TestGetSetEarnRewardAccrualTimes() { - testCases := []struct { - name string - vaultDenom string - accrualTime time.Time - panics bool - }{ - { - name: "normal time can be written and read", - vaultDenom: "usdx", - accrualTime: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - { - name: "zero time can be written and read", - vaultDenom: "usdx", - accrualTime: time.Time{}, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupApp() - - _, found := suite.keeper.GetEarnRewardAccrualTime(suite.ctx, tc.vaultDenom) - suite.False(found) - - setFunc := func() { suite.keeper.SetEarnRewardAccrualTime(suite.ctx, tc.vaultDenom, tc.accrualTime) } - if tc.panics { - suite.Panics(setFunc) - return - } else { - suite.NotPanics(setFunc) - } - - storedTime, found := suite.keeper.GetEarnRewardAccrualTime(suite.ctx, tc.vaultDenom) - suite.True(found) - suite.Equal(tc.accrualTime, storedTime) - }) - } -} - -type accrualtime struct { - denom string - time time.Time -} - -var nonEmptyAccrualTimes = []accrualtime{ - { - denom: "btcb", - time: time.Date(1998, 1, 1, 0, 0, 0, 1, time.UTC), - }, - { - denom: "ukava", - time: time.Time{}, - }, -} - -func (suite *KeeperTestSuite) TestIterateUSDXMintingAccrualTimes() { - suite.SetupApp() - - expectedAccrualTimes := nonEmptyAccrualTimes - - for _, at := range expectedAccrualTimes { - suite.keeper.SetPreviousUSDXMintingAccrualTime(suite.ctx, at.denom, at.time) - } - - var actualAccrualTimes []accrualtime - suite.keeper.IterateUSDXMintingAccrualTimes(suite.ctx, func(denom string, accrualTime time.Time) bool { - actualAccrualTimes = append(actualAccrualTimes, accrualtime{denom: denom, time: accrualTime}) - return false - }) - - suite.Equal(expectedAccrualTimes, actualAccrualTimes) -} - -func (suite *KeeperTestSuite) TestIterateHardSupplyRewardAccrualTimes() { - suite.SetupApp() - - expectedAccrualTimes := nonEmptyAccrualTimes - - for _, at := range expectedAccrualTimes { - suite.keeper.SetPreviousHardSupplyRewardAccrualTime(suite.ctx, at.denom, at.time) - } - - var actualAccrualTimes []accrualtime - suite.keeper.IterateHardSupplyRewardAccrualTimes(suite.ctx, func(denom string, accrualTime time.Time) bool { - actualAccrualTimes = append(actualAccrualTimes, accrualtime{denom: denom, time: accrualTime}) - return false - }) - - suite.Equal(expectedAccrualTimes, actualAccrualTimes) -} - -func (suite *KeeperTestSuite) TestIterateHardBorrowrRewardAccrualTimes() { - suite.SetupApp() - - expectedAccrualTimes := nonEmptyAccrualTimes - - for _, at := range expectedAccrualTimes { - suite.keeper.SetPreviousHardBorrowRewardAccrualTime(suite.ctx, at.denom, at.time) - } - - var actualAccrualTimes []accrualtime - suite.keeper.IterateHardBorrowRewardAccrualTimes(suite.ctx, func(denom string, accrualTime time.Time) bool { - actualAccrualTimes = append(actualAccrualTimes, accrualtime{denom: denom, time: accrualTime}) - return false - }) - - suite.Equal(expectedAccrualTimes, actualAccrualTimes) -} - -func (suite *KeeperTestSuite) TestIterateDelegatorRewardAccrualTimes() { - suite.SetupApp() - - expectedAccrualTimes := nonEmptyAccrualTimes - - for _, at := range expectedAccrualTimes { - suite.keeper.SetPreviousDelegatorRewardAccrualTime(suite.ctx, at.denom, at.time) - } - - var actualAccrualTimes []accrualtime - suite.keeper.IterateDelegatorRewardAccrualTimes(suite.ctx, func(denom string, accrualTime time.Time) bool { - actualAccrualTimes = append(actualAccrualTimes, accrualtime{denom: denom, time: accrualTime}) - return false - }) - - suite.Equal(expectedAccrualTimes, actualAccrualTimes) -} - -func (suite *KeeperTestSuite) TestIterateSwapRewardAccrualTimes() { - suite.SetupApp() - - expectedAccrualTimes := nonEmptyAccrualTimes - - for _, at := range expectedAccrualTimes { - suite.keeper.SetSwapRewardAccrualTime(suite.ctx, at.denom, at.time) - } - - var actualAccrualTimes []accrualtime - suite.keeper.IterateSwapRewardAccrualTimes(suite.ctx, func(denom string, accrualTime time.Time) bool { - actualAccrualTimes = append(actualAccrualTimes, accrualtime{denom: denom, time: accrualTime}) - return false - }) - - suite.Equal(expectedAccrualTimes, actualAccrualTimes) -} - -func (suite *KeeperTestSuite) TestIterateEarnRewardAccrualTimes() { - suite.SetupApp() - - expectedAccrualTimes := nonEmptyAccrualTimes - - for _, at := range expectedAccrualTimes { - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, at.denom, at.time) - } - - var actualAccrualTimes []accrualtime - suite.keeper.IterateEarnRewardAccrualTimes(suite.ctx, func(denom string, accrualTime time.Time) bool { - actualAccrualTimes = append(actualAccrualTimes, accrualtime{denom: denom, time: accrualTime}) - return false - }) - - suite.Equal(expectedAccrualTimes, actualAccrualTimes) -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} diff --git a/x/incentive/keeper/keeper_utils_test.go b/x/incentive/keeper/keeper_utils_test.go deleted file mode 100644 index 20fc9353..00000000 --- a/x/incentive/keeper/keeper_utils_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package keeper_test - -import ( - "github.com/0glabs/0g-chain/x/incentive/keeper" - "github.com/0glabs/0g-chain/x/incentive/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// TestKeeper is a test wrapper for the keeper which contains useful methods for testing -type TestKeeper struct { - keeper.Keeper -} - -func (keeper TestKeeper) storeGlobalBorrowIndexes(ctx sdk.Context, indexes types.MultiRewardIndexes) { - for _, i := range indexes { - keeper.SetHardBorrowRewardIndexes(ctx, i.CollateralType, i.RewardIndexes) - } -} - -func (keeper TestKeeper) storeGlobalSupplyIndexes(ctx sdk.Context, indexes types.MultiRewardIndexes) { - for _, i := range indexes { - keeper.SetHardSupplyRewardIndexes(ctx, i.CollateralType, i.RewardIndexes) - } -} - -func (keeper TestKeeper) storeGlobalDelegatorIndexes(ctx sdk.Context, multiRewardIndexes types.MultiRewardIndexes) { - // Hardcoded to use bond denom - multiRewardIndex, _ := multiRewardIndexes.GetRewardIndex(types.BondDenom) - keeper.SetDelegatorRewardIndexes(ctx, types.BondDenom, multiRewardIndex.RewardIndexes) -} - -func (keeper TestKeeper) storeGlobalSwapIndexes(ctx sdk.Context, indexes types.MultiRewardIndexes) { - for _, i := range indexes { - keeper.SetSwapRewardIndexes(ctx, i.CollateralType, i.RewardIndexes) - } -} - -func (keeper TestKeeper) storeGlobalSavingsIndexes(ctx sdk.Context, indexes types.MultiRewardIndexes) { - for _, i := range indexes { - keeper.SetSavingsRewardIndexes(ctx, i.CollateralType, i.RewardIndexes) - } -} - -func (keeper TestKeeper) storeGlobalEarnIndexes(ctx sdk.Context, indexes types.MultiRewardIndexes) { - for _, i := range indexes { - keeper.SetEarnRewardIndexes(ctx, i.CollateralType, i.RewardIndexes) - } -} diff --git a/x/incentive/keeper/msg_server.go b/x/incentive/keeper/msg_server.go deleted file mode 100644 index 9a1f18d8..00000000 --- a/x/incentive/keeper/msg_server.go +++ /dev/null @@ -1,117 +0,0 @@ -package keeper - -import ( - "context" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the incentive MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -func (k msgServer) ClaimUSDXMintingReward(goCtx context.Context, msg *types.MsgClaimUSDXMintingReward) (*types.MsgClaimUSDXMintingRewardResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - err = k.keeper.ClaimUSDXMintingReward(ctx, sender, sender, msg.MultiplierName) - if err != nil { - return nil, err - } - - return &types.MsgClaimUSDXMintingRewardResponse{}, nil -} - -func (k msgServer) ClaimHardReward(goCtx context.Context, msg *types.MsgClaimHardReward) (*types.MsgClaimHardRewardResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - for _, selection := range msg.DenomsToClaim { - err := k.keeper.ClaimHardReward(ctx, sender, sender, selection.Denom, selection.MultiplierName) - if err != nil { - return nil, err - } - - } - - return &types.MsgClaimHardRewardResponse{}, nil -} - -func (k msgServer) ClaimDelegatorReward(goCtx context.Context, msg *types.MsgClaimDelegatorReward) (*types.MsgClaimDelegatorRewardResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - for _, selection := range msg.DenomsToClaim { - err := k.keeper.ClaimDelegatorReward(ctx, sender, sender, selection.Denom, selection.MultiplierName) - if err != nil { - return nil, err - } - } - - return &types.MsgClaimDelegatorRewardResponse{}, nil -} - -func (k msgServer) ClaimSwapReward(goCtx context.Context, msg *types.MsgClaimSwapReward) (*types.MsgClaimSwapRewardResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - for _, selection := range msg.DenomsToClaim { - err := k.keeper.ClaimSwapReward(ctx, sender, sender, selection.Denom, selection.MultiplierName) - if err != nil { - return nil, err - } - } - - return &types.MsgClaimSwapRewardResponse{}, nil -} - -func (k msgServer) ClaimSavingsReward(goCtx context.Context, msg *types.MsgClaimSavingsReward) (*types.MsgClaimSavingsRewardResponse, error) { - err := errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "savings claims disabled") - return nil, err -} - -func (k msgServer) ClaimEarnReward(goCtx context.Context, msg *types.MsgClaimEarnReward) (*types.MsgClaimEarnRewardResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - for _, selection := range msg.DenomsToClaim { - err := k.keeper.ClaimEarnReward(ctx, sender, sender, selection.Denom, selection.MultiplierName) - if err != nil { - return nil, err - } - } - - return &types.MsgClaimEarnRewardResponse{}, nil -} diff --git a/x/incentive/keeper/msg_server_delegator_test.go b/x/incentive/keeper/msg_server_delegator_test.go deleted file mode 100644 index 8c3d51f4..00000000 --- a/x/incentive/keeper/msg_server_delegator_test.go +++ /dev/null @@ -1,112 +0,0 @@ -package keeper_test - -import ( - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -func (suite *HandlerTestSuite) TestPayoutDelegatorClaimMultiDenom() { - userAddr := suite.addrs[0] - receiverAddr := suite.addrs[1] - - authBulder := suite.authBuilder(). - WithSimpleAccount(userAddr, cs(c("ukava", 1e12))). - WithSimpleAccount(receiverAddr, nil) - - incentBuilder := suite.incentiveBuilder(). - WithSimpleDelegatorRewardPeriod(types.BondDenom, cs(c("hard", 1e6), c("swap", 1e6))) - - suite.SetupWithGenState(authBulder, incentBuilder) - - // create a delegation (need to create a validator first, which will have a self delegation) - suite.NoError( - suite.DeliverMsgCreateValidator(sdk.ValAddress(userAddr), c("ukava", 1e9)), - ) - - // Delete genesis validator to not influence rewards - suite.App.DeleteGenesisValidator(suite.T(), suite.Ctx) - - // new block required to bond validator - suite.NextBlockAfter(7 * time.Second) - // Now the delegation is bonded, accumulate some delegator rewards - suite.NextBlockAfter(7 * time.Second) - - preClaimBal := suite.GetBalance(userAddr) - - msg := types.NewMsgClaimDelegatorReward( - userAddr.String(), - types.Selections{ - types.NewSelection("hard", "small"), - types.NewSelection("swap", "medium"), - }, - ) - - // Claim denoms - err := suite.DeliverIncentiveMsg(&msg) - suite.Require().NoError(err) - - // Check rewards were paid out - expectedRewardsHard := c("hard", int64(0.2*float64(2*7*1e6))) - expectedRewardsSwap := c("swap", int64(0.5*float64(2*7*1e6))) - suite.BalanceEquals(userAddr, preClaimBal.Add(expectedRewardsHard, expectedRewardsSwap)) - - suite.VestingPeriodsEqual(userAddr, []vestingtypes.Period{ - {Length: (17+31)*secondsPerDay - 2*7, Amount: cs(expectedRewardsHard)}, - {Length: (28 + 31 + 30 + 31 + 30) * secondsPerDay, Amount: cs(expectedRewardsSwap)}, // second length is stacked on top of the first - }) - // Check that claimed coins have been removed from a claim's reward - suite.DelegatorRewardEquals(userAddr, nil) -} - -func (suite *HandlerTestSuite) TestPayoutDelegatorClaimSingleDenom() { - userAddr := suite.addrs[0] - - authBulder := suite.authBuilder(). - WithSimpleAccount(userAddr, cs(c("ukava", 1e12))) - - incentBuilder := suite.incentiveBuilder(). - WithSimpleDelegatorRewardPeriod(types.BondDenom, cs(c("hard", 1e6), c("swap", 1e6))) - - suite.SetupWithGenState(authBulder, incentBuilder) - - // create a delegation (need to create a validator first, which will have a self delegation) - suite.NoError( - suite.DeliverMsgCreateValidator(sdk.ValAddress(userAddr), c("ukava", 1e9)), - ) - - // Delete genesis validator to not influence rewards - suite.App.DeleteGenesisValidator(suite.T(), suite.Ctx) - - // new block required to bond validator - suite.NextBlockAfter(7 * time.Second) - // Now the delegation is bonded, accumulate some delegator rewards - suite.NextBlockAfter(7 * time.Second) - - preClaimBal := suite.GetBalance(userAddr) - - msg := types.NewMsgClaimDelegatorReward( - userAddr.String(), - types.Selections{ - types.NewSelection("swap", "large"), - }, - ) - - // Claim rewards - err := suite.DeliverIncentiveMsg(&msg) - suite.Require().NoError(err) - - // Check rewards were paid out - expectedRewards := c("swap", 2*7*1e6) - suite.BalanceEquals(userAddr, preClaimBal.Add(expectedRewards)) - - suite.VestingPeriodsEqual(userAddr, []vestingtypes.Period{ - {Length: (17+31+28+31+30+31+30+31+31+30+31+30+31)*secondsPerDay - 2*7, Amount: cs(expectedRewards)}, - }) - - // Check that claimed coins have been removed from a claim's reward - suite.DelegatorRewardEquals(userAddr, cs(c("hard", 2*7*1e6))) -} diff --git a/x/incentive/keeper/msg_server_earn_test.go b/x/incentive/keeper/msg_server_earn_test.go deleted file mode 100644 index 7becfa63..00000000 --- a/x/incentive/keeper/msg_server_earn_test.go +++ /dev/null @@ -1,239 +0,0 @@ -package keeper_test - -import ( - "time" - - abci "github.com/cometbft/cometbft/abci/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - earntypes "github.com/0glabs/0g-chain/x/earn/types" - "github.com/0glabs/0g-chain/x/incentive" - "github.com/0glabs/0g-chain/x/incentive/testutil" - "github.com/0glabs/0g-chain/x/incentive/types" - liquidtypes "github.com/0glabs/0g-chain/x/liquid/types" - "github.com/cosmos/cosmos-sdk/x/distribution" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/cosmos/cosmos-sdk/x/mint" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" -) - -func (suite *HandlerTestSuite) TestEarnLiquidClaim() { - userAddr1, userAddr2, validatorAddr1, validatorAddr2 := suite.addrs[0], suite.addrs[1], suite.addrs[2], suite.addrs[3] - - valAddr1 := sdk.ValAddress(validatorAddr1) - valAddr2 := sdk.ValAddress(validatorAddr2) - - authBuilder := suite.authBuilder(). - WithSimpleAccount(userAddr1, cs(c("ukava", 1e12))). - WithSimpleAccount(userAddr2, cs(c("ukava", 1e12))). - WithSimpleAccount(validatorAddr1, cs(c("ukava", 1e12))). - WithSimpleAccount(validatorAddr2, cs(c("ukava", 1e12))) - - incentBuilder := suite.incentiveBuilder(). - WithSimpleEarnRewardPeriod("bkava", cs()) - - savingsBuilder := testutil.NewSavingsGenesisBuilder(). - WithSupportedDenoms("bkava") - - earnBuilder := testutil.NewEarnGenesisBuilder(). - WithAllowedVaults(earntypes.AllowedVault{ - Denom: "bkava", - Strategies: earntypes.StrategyTypes{earntypes.STRATEGY_TYPE_SAVINGS}, - IsPrivateVault: false, - AllowedDepositors: nil, - }) - - suite.SetupWithGenState( - authBuilder, - incentBuilder, - earnBuilder, - savingsBuilder, - ) - - // ak := suite.App.GetAccountKeeper() - // bk := suite.App.GetBankKeeper() - sk := suite.App.GetStakingKeeper() - lq := suite.App.GetLiquidKeeper() - mk := suite.App.GetMintKeeper() - dk := suite.App.GetDistrKeeper() - ik := suite.App.GetIncentiveKeeper() - - iParams := ik.GetParams(suite.Ctx) - period, found := iParams.EarnRewardPeriods.GetMultiRewardPeriod("bkava") - suite.Require().True(found) - suite.Require().Equal("bkava", period.CollateralType) - - // Use ukava for mint denom - mParams := mk.GetParams(suite.Ctx) - mParams.MintDenom = "ukava" - mk.SetParams(suite.Ctx, mParams) - - bkavaDenom1 := lq.GetLiquidStakingTokenDenom(valAddr1) - bkavaDenom2 := lq.GetLiquidStakingTokenDenom(valAddr2) - - err := suite.App.FundModuleAccount(suite.Ctx, distrtypes.ModuleName, cs(c("ukava", 1e12))) - suite.NoError(err) - - // Create validators - err = suite.DeliverMsgCreateValidator(valAddr1, c("ukava", 1e9)) - suite.Require().NoError(err) - - err = suite.DeliverMsgCreateValidator(valAddr2, c("ukava", 1e9)) - suite.Require().NoError(err) - - // new block required to bond validator - suite.NextBlockAfter(7 * time.Second) - // Now the delegation is bonded, accumulate some delegator rewards - suite.NextBlockAfter(7 * time.Second) - - // Create delegations from users - // User 1: 1e9 ukava to validator 1 - // User 2: 99e9 ukava to validator 1 AND 2 - err = suite.DeliverMsgDelegate(userAddr1, valAddr1, c("ukava", 1e9)) - suite.Require().NoError(err) - - err = suite.DeliverMsgDelegate(userAddr2, valAddr1, c("ukava", 99e9)) - suite.Require().NoError(err) - - err = suite.DeliverMsgDelegate(userAddr2, valAddr2, c("ukava", 99e9)) - suite.Require().NoError(err) - - // Mint liquid tokens - _, err = suite.DeliverMsgMintDerivative(userAddr1, valAddr1, c("ukava", 1e9)) - suite.Require().NoError(err) - - _, err = suite.DeliverMsgMintDerivative(userAddr2, valAddr1, c("ukava", 99e9)) - suite.Require().NoError(err) - - _, err = suite.DeliverMsgMintDerivative(userAddr2, valAddr2, c("ukava", 99e9)) - suite.Require().NoError(err) - - // Deposit liquid tokens to earn - err = suite.DeliverEarnMsgDeposit(userAddr1, c(bkavaDenom1, 1e9), earntypes.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - err = suite.DeliverEarnMsgDeposit(userAddr2, c(bkavaDenom1, 99e9), earntypes.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - err = suite.DeliverEarnMsgDeposit(userAddr2, c(bkavaDenom2, 99e9), earntypes.STRATEGY_TYPE_SAVINGS) - suite.Require().NoError(err) - - // BeginBlocker to update minter annual provisions as it starts at 0 which results in no minted coins - _ = suite.App.BeginBlocker(suite.Ctx, abci.RequestBeginBlock{}) - - // DeliverMsgCreateValidator uses a generated pubkey, so we need to fetch - // the validator to get the correct pubkey - validator1, found := sk.GetValidator(suite.Ctx, valAddr1) - suite.Require().True(found) - - pk, err := validator1.ConsPubKey() - suite.Require().NoError(err) - - val := abci.Validator{ - Address: pk.Address(), - Power: 100, - } - - // Query for next block to get staking rewards - suite.Ctx = suite.Ctx. - WithBlockHeight(suite.Ctx.BlockHeight() + 1). - WithBlockTime(suite.Ctx.BlockTime().Add(7 * time.Second)) - - // Mint tokens - mint.BeginBlocker( - suite.Ctx, - suite.App.GetMintKeeper(), - minttypes.DefaultInflationCalculationFn, - ) - // Distribute to validators, block needs votes - distribution.BeginBlocker( - suite.Ctx, - abci.RequestBeginBlock{ - LastCommitInfo: abci.CommitInfo{ - Votes: []abci.VoteInfo{{ - Validator: val, - SignedLastBlock: true, - }}, - }, - }, - dk, - ) - - liquidMacc := suite.App.GetAccountKeeper().GetModuleAccount(suite.Ctx, liquidtypes.ModuleAccountName) - delegation, found := sk.GetDelegation(suite.Ctx, liquidMacc.GetAddress(), valAddr1) - suite.Require().True(found) - - // Get amount of rewards - endingPeriod := dk.IncrementValidatorPeriod(suite.Ctx, validator1) - - // Zero rewards since this block is the same as the block it was last claimed - - // This needs to run **after** staking rewards are minted/distributed in - // x/mint + x/distribution but **before** the x/incentive BeginBlocker. - - // Order of operations: - // 1. x/mint + x/distribution BeginBlocker - // 2. CalculateDelegationRewards - // 3. x/incentive BeginBlocker to claim staking rewards - delegationRewards := dk.CalculateDelegationRewards(suite.Ctx, validator1, delegation, endingPeriod) - suite.Require().False(delegationRewards.IsZero(), "expected non-zero delegation rewards") - - // Claim staking rewards via incentive. - // Block height was updated earlier. - incentive.BeginBlocker( - suite.Ctx, - ik, - ) - - preClaimBal1 := suite.GetBalance(userAddr1) - preClaimBal2 := suite.GetBalance(userAddr2) - - // Claim ukava staking rewards - denomsToClaim := map[string]string{"ukava": "large"} - selections := types.NewSelectionsFromMap(denomsToClaim) - - msg1 := types.NewMsgClaimEarnReward(userAddr1.String(), selections) - msg2 := types.NewMsgClaimEarnReward(userAddr2.String(), selections) - - err = suite.DeliverIncentiveMsg(&msg1) - suite.Require().NoError(err) - - err = suite.DeliverIncentiveMsg(&msg2) - suite.Require().NoError(err) - - // Check rewards were paid out - // User 1 gets 1% of rewards - // User 2 gets 99% of rewards - stakingRewards1 := delegationRewards. - AmountOf("ukava"). - Quo(sdk.NewDec(100)). - RoundInt() - suite.BalanceEquals(userAddr1, preClaimBal1.Add(sdk.NewCoin("ukava", stakingRewards1))) - - // Total * 99 / 100 - stakingRewards2 := delegationRewards. - AmountOf("ukava"). - Mul(sdk.NewDec(99)). - Quo(sdk.NewDec(100)). - RoundInt() - - suite.BalanceInEpsilon( - userAddr2, - preClaimBal2.Add(sdk.NewCoin("ukava", stakingRewards2)), - // Highest precision to allow 1ukava margin of error - // 820778117815 vs 820778117814 - 1e-11, - ) - - suite.InEpsilonf( - delegationRewards.AmountOf("ukava").RoundInt().Int64(), - stakingRewards1.Add(stakingRewards2).Int64(), - 1e-11, - "expected rewards should add up to staking rewards within a margin of error (%v vs %v)", - delegationRewards.AmountOf("ukava").RoundInt().Int64(), - stakingRewards1.Add(stakingRewards2).Int64(), - ) - - // Check that claimed coins have been removed from a claim's reward - suite.EarnRewardEquals(userAddr1, cs()) - suite.EarnRewardEquals(userAddr2, cs()) -} diff --git a/x/incentive/keeper/msg_server_hard_test.go b/x/incentive/keeper/msg_server_hard_test.go deleted file mode 100644 index f7720bb8..00000000 --- a/x/incentive/keeper/msg_server_hard_test.go +++ /dev/null @@ -1,100 +0,0 @@ -package keeper_test - -import ( - "time" - - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -func (suite *HandlerTestSuite) TestPayoutHardClaimMultiDenom() { - userAddr, receiverAddr := suite.addrs[0], suite.addrs[1] - - authBulder := suite.authBuilder(). - WithSimpleAccount(userAddr, cs(c("bnb", 1e12))). - WithSimpleAccount(receiverAddr, nil) - - incentBuilder := suite.incentiveBuilder(). - WithSimpleSupplyRewardPeriod("bnb", cs(c("hard", 1e6), c("swap", 1e6))). - WithSimpleBorrowRewardPeriod("bnb", cs(c("hard", 1e6), c("swap", 1e6))) - - suite.SetupWithGenState(authBulder, incentBuilder) - - // create a deposit and borrow - suite.NoError(suite.DeliverHardMsgDeposit(userAddr, cs(c("bnb", 1e11)))) - suite.NoError(suite.DeliverHardMsgBorrow(userAddr, cs(c("bnb", 1e10)))) - - // accumulate some rewards - suite.NextBlockAfter(7 * time.Second) - - preClaimBal := suite.GetBalance(userAddr) - - msg := types.NewMsgClaimHardReward( - userAddr.String(), - types.Selections{ - types.NewSelection("hard", "small"), - types.NewSelection("swap", "medium"), - }, - ) - - // Claim denoms - err := suite.DeliverIncentiveMsg(&msg) - suite.Require().NoError(err) - - // Check rewards were paid out - expectedRewardsHard := c("hard", int64(0.2*float64(2*7*1e6))) - expectedRewardsSwap := c("swap", int64(0.5*float64(2*7*1e6))) - suite.BalanceEquals(userAddr, preClaimBal.Add(expectedRewardsHard, expectedRewardsSwap)) - - suite.VestingPeriodsEqual(userAddr, []vestingtypes.Period{ - {Length: (17+31)*secondsPerDay - 7, Amount: cs(expectedRewardsHard)}, - {Length: (28 + 31 + 30 + 31 + 30) * secondsPerDay, Amount: cs(expectedRewardsSwap)}, // second length is stacked on top of the first - }) - // Check that claimed coins have been removed from a claim's reward - suite.HardRewardEquals(userAddr, nil) -} - -func (suite *HandlerTestSuite) TestPayoutHardClaimSingleDenom() { - userAddr := suite.addrs[0] - - authBulder := suite.authBuilder(). - WithSimpleAccount(userAddr, cs(c("bnb", 1e12))) - - incentBuilder := suite.incentiveBuilder(). - WithSimpleSupplyRewardPeriod("bnb", cs(c("hard", 1e6), c("swap", 1e6))). - WithSimpleBorrowRewardPeriod("bnb", cs(c("hard", 1e6), c("swap", 1e6))) - - suite.SetupWithGenState(authBulder, incentBuilder) - - // create a deposit and borrow - suite.NoError(suite.DeliverHardMsgDeposit(userAddr, cs(c("bnb", 1e11)))) - suite.NoError(suite.DeliverHardMsgBorrow(userAddr, cs(c("bnb", 1e10)))) - - // accumulate some rewards - suite.NextBlockAfter(7 * time.Second) - - preClaimBal := suite.GetBalance(userAddr) - - msg := types.NewMsgClaimHardReward( - userAddr.String(), - types.Selections{ - types.NewSelection("swap", "large"), - }, - ) - - // Claim rewards - err := suite.DeliverIncentiveMsg(&msg) - suite.Require().NoError(err) - - // Check rewards were paid out - expectedRewards := c("swap", 2*7*1e6) - suite.BalanceEquals(userAddr, preClaimBal.Add(expectedRewards)) - - suite.VestingPeriodsEqual(userAddr, []vestingtypes.Period{ - {Length: (17+31+28+31+30+31+30+31+31+30+31+30+31)*secondsPerDay - 7, Amount: cs(expectedRewards)}, - }) - - // Check that claimed coins have been removed from a claim's reward - suite.HardRewardEquals(userAddr, cs(c("hard", 2*7*1e6))) -} diff --git a/x/incentive/keeper/msg_server_swap_test.go b/x/incentive/keeper/msg_server_swap_test.go deleted file mode 100644 index 1c73a6aa..00000000 --- a/x/incentive/keeper/msg_server_swap_test.go +++ /dev/null @@ -1,191 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/incentive/testutil" - "github.com/0glabs/0g-chain/x/incentive/types" - kavadisttypes "github.com/0glabs/0g-chain/x/kavadist/types" -) - -const secondsPerDay = 24 * 60 * 60 - -// Test suite used for all keeper tests -type HandlerTestSuite struct { - testutil.IntegrationTester - - genesisTime time.Time - addrs []sdk.AccAddress -} - -func TestHandlerTestSuite(t *testing.T) { - suite.Run(t, new(HandlerTestSuite)) -} - -// SetupTest is run automatically before each suite test -func (suite *HandlerTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - _, suite.addrs = app.GeneratePrivKeyAddressPairs(5) - - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *HandlerTestSuite) SetupApp() { - suite.App = app.NewTestApp() - - suite.Ctx = suite.App.NewContext(true, tmproto.Header{Height: 1, Time: suite.genesisTime}) -} - -func (suite *HandlerTestSuite) SetupWithGenState(builders ...testutil.GenesisBuilder) { - suite.SetupApp() - - builtGenStates := []app.GenesisState{ - NewStakingGenesisState(suite.App.AppCodec()), - NewPricefeedGenStateMultiFromTime(suite.App.AppCodec(), suite.genesisTime), - NewCDPGenStateMulti(suite.App.AppCodec()), - NewHardGenStateMulti(suite.genesisTime).BuildMarshalled(suite.App.AppCodec()), - NewSwapGenesisState(suite.App.AppCodec()), - } - for _, builder := range builders { - builtGenStates = append(builtGenStates, builder.BuildMarshalled(suite.App.AppCodec())) - } - - suite.App.InitializeFromGenesisStatesWithTime( - suite.genesisTime, - builtGenStates..., - ) -} - -// authBuilder returns a new auth genesis builder with a full kavadist module account. -func (suite *HandlerTestSuite) authBuilder() *app.AuthBankGenesisBuilder { - return app.NewAuthBankGenesisBuilder(). - WithSimpleModuleAccount(kavadisttypes.ModuleName, cs(c(types.USDXMintingRewardDenom, 1e18), c("hard", 1e18), c("swap", 1e18))) -} - -// incentiveBuilder returns a new incentive genesis builder with a genesis time and multipliers set -func (suite *HandlerTestSuite) incentiveBuilder() testutil.IncentiveGenesisBuilder { - return testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithMultipliers(types.MultipliersPerDenoms{ - { - Denom: "hard", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.2")), - types.NewMultiplier("large", 12, d("1.0")), - }, - }, - { - Denom: "swap", - Multipliers: types.Multipliers{ - types.NewMultiplier("medium", 6, d("0.5")), - types.NewMultiplier("large", 12, d("1.0")), - }, - }, - { - Denom: "ukava", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, d("0.2")), - types.NewMultiplier("large", 12, d("1.0")), - }, - }, - }) -} - -func (suite *HandlerTestSuite) TestPayoutSwapClaimMultiDenom() { - userAddr := suite.addrs[0] - - authBulder := suite.authBuilder(). - WithSimpleAccount(userAddr, cs(c("ukava", 1e12), c("busd", 1e12))) - - incentBuilder := suite.incentiveBuilder(). - WithSimpleSwapRewardPeriod("busd:ukava", cs(c("hard", 1e6), c("swap", 1e6))) - - suite.SetupWithGenState(authBulder, incentBuilder) - - // deposit into a swap pool - suite.NoError( - suite.DeliverSwapMsgDeposit(userAddr, c("ukava", 1e9), c("busd", 1e9), d("1.0")), - ) - // accumulate some swap rewards - suite.NextBlockAfter(7 * time.Second) - - preClaimBal := suite.GetBalance(userAddr) - - msg := types.NewMsgClaimSwapReward( - userAddr.String(), - types.Selections{ - types.NewSelection("hard", "small"), - types.NewSelection("swap", "medium"), - }, - ) - - // Claim rewards - err := suite.DeliverIncentiveMsg(&msg) - suite.Require().NoError(err) - - // Check rewards were paid out - expectedRewardsHard := c("hard", int64(0.2*float64(7*1e6))) - expectedRewardsSwap := c("swap", int64(0.5*float64(7*1e6))) - suite.BalanceEquals(userAddr, preClaimBal.Add(expectedRewardsHard, expectedRewardsSwap)) - - suite.VestingPeriodsEqual(userAddr, []vestingtypes.Period{ - {Length: (17+31)*secondsPerDay - 7, Amount: cs(expectedRewardsHard)}, - {Length: (28 + 31 + 30 + 31 + 30) * secondsPerDay, Amount: cs(expectedRewardsSwap)}, // second length is stacked on top of the first - }) - - // Check that each claim reward coin's amount has been reset to 0 - suite.SwapRewardEquals(userAddr, nil) -} - -func (suite *HandlerTestSuite) TestPayoutSwapClaimSingleDenom() { - userAddr := suite.addrs[0] - - authBulder := suite.authBuilder(). - WithSimpleAccount(userAddr, cs(c("ukava", 1e12), c("busd", 1e12))) - - incentBuilder := suite.incentiveBuilder(). - WithSimpleSwapRewardPeriod("busd:ukava", cs(c("hard", 1e6), c("swap", 1e6))) - - suite.SetupWithGenState(authBulder, incentBuilder) - - // deposit into a swap pool - suite.NoError( - suite.DeliverSwapMsgDeposit(userAddr, c("ukava", 1e9), c("busd", 1e9), d("1.0")), - ) - - // accumulate some swap rewards - suite.NextBlockAfter(7 * time.Second) - - preClaimBal := suite.GetBalance(userAddr) - - msg := types.NewMsgClaimSwapReward( - userAddr.String(), - types.Selections{ - types.NewSelection("swap", "large"), - }, - ) - - // Claim rewards - err := suite.DeliverIncentiveMsg(&msg) - suite.Require().NoError(err) - - // Check rewards were paid out - expectedRewards := c("swap", 7*1e6) - suite.BalanceEquals(userAddr, preClaimBal.Add(expectedRewards)) - - suite.VestingPeriodsEqual(userAddr, vestingtypes.Periods{ - {Length: (17+31+28+31+30+31+30+31+31+30+31+30+31)*secondsPerDay - 7, Amount: cs(expectedRewards)}, - }) - - // Check that claimed coins have been removed from a claim's reward - suite.SwapRewardEquals(userAddr, cs(c("hard", 7*1e6))) -} diff --git a/x/incentive/keeper/msg_server_usdx_test.go b/x/incentive/keeper/msg_server_usdx_test.go deleted file mode 100644 index 8d299295..00000000 --- a/x/incentive/keeper/msg_server_usdx_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package keeper_test - -import ( - "time" - - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -func (suite *HandlerTestSuite) TestPayoutUSDXClaim() { - userAddr, receiverAddr := suite.addrs[0], suite.addrs[1] - - authBulder := suite.authBuilder(). - WithSimpleAccount(userAddr, cs(c("bnb", 1e12))). - WithSimpleAccount(receiverAddr, nil) - - incentBuilder := suite.incentiveBuilder(). - WithSimpleUSDXRewardPeriod("bnb-a", c(types.USDXMintingRewardDenom, 1e6)) - - suite.SetupWithGenState(authBulder, incentBuilder) - - // mint some usdx - err := suite.DeliverMsgCreateCDP(userAddr, c("bnb", 1e9), c("usdx", 1e7), "bnb-a") - suite.NoError(err) - // accumulate some rewards - suite.NextBlockAfter(7 * time.Second) - - preClaimBal := suite.GetBalance(userAddr) - - msg := types.NewMsgClaimUSDXMintingReward(userAddr.String(), "large") - - // Claim a single denom - err = suite.DeliverIncentiveMsg(&msg) - suite.Require().NoError(err) - - // Check rewards were paid out - expectedRewards := cs(c(types.USDXMintingRewardDenom, 7*1e6)) - suite.BalanceEquals(userAddr, preClaimBal.Add(expectedRewards...)) - - suite.VestingPeriodsEqual(userAddr, []vestingtypes.Period{ - {Length: (17+31+28+31+30+31+30+31+31+30+31+30+31)*secondsPerDay - 7, Amount: expectedRewards}, - }) - // Check that claimed coins have been removed from a claim's reward - suite.USDXRewardEquals(userAddr, c(types.USDXMintingRewardDenom, 0)) -} diff --git a/x/incentive/keeper/params.go b/x/incentive/keeper/params.go deleted file mode 100644 index b8b89c93..00000000 --- a/x/incentive/keeper/params.go +++ /dev/null @@ -1,95 +0,0 @@ -package keeper - -import ( - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// GetParams returns the params from the store -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - var p types.Params - k.paramSubspace.GetParamSet(ctx, &p) - return p -} - -// SetParams sets params on the store -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSubspace.SetParamSet(ctx, ¶ms) -} - -// GetUSDXMintingRewardPeriod returns the reward period with the specified collateral type if it's found in the params -func (k Keeper) GetUSDXMintingRewardPeriod(ctx sdk.Context, collateralType string) (types.RewardPeriod, bool) { - params := k.GetParams(ctx) - for _, rp := range params.USDXMintingRewardPeriods { - if rp.CollateralType == collateralType { - return rp, true - } - } - return types.RewardPeriod{}, false -} - -// GetHardSupplyRewardPeriods returns the reward period with the specified collateral type if it's found in the params -func (k Keeper) GetHardSupplyRewardPeriods(ctx sdk.Context, denom string) (types.MultiRewardPeriod, bool) { - params := k.GetParams(ctx) - for _, rp := range params.HardSupplyRewardPeriods { - if rp.CollateralType == denom { - return rp, true - } - } - return types.MultiRewardPeriod{}, false -} - -// GetHardBorrowRewardPeriods returns the reward period with the specified collateral type if it's found in the params -func (k Keeper) GetHardBorrowRewardPeriods(ctx sdk.Context, denom string) (types.MultiRewardPeriod, bool) { - params := k.GetParams(ctx) - for _, rp := range params.HardBorrowRewardPeriods { - if rp.CollateralType == denom { - return rp, true - } - } - return types.MultiRewardPeriod{}, false -} - -// GetDelegatorRewardPeriods returns the reward period with the specified collateral type if it's found in the params -func (k Keeper) GetDelegatorRewardPeriods(ctx sdk.Context, denom string) (types.MultiRewardPeriod, bool) { - params := k.GetParams(ctx) - for _, rp := range params.DelegatorRewardPeriods { - if rp.CollateralType == denom { - return rp, true - } - } - return types.MultiRewardPeriod{}, false -} - -// GetSavingsRewardPeriods returns the reward period with the specified collateral type if it's found in the params -func (k Keeper) GetSavingsRewardPeriods(ctx sdk.Context, denom string) (types.MultiRewardPeriod, bool) { - params := k.GetParams(ctx) - for _, rp := range params.SavingsRewardPeriods { - if rp.CollateralType == denom { - return rp, true - } - } - return types.MultiRewardPeriod{}, false -} - -// GetMultiplierByDenom fetches a multiplier from the params matching the denom and name. -func (k Keeper) GetMultiplierByDenom(ctx sdk.Context, denom string, name string) (types.Multiplier, bool) { - params := k.GetParams(ctx) - - for _, dm := range params.ClaimMultipliers { - if dm.Denom == denom { - m, found := dm.Multipliers.Get(name) - return m, found - } - } - return types.Multiplier{}, false -} - -// GetClaimEnd returns the claim end time for the params -func (k Keeper) GetClaimEnd(ctx sdk.Context) time.Time { - params := k.GetParams(ctx) - return params.ClaimEnd -} diff --git a/x/incentive/keeper/payout.go b/x/incentive/keeper/payout.go deleted file mode 100644 index e7c0d0b9..00000000 --- a/x/incentive/keeper/payout.go +++ /dev/null @@ -1,198 +0,0 @@ -package keeper - -import ( - "time" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - - "github.com/0glabs/0g-chain/x/incentive/types" - // validatorvesting "github.com/0glabs/0g-chain/x/validator-vesting" -) - -const ( - // BeginningOfMonth harvest rewards that are claimed after the 15th at 14:00UTC of the month always vest on the first of the month - BeginningOfMonth = 1 - // MidMonth harvest rewards that are claimed before the 15th at 14:00UTC of the month always vest on the 15 of the month - MidMonth = 15 - // PaymentHour harvest rewards always vest at 14:00UTC - PaymentHour = 14 -) - -// SendTimeLockedCoinsToAccount sends time-locked coins from the input module account to the recipient. If the recipients account is not a vesting account and the input length is greater than zero, the recipient account is converted to a periodic vesting account and the coins are added to the vesting balance as a vesting period with the input length. -func (k Keeper) SendTimeLockedCoinsToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins, length int64) error { - macc := k.accountKeeper.GetModuleAccount(ctx, senderModule) - maccCoins := k.bankKeeper.GetAllBalances(ctx, macc.GetAddress()) - if !maccCoins.IsAllGTE(amt) { - return errorsmod.Wrapf(types.ErrInsufficientModAccountBalance, "%s", senderModule) - } - - // 0. Get the account from the account keeper and do a type switch, error if it's a validator vesting account or module account (can make this work for validator vesting later if necessary) - acc := k.accountKeeper.GetAccount(ctx, recipientAddr) - if acc == nil { - return errorsmod.Wrapf(types.ErrAccountNotFound, recipientAddr.String()) - } - if length == 0 { - return k.bankKeeper.SendCoinsFromModuleToAccount(ctx, senderModule, recipientAddr, amt) - } - - switch acc.(type) { - case *vestingtypes.ContinuousVestingAccount, authtypes.ModuleAccountI: - return errorsmod.Wrapf(types.ErrInvalidAccountType, "%T", acc) - case *vestingtypes.PeriodicVestingAccount: - return k.SendTimeLockedCoinsToPeriodicVestingAccount(ctx, senderModule, recipientAddr, amt, length) - case *authtypes.BaseAccount: - return k.SendTimeLockedCoinsToBaseAccount(ctx, senderModule, recipientAddr, amt, length) - default: - return errorsmod.Wrapf(types.ErrInvalidAccountType, "%T", acc) - } -} - -// SendTimeLockedCoinsToPeriodicVestingAccount sends time-locked coins from the input module account to the recipient -func (k Keeper) SendTimeLockedCoinsToPeriodicVestingAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins, length int64) error { - err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, senderModule, recipientAddr, amt) - if err != nil { - return err - } - k.addCoinsToVestingSchedule(ctx, recipientAddr, amt, length) - return nil -} - -// SendTimeLockedCoinsToBaseAccount sends time-locked coins from the input module account to the recipient, converting the recipient account to a vesting account -func (k Keeper) SendTimeLockedCoinsToBaseAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins, length int64) error { - err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, senderModule, recipientAddr, amt) - if err != nil { - return err - } - acc := k.accountKeeper.GetAccount(ctx, recipientAddr) - // transition the account to a periodic vesting account: - bacc := authtypes.NewBaseAccount(acc.GetAddress(), acc.GetPubKey(), acc.GetAccountNumber(), acc.GetSequence()) - - newPeriods := vestingtypes.Periods{types.NewPeriod(amt, length)} - bva := vestingtypes.NewBaseVestingAccount(bacc, amt, ctx.BlockTime().Unix()+length) - pva := vestingtypes.NewPeriodicVestingAccountRaw(bva, ctx.BlockTime().Unix(), newPeriods) - k.accountKeeper.SetAccount(ctx, pva) - - return nil -} - -// GetPeriodLength returns the length of the lockup period based on the input blocktime and multiplier lockup. -// Note that pay dates are always the 1st or 15th of the month at 14:00UTC. -// Months lockup cannot be negative -func (k Keeper) GetPeriodLength(blockTime time.Time, monthsLockup int64) int64 { - if monthsLockup < 0 { - panic("months lockup must be non negative") - } - if monthsLockup == 0 { - return 0 - } - currentDay := blockTime.Day() - payDay := BeginningOfMonth - monthOffset := int64(1) - if currentDay < MidMonth || (currentDay == MidMonth && blockTime.Hour() < PaymentHour) { - payDay = MidMonth - monthOffset = int64(0) - } - periodEndDate := time.Date(blockTime.Year(), blockTime.Month(), payDay, PaymentHour, 0, 0, 0, time.UTC).AddDate(0, int(monthsLockup+monthOffset), 0) - return periodEndDate.Unix() - blockTime.Unix() -} - -// addCoinsToVestingSchedule adds coins to the input account's vesting schedule where length is the amount of time (from the current block time), in seconds, that the coins will be vesting for -// the input address must be a periodic vesting account -func (k Keeper) addCoinsToVestingSchedule(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins, length int64) { - acc := k.accountKeeper.GetAccount(ctx, addr) - vacc := acc.(*vestingtypes.PeriodicVestingAccount) - // Add the new vesting coins to OriginalVesting - vacc.OriginalVesting = vacc.OriginalVesting.Add(amt...) - // update vesting periods - // EndTime = 100 - // BlockTime = 110 - // length == 6 - if vacc.EndTime < ctx.BlockTime().Unix() { - // edge case one - the vesting account's end time is in the past (ie, all previous vesting periods have completed) - // append a new period to the vesting account, update the end time, update the account in the store and return - newPeriodLength := (ctx.BlockTime().Unix() - vacc.EndTime) + length // 110 - 100 + 6 = 16 - newPeriod := types.NewPeriod(amt, newPeriodLength) - vacc.VestingPeriods = append(vacc.VestingPeriods, newPeriod) - vacc.EndTime = ctx.BlockTime().Unix() + length - k.accountKeeper.SetAccount(ctx, vacc) - return - } - // StartTime = 110 - // BlockTime = 100 - // length = 6 - if vacc.StartTime > ctx.BlockTime().Unix() { - // edge case two - the vesting account's start time is in the future (all periods have not started) - // update the start time to now and adjust the period lengths in place - a new period will be inserted in the next code block - updatedPeriods := vestingtypes.Periods{} - for i, period := range vacc.VestingPeriods { - updatedPeriod := period - if i == 0 { - updatedPeriod = types.NewPeriod(period.Amount, (vacc.StartTime-ctx.BlockTime().Unix())+period.Length) // 110 - 100 + 6 = 16 - } - updatedPeriods = append(updatedPeriods, updatedPeriod) - } - vacc.VestingPeriods = updatedPeriods - vacc.StartTime = ctx.BlockTime().Unix() - } - - // logic for inserting a new vesting period into the existing vesting schedule - remainingLength := vacc.EndTime - ctx.BlockTime().Unix() - elapsedTime := ctx.BlockTime().Unix() - vacc.StartTime - proposedEndTime := ctx.BlockTime().Unix() + length - if remainingLength < length { - // in the case that the proposed length is longer than the remaining length of all vesting periods, create a new period with length equal to the difference between the proposed length and the previous total length - newPeriodLength := length - remainingLength - newPeriod := types.NewPeriod(amt, newPeriodLength) - vacc.VestingPeriods = append(vacc.VestingPeriods, newPeriod) - // update the end time so that the sum of all period lengths equals endTime - startTime - vacc.EndTime = proposedEndTime - } else { - // In the case that the proposed length is less than or equal to the sum of all previous period lengths, insert the period and update other periods as necessary. - // EXAMPLE (l is length, a is amount) - // Original Periods: {[l: 1 a: 1], [l: 2, a: 1], [l:8, a:3], [l: 5, a: 3]} - // Period we want to insert [l: 5, a: x] - // Expected result: - // {[l: 1, a: 1], [l:2, a: 1], [l:2, a:x], [l:6, a:3], [l:5, a:3]} - - // StartTime = 100 - // Periods = [5,5,5,5] - // EndTime = 120 - // BlockTime = 101 - // length = 2 - - // for period in Periods: - // iteration 1: - // lengthCounter = 5 - // if 5 < 101 - 100 + 2 - no - // if 5 = 3 - no - // else - // newperiod = 2 - 0 - newPeriods := vestingtypes.Periods{} - lengthCounter := int64(0) - appendRemaining := false - for _, period := range vacc.VestingPeriods { - if appendRemaining { - newPeriods = append(newPeriods, period) - continue - } - lengthCounter += period.Length - if lengthCounter < elapsedTime+length { // 1 - newPeriods = append(newPeriods, period) - } else if lengthCounter == elapsedTime+length { - newPeriod := types.NewPeriod(period.Amount.Add(amt...), period.Length) - newPeriods = append(newPeriods, newPeriod) - appendRemaining = true - } else { - newPeriod := types.NewPeriod(amt, elapsedTime+length-types.GetTotalVestingPeriodLength(newPeriods)) - previousPeriod := types.NewPeriod(period.Amount, period.Length-newPeriod.Length) - newPeriods = append(newPeriods, newPeriod, previousPeriod) - appendRemaining = true - } - } - vacc.VestingPeriods = newPeriods - } - k.accountKeeper.SetAccount(ctx, vacc) -} diff --git a/x/incentive/keeper/payout_test.go b/x/incentive/keeper/payout_test.go deleted file mode 100644 index a88c9ac4..00000000 --- a/x/incentive/keeper/payout_test.go +++ /dev/null @@ -1,522 +0,0 @@ -package keeper_test - -import ( - "strings" - "testing" - "time" - - "github.com/stretchr/testify/suite" - - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - - "github.com/0glabs/0g-chain/app" - cdpkeeper "github.com/0glabs/0g-chain/x/cdp/keeper" - cdptypes "github.com/0glabs/0g-chain/x/cdp/types" - hardkeeper "github.com/0glabs/0g-chain/x/hard/keeper" - "github.com/0glabs/0g-chain/x/incentive/keeper" - "github.com/0glabs/0g-chain/x/incentive/testutil" - "github.com/0glabs/0g-chain/x/incentive/types" - kavadisttypes "github.com/0glabs/0g-chain/x/kavadist/types" -) - -// Test suite used for all keeper tests -type PayoutTestSuite struct { - suite.Suite - - keeper keeper.Keeper - hardKeeper hardkeeper.Keeper - cdpKeeper cdpkeeper.Keeper - - app app.TestApp - ctx sdk.Context - - genesisTime time.Time - addrs []sdk.AccAddress -} - -// SetupTest is run automatically before each suite test -func (suite *PayoutTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - _, suite.addrs = app.GeneratePrivKeyAddressPairs(5) - - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *PayoutTestSuite) SetupApp() { - suite.app = app.NewTestApp() - - suite.keeper = suite.app.GetIncentiveKeeper() - suite.hardKeeper = suite.app.GetHardKeeper() - suite.cdpKeeper = suite.app.GetCDPKeeper() - - suite.ctx = suite.app.NewContext(true, tmprototypes.Header{Time: suite.genesisTime}) -} - -func (suite *PayoutTestSuite) SetupWithGenState(authBuilder app.AuthBankGenesisBuilder, incentBuilder testutil.IncentiveGenesisBuilder, hardBuilder testutil.HardGenesisBuilder) { - suite.SetupApp() - - suite.app.InitializeFromGenesisStatesWithTime( - suite.genesisTime, - authBuilder.BuildMarshalled(suite.app.AppCodec()), - NewPricefeedGenStateMultiFromTime(suite.app.AppCodec(), suite.genesisTime), - NewCDPGenStateMulti(suite.app.AppCodec()), - hardBuilder.BuildMarshalled(suite.app.AppCodec()), - incentBuilder.BuildMarshalled(suite.app.AppCodec()), - ) -} - -func (suite *PayoutTestSuite) getAccount(addr sdk.AccAddress) authtypes.AccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetAccount(suite.ctx, addr) -} - -func (suite *PayoutTestSuite) getModuleAccount(name string) authtypes.ModuleAccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetModuleAccount(suite.ctx, name) -} - -func (suite *PayoutTestSuite) TestSendCoinsToPeriodicVestingAccount() { - type accountArgs struct { - periods []vestingtypes.Period - origVestingCoins sdk.Coins - startTime int64 - endTime int64 - } - type args struct { - accArgs accountArgs - period vestingtypes.Period - ctxTime time.Time - mintModAccountCoins bool - expectedPeriods []vestingtypes.Period - expectedStartTime int64 - expectedEndTime int64 - } - type errArgs struct { - expectErr bool - contains string - } - type testCase struct { - name string - args args - errArgs errArgs - } - type testCases []testCase - - tests := testCases{ - { - name: "insert period at beginning schedule", - args: args{ - accArgs: accountArgs{ - periods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - origVestingCoins: cs(c("ukava", 20)), - startTime: 100, - endTime: 120, - }, - period: vestingtypes.Period{Length: 2, Amount: cs(c("ukava", 6))}, - ctxTime: time.Unix(101, 0), - mintModAccountCoins: true, - expectedPeriods: []vestingtypes.Period{ - {Length: 3, Amount: cs(c("ukava", 6))}, - {Length: 2, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - expectedStartTime: 100, - expectedEndTime: 120, - }, - errArgs: errArgs{ - expectErr: false, - contains: "", - }, - }, - { - name: "insert period at beginning with new start time", - args: args{ - accArgs: accountArgs{ - periods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - origVestingCoins: cs(c("ukava", 20)), - startTime: 100, - endTime: 120, - }, - period: vestingtypes.Period{Length: 7, Amount: cs(c("ukava", 6))}, - ctxTime: time.Unix(80, 0), - mintModAccountCoins: true, - expectedPeriods: []vestingtypes.Period{ - {Length: 7, Amount: cs(c("ukava", 6))}, - {Length: 18, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - expectedStartTime: 80, - expectedEndTime: 120, - }, - errArgs: errArgs{ - expectErr: false, - contains: "", - }, - }, - { - name: "insert period in middle of schedule", - args: args{ - accArgs: accountArgs{ - periods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - origVestingCoins: cs(c("ukava", 20)), - startTime: 100, - endTime: 120, - }, - period: vestingtypes.Period{Length: 7, Amount: cs(c("ukava", 6))}, - ctxTime: time.Unix(101, 0), - mintModAccountCoins: true, - expectedPeriods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 3, Amount: cs(c("ukava", 6))}, - {Length: 2, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - expectedStartTime: 100, - expectedEndTime: 120, - }, - errArgs: errArgs{ - expectErr: false, - contains: "", - }, - }, - { - name: "append to end of schedule", - args: args{ - accArgs: accountArgs{ - periods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - origVestingCoins: cs(c("ukava", 20)), - startTime: 100, - endTime: 120, - }, - period: vestingtypes.Period{Length: 7, Amount: cs(c("ukava", 6))}, - ctxTime: time.Unix(125, 0), - mintModAccountCoins: true, - expectedPeriods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 12, Amount: cs(c("ukava", 6))}, - }, - expectedStartTime: 100, - expectedEndTime: 132, - }, - errArgs: errArgs{ - expectErr: false, - contains: "", - }, - }, - { - name: "add coins to existing period", - args: args{ - accArgs: accountArgs{ - periods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - origVestingCoins: cs(c("ukava", 20)), - startTime: 100, - endTime: 120, - }, - period: vestingtypes.Period{Length: 5, Amount: cs(c("ukava", 6))}, - ctxTime: time.Unix(110, 0), - mintModAccountCoins: true, - expectedPeriods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 11))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - expectedStartTime: 100, - expectedEndTime: 120, - }, - errArgs: errArgs{ - expectErr: false, - contains: "", - }, - }, - { - name: "insufficient mod account balance", - args: args{ - accArgs: accountArgs{ - periods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - origVestingCoins: cs(c("ukava", 20)), - startTime: 100, - endTime: 120, - }, - period: vestingtypes.Period{Length: 7, Amount: cs(c("ukava", 6))}, - ctxTime: time.Unix(125, 0), - mintModAccountCoins: false, - expectedPeriods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 12, Amount: cs(c("ukava", 6))}, - }, - expectedStartTime: 100, - expectedEndTime: 132, - }, - errArgs: errArgs{ - expectErr: true, - contains: "insufficient funds", - }, - }, - { - name: "add large period mid schedule", - args: args{ - accArgs: accountArgs{ - periods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - }, - origVestingCoins: cs(c("ukava", 20)), - startTime: 100, - endTime: 120, - }, - period: vestingtypes.Period{Length: 50, Amount: cs(c("ukava", 6))}, - ctxTime: time.Unix(110, 0), - mintModAccountCoins: true, - expectedPeriods: []vestingtypes.Period{ - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 5, Amount: cs(c("ukava", 5))}, - {Length: 40, Amount: cs(c("ukava", 6))}, - }, - expectedStartTime: 100, - expectedEndTime: 160, - }, - errArgs: errArgs{ - expectErr: false, - contains: "", - }, - }, - } - for _, tc := range tests { - suite.Run(tc.name, func() { - authBuilder := app.NewAuthBankGenesisBuilder().WithSimplePeriodicVestingAccount( - suite.addrs[0], - tc.args.accArgs.origVestingCoins, - tc.args.accArgs.periods, - tc.args.accArgs.startTime, - ) - if tc.args.mintModAccountCoins { - authBuilder = authBuilder.WithSimpleModuleAccount(kavadisttypes.ModuleName, tc.args.period.Amount) - } - - suite.genesisTime = tc.args.ctxTime - suite.SetupApp() - suite.app.InitializeFromGenesisStates( - authBuilder.BuildMarshalled(suite.app.AppCodec()), - ) - - err := suite.keeper.SendTimeLockedCoinsToPeriodicVestingAccount(suite.ctx, kavadisttypes.ModuleName, suite.addrs[0], tc.args.period.Amount, tc.args.period.Length) - - if tc.errArgs.expectErr { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } else { - suite.Require().NoError(err) - - acc := suite.getAccount(suite.addrs[0]) - vacc, ok := acc.(*vestingtypes.PeriodicVestingAccount) - suite.Require().True(ok) - suite.Require().Equal(tc.args.expectedPeriods, vacc.VestingPeriods) - suite.Require().Equal(tc.args.expectedStartTime, vacc.StartTime) - suite.Require().Equal(tc.args.expectedEndTime, vacc.EndTime) - } - }) - } -} - -func (suite *PayoutTestSuite) TestSendCoinsToBaseAccount() { - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[1], cs(c("ukava", 400))). - WithSimpleModuleAccount(kavadisttypes.ModuleName, cs(c("ukava", 600))) - - suite.genesisTime = time.Unix(100, 0) - suite.SetupApp() - suite.app.InitializeFromGenesisStates( - authBuilder.BuildMarshalled(suite.app.AppCodec()), - ) - - // send coins to base account - err := suite.keeper.SendTimeLockedCoinsToAccount(suite.ctx, kavadisttypes.ModuleName, suite.addrs[1], cs(c("ukava", 100)), 5) - suite.Require().NoError(err) - acc := suite.getAccount(suite.addrs[1]) - vacc, ok := acc.(*vestingtypes.PeriodicVestingAccount) - suite.True(ok) - expectedPeriods := []vestingtypes.Period{ - {Length: int64(5), Amount: cs(c("ukava", 100))}, - } - - bk := suite.app.GetBankKeeper() - - suite.Equal(expectedPeriods, vacc.VestingPeriods) - suite.Equal(cs(c("ukava", 100)), vacc.OriginalVesting) - suite.Equal(cs(c("ukava", 500)), bk.GetAllBalances(suite.ctx, vacc.GetAddress())) - suite.Equal(int64(105), vacc.EndTime) - suite.Equal(int64(100), vacc.StartTime) -} - -func (suite *PayoutTestSuite) TestSendCoinsToInvalidAccount() { - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleModuleAccount(kavadisttypes.ModuleName, cs(c("ukava", 600))) - - suite.SetupApp() - suite.app.InitializeFromGenesisStates( - authBuilder.BuildMarshalled(suite.app.AppCodec()), - ) - - // No longer an empty validator vesting account, just a regular addr - err := suite.keeper.SendTimeLockedCoinsToAccount(suite.ctx, kavadisttypes.ModuleName, suite.addrs[2], cs(c("ukava", 100)), 5) - suite.Require().ErrorIs(err, types.ErrAccountNotFound) - - macc := suite.getModuleAccount(cdptypes.ModuleName) - err = suite.keeper.SendTimeLockedCoinsToAccount(suite.ctx, kavadisttypes.ModuleName, macc.GetAddress(), cs(c("ukava", 100)), 5) - suite.Require().ErrorIs(err, types.ErrInvalidAccountType) -} - -func (suite *PayoutTestSuite) TestGetPeriodLength() { - type args struct { - blockTime time.Time - lockup int64 - } - type periodTest struct { - name string - args args - expectedLength int64 - } - testCases := []periodTest{ - { - name: "first half of month", - args: args{ - blockTime: time.Date(2020, 11, 2, 15, 0, 0, 0, time.UTC), - lockup: 6, - }, - expectedLength: time.Date(2021, 5, 15, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2020, 11, 2, 15, 0, 0, 0, time.UTC).Unix(), - }, - { - name: "first half of month long lockup", - args: args{ - blockTime: time.Date(2020, 11, 2, 15, 0, 0, 0, time.UTC), - lockup: 24, - }, - expectedLength: time.Date(2022, 11, 15, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2020, 11, 2, 15, 0, 0, 0, time.UTC).Unix(), - }, - { - name: "second half of month", - args: args{ - blockTime: time.Date(2020, 12, 31, 15, 0, 0, 0, time.UTC), - lockup: 6, - }, - expectedLength: time.Date(2021, 7, 1, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2020, 12, 31, 15, 0, 0, 0, time.UTC).Unix(), - }, - { - name: "second half of month long lockup", - args: args{ - blockTime: time.Date(2020, 12, 31, 15, 0, 0, 0, time.UTC), - lockup: 24, - }, - expectedLength: time.Date(2023, 1, 1, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2020, 12, 31, 15, 0, 0, 0, time.UTC).Unix(), - }, - { - name: "end of feb", - args: args{ - blockTime: time.Date(2021, 2, 28, 15, 0, 0, 0, time.UTC), - lockup: 6, - }, - expectedLength: time.Date(2021, 9, 1, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2021, 2, 28, 15, 0, 0, 0, time.UTC).Unix(), - }, - { - name: "leap year", - args: args{ - blockTime: time.Date(2020, 2, 29, 15, 0, 0, 0, time.UTC), - lockup: 6, - }, - expectedLength: time.Date(2020, 9, 1, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2020, 2, 29, 15, 0, 0, 0, time.UTC).Unix(), - }, - { - name: "leap year long lockup", - args: args{ - blockTime: time.Date(2020, 2, 29, 15, 0, 0, 0, time.UTC), - lockup: 24, - }, - expectedLength: time.Date(2022, 3, 1, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2020, 2, 29, 15, 0, 0, 0, time.UTC).Unix(), - }, - { - name: "exactly half of month, is pushed to start of month + lockup", - args: args{ - blockTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC), - lockup: 6, - }, - expectedLength: time.Date(2021, 7, 1, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Unix(), - }, - { - name: "just before half of month", - args: args{ - blockTime: time.Date(2020, 12, 15, 13, 59, 59, 0, time.UTC), - lockup: 6, - }, - expectedLength: time.Date(2021, 6, 15, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2020, 12, 15, 13, 59, 59, 0, time.UTC).Unix(), - }, - { - name: "just after start of month payout time, is pushed to mid month + lockup", - args: args{ - blockTime: time.Date(2020, 12, 1, 14, 0, 1, 0, time.UTC), - lockup: 1, - }, - expectedLength: time.Date(2021, 1, 15, 14, 0, 0, 0, time.UTC).Unix() - time.Date(2020, 12, 1, 14, 0, 1, 0, time.UTC).Unix(), - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - length := suite.keeper.GetPeriodLength(tc.args.blockTime, tc.args.lockup) - suite.Require().Equal(tc.expectedLength, length) - }) - } -} - -func TestPayoutTestSuite(t *testing.T) { - suite.Run(t, new(PayoutTestSuite)) -} diff --git a/x/incentive/keeper/querier.go b/x/incentive/keeper/querier.go deleted file mode 100644 index 34b830d5..00000000 --- a/x/incentive/keeper/querier.go +++ /dev/null @@ -1,144 +0,0 @@ -package keeper - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - earntypes "github.com/0glabs/0g-chain/x/earn/types" - "github.com/0glabs/0g-chain/x/incentive/types" - liquidtypes "github.com/0glabs/0g-chain/x/liquid/types" -) - -const ( - SecondsPerYear = 31536000 -) - -// GetStakingAPR returns the total APR for staking and incentive rewards -func GetStakingAPR(ctx sdk.Context, k Keeper, params types.Params) (sdk.Dec, error) { - // Get staking APR + incentive APR - inflationRate := k.mintKeeper.GetMinter(ctx).Inflation - communityTax := k.distrKeeper.GetCommunityTax(ctx) - - bondedTokens := k.stakingKeeper.TotalBondedTokens(ctx) - circulatingSupply := k.bankKeeper.GetSupply(ctx, types.BondDenom) - - // Staking APR = (Inflation Rate * (1 - Community Tax)) / (Bonded Tokens / Circulating Supply) - stakingAPR := inflationRate. - Mul(sdk.OneDec().Sub(communityTax)). - Quo(sdk.NewDecFromInt(bondedTokens). - Quo(sdk.NewDecFromInt(circulatingSupply.Amount))) - - // Get incentive APR - bkavaRewardPeriod, found := params.EarnRewardPeriods.GetMultiRewardPeriod(liquidtypes.DefaultDerivativeDenom) - if !found { - // No incentive rewards for bkava, only staking rewards - return stakingAPR, nil - } - - // Total amount of bkava in earn vaults, this may be lower than total bank - // supply of bkava as some bkava may not be deposited in earn vaults - totalEarnBkavaDeposited := sdk.ZeroInt() - - var iterErr error - k.earnKeeper.IterateVaultRecords(ctx, func(record earntypes.VaultRecord) (stop bool) { - if !k.liquidKeeper.IsDerivativeDenom(ctx, record.TotalShares.Denom) { - return false - } - - vaultValue, err := k.earnKeeper.GetVaultTotalValue(ctx, record.TotalShares.Denom) - if err != nil { - iterErr = err - return false - } - - totalEarnBkavaDeposited = totalEarnBkavaDeposited.Add(vaultValue.Amount) - - return false - }) - - if iterErr != nil { - return sdk.ZeroDec(), iterErr - } - - // Incentive APR = rewards per second * seconds per year / total supplied to earn vaults - // Override collateral type to use "kava" instead of "bkava" when fetching - incentiveAPY, err := GetAPYFromMultiRewardPeriod(ctx, k, types.BondDenom, bkavaRewardPeriod, totalEarnBkavaDeposited) - if err != nil { - return sdk.ZeroDec(), err - } - - totalAPY := stakingAPR.Add(incentiveAPY) - return totalAPY, nil -} - -// GetAPYFromMultiRewardPeriod calculates the APY for a given MultiRewardPeriod -func GetAPYFromMultiRewardPeriod( - ctx sdk.Context, - k Keeper, - collateralType string, - rewardPeriod types.MultiRewardPeriod, - totalSupply sdkmath.Int, -) (sdk.Dec, error) { - if totalSupply.IsZero() { - return sdk.ZeroDec(), nil - } - - // Get USD value of collateral type - collateralUSDValue, err := k.pricefeedKeeper.GetCurrentPrice(ctx, getMarketID(collateralType)) - if err != nil { - return sdk.ZeroDec(), fmt.Errorf( - "failed to get price for incentive collateralType %s with market ID %s: %w", - collateralType, getMarketID(collateralType), err, - ) - } - - // Total USD value of the collateral type total supply - totalSupplyUSDValue := sdk.NewDecFromInt(totalSupply).Mul(collateralUSDValue.Price) - - totalUSDRewardsPerSecond := sdk.ZeroDec() - - // In many cases, RewardsPerSecond are assets that are different from the - // CollateralType, so we need to use the USD value of CollateralType and - // RewardsPerSecond to determine the APY. - for _, reward := range rewardPeriod.RewardsPerSecond { - // Get USD value of 1 unit of reward asset type, using TWAP - rewardDenomUSDValue, err := k.pricefeedKeeper.GetCurrentPrice(ctx, getMarketID(reward.Denom)) - if err != nil { - return sdk.ZeroDec(), fmt.Errorf("failed to get price for RewardsPerSecond asset %s: %w", reward.Denom, err) - } - - rewardPerSecond := sdk.NewDecFromInt(reward.Amount).Mul(rewardDenomUSDValue.Price) - totalUSDRewardsPerSecond = totalUSDRewardsPerSecond.Add(rewardPerSecond) - } - - // APY = USD rewards per second * seconds per year / USD total supplied - apy := totalUSDRewardsPerSecond. - MulInt64(SecondsPerYear). - Quo(totalSupplyUSDValue) - - return apy, nil -} - -func getMarketID(denom string) string { - // Rewrite denoms as pricefeed has different names for some assets, - // e.g. "ukava" -> "kava", "erc20/multichain/usdc" -> "usdc" - // bkava is not included as it is handled separately - - // TODO: Replace hardcoded conversion with possible params set somewhere - // to be more flexible. E.g. a map of denoms to pricefeed market denoms in - // pricefeed params. - switch denom { - case types.BondDenom: - denom = "kava" - case "erc20/multichain/usdc": - denom = "usdc" - case "erc20/multichain/usdt": - denom = "usdt" - case "erc20/multichain/dai": - denom = "dai" - } - - return fmt.Sprintf("%s:usd:30", denom) -} diff --git a/x/incentive/keeper/querier_test.go b/x/incentive/keeper/querier_test.go deleted file mode 100644 index 865a1012..00000000 --- a/x/incentive/keeper/querier_test.go +++ /dev/null @@ -1,135 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" - sdk "github.com/cosmos/cosmos-sdk/types" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - - earntypes "github.com/0glabs/0g-chain/x/earn/types" - "github.com/0glabs/0g-chain/x/incentive/keeper" - "github.com/0glabs/0g-chain/x/incentive/types" - "github.com/stretchr/testify/suite" -) - -type QuerierTestSuite struct { - unitTester -} - -func TestQuerierTestSuite(t *testing.T) { - suite.Run(t, new(QuerierTestSuite)) -} - -func (suite *QuerierTestSuite) TestGetStakingAPR() { - communityTax := sdk.MustNewDecFromStr("0.90") - inflation := sdk.MustNewDecFromStr("0.75") - - bondedTokens := int64(120_000_000_000000) - liquidStakedTokens := int64(60_000_000_000000) - totalSupply := int64(289_138_414_286684) - - usdcDenom := "erc20/multichain/usdc" - usdcSupply := int64(2_500_000_000000) - - earnKeeper := newFakeEarnKeeper(). - addVault("bkava-asdf", earntypes.NewVaultShare("bkava-asdf", sdk.NewDec(liquidStakedTokens))). - addVault(usdcDenom, earntypes.NewVaultShare(usdcDenom, sdk.NewDec(usdcSupply))) - - suite.keeper = suite.NewTestKeeper(&fakeParamSubspace{}). - WithDistrKeeper( - newFakeDistrKeeper().setCommunityTax(communityTax), - ). - WithMintKeeper( - newFakeMintKeeper(). - setMinter(minttypes.NewMinter(inflation, sdk.OneDec())), - ). - WithStakingKeeper( - newFakeStakingKeeper().addBondedTokens(bondedTokens), - ). - WithBankKeeper( - newFakeBankKeeper().setSupply(sdk.NewCoin(types.BondDenom, sdkmath.NewInt(totalSupply))), - ). - WithEarnKeeper(earnKeeper). - WithLiquidKeeper( - newFakeLiquidKeeper().addDerivative(suite.ctx, "bkava-asdf", sdkmath.NewInt(liquidStakedTokens)), - ). - WithPricefeedKeeper( - newFakePricefeedKeeper(). - setPrice(pricefeedtypes.NewCurrentPrice("kava:usd:30", sdk.MustNewDecFromStr("1.5"))). - setPrice(pricefeedtypes.NewCurrentPrice("usdc:usd:30", sdk.OneDec())), - ). - Build() - - // ~18% APR - expectedStakingAPY := inflation. - Mul(sdk.OneDec().Sub(communityTax)). - Quo(sdk.NewDec(bondedTokens).Quo(sdk.NewDec(totalSupply))) - - // Staking APR = (Inflation Rate * (1 - Community Tax)) / (Bonded Tokens / Circulating Supply) - aprWithoutIncentives, err := keeper.GetStakingAPR(suite.ctx, suite.keeper, types.Params{}) - suite.Require().NoError(err) - suite.Require().Equal( - expectedStakingAPY, - aprWithoutIncentives, - ) - - suite.T().Logf("Staking APR without incentives: %s", aprWithoutIncentives) - - params := types.Params{ - EarnRewardPeriods: types.MultiRewardPeriods{ - { - Active: true, - CollateralType: "bkava", - Start: suite.ctx.BlockTime().Add(-time.Hour), - End: suite.ctx.BlockTime().Add(time.Hour), - RewardsPerSecond: sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(190258)), - ), - }, - { - Active: true, - CollateralType: "erc20/multichain/usdc", - Start: suite.ctx.BlockTime().Add(-time.Hour), - End: suite.ctx.BlockTime().Add(time.Hour), - RewardsPerSecond: sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(5284)), - ), - }, - }, - } - - suite.Run("GetStakingAPR", func() { - aprWithIncentives, err := keeper.GetStakingAPR(suite.ctx, suite.keeper, params) - suite.Require().NoError(err) - // Approx 10% increase in APR from incentives - suite.Require().Equal(sdk.MustNewDecFromStr("0.280711113729177500"), aprWithIncentives) - - suite.Require().Truef( - aprWithIncentives.GT(aprWithoutIncentives), - "APR with incentives (%s) should be greater than APR without incentives (%s)", - ) - }) - - suite.Run("GetAPYFromMultiRewardPeriod", func() { - vaultTotalValue, err := earnKeeper.GetVaultTotalValue(suite.ctx, usdcDenom) - suite.Require().NoError(err) - suite.Require().True(vaultTotalValue.Amount.IsPositive()) - - apy, err := keeper.GetAPYFromMultiRewardPeriod( - suite.ctx, - suite.keeper, - usdcDenom, - params.EarnRewardPeriods[1], - vaultTotalValue.Amount, - ) - suite.Require().NoError(err) - suite.Require().Equal( - sdk.MustNewDecFromStr("0.099981734400000000"), - apy, - "usdc apy should be approx 10%", - ) - }) -} diff --git a/x/incentive/keeper/rewards_borrow.go b/x/incentive/keeper/rewards_borrow.go deleted file mode 100644 index 806b1b59..00000000 --- a/x/incentive/keeper/rewards_borrow.go +++ /dev/null @@ -1,225 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - hardtypes "github.com/0glabs/0g-chain/x/hard/types" - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// AccumulateHardBorrowRewards calculates new rewards to distribute this block and updates the global indexes to reflect this. -// The provided rewardPeriod must be valid to avoid panics in calculating time durations. -func (k Keeper) AccumulateHardBorrowRewards(ctx sdk.Context, rewardPeriod types.MultiRewardPeriod) { - previousAccrualTime, found := k.GetPreviousHardBorrowRewardAccrualTime(ctx, rewardPeriod.CollateralType) - if !found { - previousAccrualTime = ctx.BlockTime() - } - - indexes, found := k.GetHardBorrowRewardIndexes(ctx, rewardPeriod.CollateralType) - if !found { - indexes = types.RewardIndexes{} - } - - acc := types.NewAccumulator(previousAccrualTime, indexes) - - totalSource := k.getHardBorrowTotalSourceShares(ctx, rewardPeriod.CollateralType) - - acc.Accumulate(rewardPeriod, totalSource, ctx.BlockTime()) - - k.SetPreviousHardBorrowRewardAccrualTime(ctx, rewardPeriod.CollateralType, acc.PreviousAccumulationTime) - if len(acc.Indexes) > 0 { - // the store panics when setting empty or nil indexes - k.SetHardBorrowRewardIndexes(ctx, rewardPeriod.CollateralType, acc.Indexes) - } -} - -// getHardBorrowTotalSourceShares fetches the sum of all source shares for a borrow reward. -// -// In the case of hard borrow, this is the total borrowed divided by the borrow interest factor (for a particular denom). -// This gives the "pre interest" or "normalized" value of the total borrowed. This is an amount, that if it was borrowed when -// the interest factor was zero (ie at time 0), the current value of it with interest would be equal to the current total borrowed. -// -// The normalized borrow is also used for each individual borrow's source shares amount. Normalized amounts do not change except through -// user input. This is essential as claims must be synced before any change to a source shares amount. The actual borrowed amounts cannot -// be used as they increase every block due to interest. -func (k Keeper) getHardBorrowTotalSourceShares(ctx sdk.Context, denom string) sdk.Dec { - totalBorrowedCoins, found := k.hardKeeper.GetBorrowedCoins(ctx) - if !found { - // assume no coins have been borrowed - totalBorrowedCoins = sdk.NewCoins() - } - totalBorrowed := totalBorrowedCoins.AmountOf(denom) - - interestFactor, found := k.hardKeeper.GetBorrowInterestFactor(ctx, denom) - if !found { - // assume nothing has been borrowed so the factor starts at it's default value - interestFactor = sdk.OneDec() - } - - // return borrowed/factor to get the "pre interest" value of the current total borrowed - return sdk.NewDecFromInt(totalBorrowed).Quo(interestFactor) -} - -// InitializeHardBorrowReward initializes the borrow-side of a hard liquidity provider claim -// by creating the claim and setting the borrow reward factor index -func (k Keeper) InitializeHardBorrowReward(ctx sdk.Context, borrow hardtypes.Borrow) { - claim, found := k.GetHardLiquidityProviderClaim(ctx, borrow.Borrower) - if !found { - claim = types.NewHardLiquidityProviderClaim(borrow.Borrower, sdk.Coins{}, nil, nil) - } - - var borrowRewardIndexes types.MultiRewardIndexes - for _, coin := range borrow.Amount { - globalRewardIndexes, found := k.GetHardBorrowRewardIndexes(ctx, coin.Denom) - if !found { - globalRewardIndexes = types.RewardIndexes{} - } - borrowRewardIndexes = borrowRewardIndexes.With(coin.Denom, globalRewardIndexes) - } - - claim.BorrowRewardIndexes = borrowRewardIndexes - k.SetHardLiquidityProviderClaim(ctx, claim) -} - -// SynchronizeHardBorrowReward updates the claim object by adding any accumulated rewards -// and updating the reward index value -func (k Keeper) SynchronizeHardBorrowReward(ctx sdk.Context, borrow hardtypes.Borrow) { - claim, found := k.GetHardLiquidityProviderClaim(ctx, borrow.Borrower) - if !found { - return - } - - // Source shares for hard borrows is their normalized borrow amount - normalizedBorrows, err := borrow.NormalizedBorrow() - if err != nil { - panic(fmt.Sprintf("during borrow reward sync, could not get normalized borrow for %s: %s", borrow.Borrower, err.Error())) - } - - for _, normedBorrow := range normalizedBorrows { - claim = k.synchronizeSingleHardBorrowReward(ctx, claim, normedBorrow.Denom, normedBorrow.Amount) - } - k.SetHardLiquidityProviderClaim(ctx, claim) -} - -// synchronizeSingleHardBorrowReward synchronizes a single rewarded borrow denom in a hard claim. -// It returns the claim without setting in the store. -// The public methods for accessing and modifying claims are preferred over this one. Direct modification of claims is easy to get wrong. -func (k Keeper) synchronizeSingleHardBorrowReward(ctx sdk.Context, claim types.HardLiquidityProviderClaim, denom string, sourceShares sdk.Dec) types.HardLiquidityProviderClaim { - globalRewardIndexes, found := k.GetHardBorrowRewardIndexes(ctx, denom) - if !found { - // The global factor is only not found if - // - the borrowed denom has not started accumulating rewards yet (either there is no reward specified in params, or the reward start time hasn't been hit) - // - OR it was wrongly deleted from state (factors should never be removed while unsynced claims exist) - // If not found we could either skip this sync, or assume the global factor is zero. - // Skipping will avoid storing unnecessary factors in the claim for non rewarded denoms. - // And in the event a global factor is wrongly deleted, it will avoid this function panicking when calculating rewards. - return claim - } - - userRewardIndexes, found := claim.BorrowRewardIndexes.Get(denom) - if !found { - // Normally the reward indexes should always be found. - // But if a denom was not rewarded then becomes rewarded (ie a reward period is added to params), then the indexes will be missing from claims for that borrowed denom. - // So given the reward period was just added, assume the starting value for any global reward indexes, which is an empty slice. - userRewardIndexes = types.RewardIndexes{} - } - - newRewards, err := k.CalculateRewards(userRewardIndexes, globalRewardIndexes, sourceShares) - if err != nil { - // Global reward factors should never decrease, as it would lead to a negative update to claim.Rewards. - // This panics if a global reward factor decreases or disappears between the old and new indexes. - panic(fmt.Sprintf("corrupted global reward indexes found: %v", err)) - } - - claim.Reward = claim.Reward.Add(newRewards...) - claim.BorrowRewardIndexes = claim.BorrowRewardIndexes.With(denom, globalRewardIndexes) - - return claim -} - -// UpdateHardBorrowIndexDenoms adds or removes reward indexes from a claim to match the denoms in the borrow. -func (k Keeper) UpdateHardBorrowIndexDenoms(ctx sdk.Context, borrow hardtypes.Borrow) { - claim, found := k.GetHardLiquidityProviderClaim(ctx, borrow.Borrower) - if !found { - claim = types.NewHardLiquidityProviderClaim(borrow.Borrower, sdk.Coins{}, nil, nil) - } - - borrowDenoms := getDenoms(borrow.Amount) - borrowRewardIndexDenoms := claim.BorrowRewardIndexes.GetCollateralTypes() - - borrowRewardIndexes := claim.BorrowRewardIndexes - - // Create a new multi-reward index in the claim for every new borrow denom - uniqueBorrowDenoms := setDifference(borrowDenoms, borrowRewardIndexDenoms) - - for _, denom := range uniqueBorrowDenoms { - globalBorrowRewardIndexes, found := k.GetHardBorrowRewardIndexes(ctx, denom) - if !found { - globalBorrowRewardIndexes = types.RewardIndexes{} - } - borrowRewardIndexes = borrowRewardIndexes.With(denom, globalBorrowRewardIndexes) - } - - // Delete multi-reward index from claim if the collateral type is no longer borrowed - uniqueBorrowRewardDenoms := setDifference(borrowRewardIndexDenoms, borrowDenoms) - - for _, denom := range uniqueBorrowRewardDenoms { - borrowRewardIndexes = borrowRewardIndexes.RemoveRewardIndex(denom) - } - - claim.BorrowRewardIndexes = borrowRewardIndexes - k.SetHardLiquidityProviderClaim(ctx, claim) -} - -// CalculateRewards computes how much rewards should have accrued to a reward source (eg a user's hard borrowed btc amount) -// between two index values. -// -// oldIndex is normally the index stored on a claim, newIndex the current global value, and sourceShares a hard borrowed/supplied amount. -// -// It returns an error if newIndexes does not contain all CollateralTypes from oldIndexes, or if any value of oldIndex.RewardFactor > newIndex.RewardFactor. -// This should never happen, as it would mean that a global reward index has decreased in value, or that a global reward index has been deleted from state. -func (k Keeper) CalculateRewards(oldIndexes, newIndexes types.RewardIndexes, sourceShares sdk.Dec) (sdk.Coins, error) { - // check for missing CollateralType's - for _, oldIndex := range oldIndexes { - if newIndex, found := newIndexes.Get(oldIndex.CollateralType); !found { - return nil, errorsmod.Wrapf(types.ErrDecreasingRewardFactor, "old: %v, new: %v", oldIndex, newIndex) - } - } - var reward sdk.Coins - for _, newIndex := range newIndexes { - oldFactor, found := oldIndexes.Get(newIndex.CollateralType) - if !found { - oldFactor = sdk.ZeroDec() - } - - rewardAmount, err := k.CalculateSingleReward(oldFactor, newIndex.RewardFactor, sourceShares) - if err != nil { - return nil, err - } - - reward = reward.Add( - sdk.NewCoin(newIndex.CollateralType, rewardAmount), - ) - } - return reward, nil -} - -// CalculateSingleReward computes how much rewards should have accrued to a reward source (eg a user's btcb-a cdp principal) -// between two index values. -// -// oldIndex is normally the index stored on a claim, newIndex the current global value, and sourceShares a cdp principal amount. -// -// Returns an error if oldIndex > newIndex. This should never happen, as it would mean that a global reward index has decreased in value, -// or that a global reward index has been deleted from state. -func (k Keeper) CalculateSingleReward(oldIndex, newIndex, sourceShares sdk.Dec) (sdkmath.Int, error) { - increase := newIndex.Sub(oldIndex) - if increase.IsNegative() { - return sdkmath.Int{}, errorsmod.Wrapf(types.ErrDecreasingRewardFactor, "old: %v, new: %v", oldIndex, newIndex) - } - reward := increase.Mul(sourceShares).RoundInt() - return reward, nil -} diff --git a/x/incentive/keeper/rewards_borrow_accum_test.go b/x/incentive/keeper/rewards_borrow_accum_test.go deleted file mode 100644 index a1a71bc6..00000000 --- a/x/incentive/keeper/rewards_borrow_accum_test.go +++ /dev/null @@ -1,322 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -type AccumulateBorrowRewardsTests struct { - unitTester -} - -func (suite *AccumulateBorrowRewardsTests) storedTimeEquals(denom string, expected time.Time) { - storedTime, found := suite.keeper.GetPreviousHardBorrowRewardAccrualTime(suite.ctx, denom) - suite.True(found) - suite.Equal(expected, storedTime) -} - -func (suite *AccumulateBorrowRewardsTests) storedIndexesEqual(denom string, expected types.RewardIndexes) { - storedIndexes, found := suite.keeper.GetHardBorrowRewardIndexes(suite.ctx, denom) - suite.Equal(found, expected != nil) - - if found { - suite.Equal(expected, storedIndexes) - } else { - // Can't compare Equal for types.RewardIndexes(nil) vs types.RewardIndexes{} - suite.Empty(storedIndexes) - } -} - -func TestAccumulateBorrowRewards(t *testing.T) { - suite.Run(t, new(AccumulateBorrowRewardsTests)) -} - -func (suite *AccumulateBorrowRewardsTests) TestStateUpdatedWhenBlockTimeHasIncreased() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalBorrow(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - suite.storeGlobalBorrowIndexes(types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - }) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardBorrowRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - newAccrualTime := previousAccrualTime.Add(1 * time.Hour) - suite.ctx = suite.ctx.WithBlockTime(newAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(denom, newAccrualTime) - suite.storedIndexesEqual(denom, types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("7.22"), - }, - { - CollateralType: "ukava", - RewardFactor: d("3.64"), - }, - }) -} - -func (suite *AccumulateBorrowRewardsTests) TestStateUnchangedWhenBlockTimeHasNotIncreased() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalBorrow(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalBorrowIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardBorrowRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(denom, previousAccrualTime) - expected, f := previousIndexes.Get(denom) - suite.True(f) - suite.storedIndexesEqual(denom, expected) -} - -func (suite *AccumulateBorrowRewardsTests) TestNoAccumulationWhenSourceSharesAreZero() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper() // zero total borrows - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalBorrowIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardBorrowRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(7 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(denom, firstAccrualTime) - expected, f := previousIndexes.Get(denom) - suite.True(f) - suite.storedIndexesEqual(denom, expected) -} - -func (suite *AccumulateBorrowRewardsTests) TestStateAddedWhenStateDoesNotExist() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalBorrow(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), - ) - - firstAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, period) - - // After the first accumulation only the current block time should be stored. - // The indexes will be empty as no time has passed since the previous block because it didn't exist. - suite.storedTimeEquals(denom, firstAccrualTime) - suite.storedIndexesEqual(denom, nil) - - secondAccrualTime := firstAccrualTime.Add(10 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(secondAccrualTime) - - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, period) - - // After the second accumulation both current block time and indexes should be stored. - suite.storedTimeEquals(denom, secondAccrualTime) - suite.storedIndexesEqual(denom, types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.01"), - }, - }) -} - -func (suite *AccumulateBorrowRewardsTests) TestNoPanicWhenStateDoesNotExist() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper() - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(), - ) - - accrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(accrualTime) - - // Accumulate with no source shares and no rewards per second will result in no increment to the indexes. - // No increment and no previous indexes stored, results in an updated of nil. Setting this in the state panics. - // Check there is no panic. - suite.NotPanics(func() { - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, period) - }) - - suite.storedTimeEquals(denom, accrualTime) - suite.storedIndexesEqual(denom, nil) -} - -func (suite *AccumulateBorrowRewardsTests) TestNoAccumulationWhenBeforeStartTime() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalBorrow(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalBorrowIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardBorrowRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(10 * time.Second) - - period := types.NewMultiRewardPeriod( - true, - denom, - firstAccrualTime.Add(time.Nanosecond), // start time after accrual time - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, period) - - // The accrual time should be updated, but the indexes unchanged - suite.storedTimeEquals(denom, firstAccrualTime) - expectedIndexes, f := previousIndexes.Get(denom) - suite.True(f) - suite.storedIndexesEqual(denom, expectedIndexes) -} - -func (suite *AccumulateBorrowRewardsTests) TestPanicWhenCurrentTimeLessThanPrevious() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalBorrow(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardBorrowRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - firstAccrualTime := time.Time{} - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Time{}, // start time after accrual time - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.Panics(func() { - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, period) - }) -} diff --git a/x/incentive/keeper/rewards_borrow_init_test.go b/x/incentive/keeper/rewards_borrow_init_test.go deleted file mode 100644 index 1b80df86..00000000 --- a/x/incentive/keeper/rewards_borrow_init_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// InitializeHardBorrowRewardTests runs unit tests for the keeper.InitializeHardBorrowReward method -type InitializeHardBorrowRewardTests struct { - unitTester -} - -func TestInitializeHardBorrowReward(t *testing.T) { - suite.Run(t, new(InitializeHardBorrowRewardTests)) -} - -func (suite *InitializeHardBorrowRewardTests) TestClaimIndexesAreSetWhenClaimExists() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - // Indexes should always be empty when initialize is called. - // If initialize is called then the user must have repaid their borrow positions, - // which means UpdateHardBorrowIndexDenoms was called and should have remove indexes. - BorrowRewardIndexes: types.MultiRewardIndexes{}, - } - suite.storeHardClaim(claim) - - globalIndexes := nonEmptyMultiRewardIndexes - suite.storeGlobalBorrowIndexes(globalIndexes) - - borrow := NewBorrowBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.InitializeHardBorrowReward(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.BorrowRewardIndexes) -} - -func (suite *InitializeHardBorrowRewardTests) TestClaimIndexesAreSetWhenClaimDoesNotExist() { - globalIndexes := nonEmptyMultiRewardIndexes - suite.storeGlobalBorrowIndexes(globalIndexes) - - owner := arbitraryAddress() - borrow := NewBorrowBuilder(owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.InitializeHardBorrowReward(suite.ctx, borrow) - - syncedClaim, found := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, owner) - suite.True(found) - suite.Equal(globalIndexes, syncedClaim.BorrowRewardIndexes) -} - -func (suite *InitializeHardBorrowRewardTests) TestClaimIndexesAreSetEmptyForMissingIndexes() { - globalIndexes := nonEmptyMultiRewardIndexes - suite.storeGlobalBorrowIndexes(globalIndexes) - - owner := arbitraryAddress() - // Borrow a denom that is not in the global indexes. - // This happens when a borrow denom has no rewards associated with it. - expectedIndexes := appendUniqueEmptyMultiRewardIndex(globalIndexes) - borrowedDenoms := extractCollateralTypes(expectedIndexes) - borrow := NewBorrowBuilder(owner). - WithArbitrarySourceShares(borrowedDenoms...). - Build() - - suite.keeper.InitializeHardBorrowReward(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, owner) - suite.Equal(expectedIndexes, syncedClaim.BorrowRewardIndexes) -} diff --git a/x/incentive/keeper/rewards_borrow_sync_test.go b/x/incentive/keeper/rewards_borrow_sync_test.go deleted file mode 100644 index ac28fb87..00000000 --- a/x/incentive/keeper/rewards_borrow_sync_test.go +++ /dev/null @@ -1,568 +0,0 @@ -package keeper_test - -import ( - "errors" - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" - - hardtypes "github.com/0glabs/0g-chain/x/hard/types" - "github.com/0glabs/0g-chain/x/incentive/keeper" - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// SynchronizeHardBorrowRewardTests runs unit tests for the keeper.SynchronizeHardBorrowReward method -type SynchronizeHardBorrowRewardTests struct { - unitTester -} - -func TestSynchronizeHardBorrowReward(t *testing.T) { - suite.Run(t, new(SynchronizeHardBorrowRewardTests)) -} - -func (suite *SynchronizeHardBorrowRewardTests) TestClaimIndexesAreUpdatedWhenGlobalIndexesHaveIncreased() { - // This is the normal case - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - BorrowRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - - globalIndexes := increaseAllRewardFactors(nonEmptyMultiRewardIndexes) - suite.storeGlobalBorrowIndexes(globalIndexes) - - borrow := NewBorrowBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(claim.BorrowRewardIndexes)...). - Build() - - suite.keeper.SynchronizeHardBorrowReward(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.BorrowRewardIndexes) -} - -func (suite *SynchronizeHardBorrowRewardTests) TestClaimIndexesAreUnchangedWhenGlobalIndexesUnchanged() { - // It should be safe to call SynchronizeHardBorrowReward multiple times - - unchangingIndexes := nonEmptyMultiRewardIndexes - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - BorrowRewardIndexes: unchangingIndexes, - } - suite.storeHardClaim(claim) - - suite.storeGlobalBorrowIndexes(unchangingIndexes) - - borrow := NewBorrowBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(unchangingIndexes)...). - Build() - - suite.keeper.SynchronizeHardBorrowReward(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(unchangingIndexes, syncedClaim.BorrowRewardIndexes) -} - -func (suite *SynchronizeHardBorrowRewardTests) TestClaimIndexesAreUpdatedWhenNewRewardAdded() { - // When a new reward is added (via gov) for a hard borrow denom the user has already borrowed, and the claim is synced; - // Then the new reward's index should be added to the claim. - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - BorrowRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - - globalIndexes := appendUniqueMultiRewardIndex(nonEmptyMultiRewardIndexes) - suite.storeGlobalBorrowIndexes(globalIndexes) - - borrow := NewBorrowBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.SynchronizeHardBorrowReward(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.BorrowRewardIndexes) -} - -func (suite *SynchronizeHardBorrowRewardTests) TestClaimIndexesAreUpdatedWhenNewRewardDenomAdded() { - // When a new reward coin is added (via gov) to an already rewarded borrow denom (that the user has already borrowed), and the claim is synced; - // Then the new reward coin's index should be added to the claim. - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - BorrowRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - - globalIndexes := appendUniqueRewardIndexToFirstItem(nonEmptyMultiRewardIndexes) - suite.storeGlobalBorrowIndexes(globalIndexes) - - borrow := NewBorrowBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.SynchronizeHardBorrowReward(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.BorrowRewardIndexes) -} - -func (suite *SynchronizeHardBorrowRewardTests) TestRewardIsIncrementedWhenGlobalIndexesHaveIncreased() { - // This is the normal case - // Given some time has passed (meaning the global indexes have increased) - // When the claim is synced - // The user earns rewards for the time passed - - originalReward := arbitraryCoins() - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - BorrowRewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: "borrowdenom", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeHardClaim(claim) - - suite.storeGlobalBorrowIndexes(types.MultiRewardIndexes{ - { - CollateralType: "borrowdenom", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("2000.002"), - }, - }, - }, - }) - - borrow := NewBorrowBuilder(claim.Owner). - WithSourceShares("borrowdenom", 1e9). - Build() - - suite.keeper.SynchronizeHardBorrowReward(suite.ctx, borrow) - - // new reward is (new index - old index) * borrow amount - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal( - cs(c("rewarddenom", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeHardBorrowRewardTests) TestRewardIsIncrementedWhenNewRewardAdded() { - // When a new reward is added (via gov) for a hard borrow denom the user has already borrowed, and the claim is synced - // Then the user earns rewards for the time since the reward was added - - originalReward := arbitraryCoins() - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - BorrowRewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: "rewarded", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeHardClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: "rewarded", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - }, - }, - { - CollateralType: "newlyrewarded", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalBorrowIndexes(globalIndexes) - - borrow := NewBorrowBuilder(claim.Owner). - WithSourceShares("rewarded", 1e9). - WithSourceShares("newlyrewarded", 1e9). - Build() - - suite.keeper.SynchronizeHardBorrowReward(suite.ctx, borrow) - - // new reward is (new index - old index) * borrow amount for each borrowed denom - // The old index for `newlyrewarded` isn't in the claim, so it's added starting at 0 for calculating the reward. - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal( - cs(c("otherreward", 1_000_001_000_000), c("reward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeHardBorrowRewardTests) TestRewardIsIncrementedWhenNewRewardDenomAdded() { - // When a new reward coin is added (via gov) to an already rewarded borrow denom (that the user has already borrowed), and the claim is synced; - // Then the user earns rewards for the time since the reward was added - - originalReward := arbitraryCoins() - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - BorrowRewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: "borrowed", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeHardClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: "borrowed", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalBorrowIndexes(globalIndexes) - - borrow := NewBorrowBuilder(claim.Owner). - WithSourceShares("borrowed", 1e9). - Build() - - suite.keeper.SynchronizeHardBorrowReward(suite.ctx, borrow) - - // new reward is (new index - old index) * borrow amount for each borrowed denom - // The old index for `otherreward` isn't in the claim, so it's added starting at 0 for calculating the reward. - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal( - cs(c("reward", 1_000_001_000_000), c("otherreward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -// BorrowBuilder is a tool for creating a hard borrows. -// The builder inherits from hard.Borrow, so fields can be accessed directly if a helper method doesn't exist. -type BorrowBuilder struct { - hardtypes.Borrow -} - -// NewBorrowBuilder creates a BorrowBuilder containing an empty borrow. -func NewBorrowBuilder(borrower sdk.AccAddress) BorrowBuilder { - return BorrowBuilder{ - Borrow: hardtypes.Borrow{ - Borrower: borrower, - }, - } -} - -// Build assembles and returns the final borrow. -func (builder BorrowBuilder) Build() hardtypes.Borrow { return builder.Borrow } - -// WithSourceShares adds a borrow amount and factor such that the source shares for this borrow is equal to specified. -// With a factor of 1, the borrow amount is the source shares. This picks an arbitrary factor to ensure factors are accounted for in production code. -func (builder BorrowBuilder) WithSourceShares(denom string, shares int64) BorrowBuilder { - if !builder.Amount.AmountOf(denom).Equal(sdk.ZeroInt()) { - panic("adding to amount with existing denom not implemented") - } - if _, f := builder.Index.GetInterestFactor(denom); f { - panic("adding to indexes with existing denom not implemented") - } - - // pick arbitrary factor - factor := sdk.MustNewDecFromStr("2") - - // Calculate borrow amount that would equal the requested source shares given the above factor. - amt := sdkmath.NewInt(shares).Mul(factor.RoundInt()) - - builder.Amount = builder.Amount.Add(sdk.NewCoin(denom, amt)) - builder.Index = builder.Index.SetInterestFactor(denom, factor) - return builder -} - -// WithArbitrarySourceShares adds arbitrary borrow amounts and indexes for each specified denom. -func (builder BorrowBuilder) WithArbitrarySourceShares(denoms ...string) BorrowBuilder { - const arbitraryShares = 1e9 - for _, denom := range denoms { - builder = builder.WithSourceShares(denom, arbitraryShares) - } - return builder -} - -func TestCalculateRewards(t *testing.T) { - type expected struct { - err error - coins sdk.Coins - } - type args struct { - oldIndexes, newIndexes types.RewardIndexes - sourceAmount sdk.Dec - } - testcases := []struct { - name string - args args - expected expected - }{ - { - name: "when old and new indexes have same denoms, rewards are calculated correctly", - args: args{ - oldIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.000000001"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.1"), - }, - }, - newIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("1000.0"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.100000001"), - }, - }, - sourceAmount: d("1000000000"), - }, - expected: expected{ - // for each denom: (new - old) * sourceAmount - coins: cs(c("hard", 999999999999), c("ukava", 1)), - }, - }, - { - name: "when new indexes have an extra denom, rewards are calculated as if it was 0 in old indexes", - args: args{ - oldIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.000000001"), - }, - }, - newIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("1000.0"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.100000001"), - }, - }, - sourceAmount: d("1000000000"), - }, - expected: expected{ - // for each denom: (new - old) * sourceAmount - coins: cs(c("hard", 999999999999), c("ukava", 100000001)), - }, - }, - { - name: "when new indexes are smaller than old, an error is returned", - args: args{ - oldIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.2"), - }, - }, - newIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.1"), - }, - }, - sourceAmount: d("1000000000"), - }, - expected: expected{ - err: types.ErrDecreasingRewardFactor, - }, - }, - { - name: "when old indexes have an extra denom, an error is returned", - args: args{ - oldIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.1"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.1"), - }, - }, - newIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.2"), - }, - }, - sourceAmount: d("1000000000"), - }, - expected: expected{ - err: types.ErrDecreasingRewardFactor, - }, - }, - { - name: "when old and new indexes are 0, rewards are 0", - args: args{ - oldIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.0"), - }, - }, - newIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.0"), - }, - }, - sourceAmount: d("1000000000"), - }, - expected: expected{ - coins: sdk.Coins{}, - }, - }, - { - name: "when old and new indexes are empty, rewards are 0", - args: args{ - oldIndexes: types.RewardIndexes{}, - newIndexes: nil, - sourceAmount: d("1000000000"), - }, - expected: expected{ - coins: nil, - }, - }, - } - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - coins, err := keeper.Keeper{}.CalculateRewards(tc.args.oldIndexes, tc.args.newIndexes, tc.args.sourceAmount) - if tc.expected.err != nil { - require.True(t, errors.Is(err, tc.expected.err)) - } else { - require.Equal(t, tc.expected.coins, coins) - } - }) - } -} - -func TestCalculateSingleReward(t *testing.T) { - type expected struct { - err error - reward sdkmath.Int - } - type args struct { - oldIndex, newIndex sdk.Dec - sourceAmount sdk.Dec - } - testcases := []struct { - name string - args args - expected expected - }{ - { - name: "when new index is > old, rewards are calculated correctly", - args: args{ - oldIndex: d("0.000000001"), - newIndex: d("1000.0"), - sourceAmount: d("1000000000"), - }, - expected: expected{ - // (new - old) * sourceAmount - reward: i(999999999999), - }, - }, - { - name: "when new index is < old, an error is returned", - args: args{ - oldIndex: d("0.000000001"), - newIndex: d("0.0"), - sourceAmount: d("1000000000"), - }, - expected: expected{ - err: types.ErrDecreasingRewardFactor, - }, - }, - { - name: "when old and new indexes are 0, rewards are 0", - args: args{ - oldIndex: d("0.0"), - newIndex: d("0.0"), - sourceAmount: d("1000000000"), - }, - expected: expected{ - reward: sdk.ZeroInt(), - }, - }, - } - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - reward, err := keeper.Keeper{}.CalculateSingleReward(tc.args.oldIndex, tc.args.newIndex, tc.args.sourceAmount) - if tc.expected.err != nil { - require.True(t, errors.Is(err, tc.expected.err)) - } else { - require.Equal(t, tc.expected.reward, reward) - } - }) - } -} diff --git a/x/incentive/keeper/rewards_borrow_test.go b/x/incentive/keeper/rewards_borrow_test.go deleted file mode 100644 index e0df053a..00000000 --- a/x/incentive/keeper/rewards_borrow_test.go +++ /dev/null @@ -1,1073 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - proposaltypes "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/committee" - committeekeeper "github.com/0glabs/0g-chain/x/committee/keeper" - committeetypes "github.com/0glabs/0g-chain/x/committee/types" - "github.com/0glabs/0g-chain/x/hard" - hardkeeper "github.com/0glabs/0g-chain/x/hard/keeper" - "github.com/0glabs/0g-chain/x/incentive/keeper" - "github.com/0glabs/0g-chain/x/incentive/testutil" - "github.com/0glabs/0g-chain/x/incentive/types" - kavadisttypes "github.com/0glabs/0g-chain/x/kavadist/types" -) - -type BorrowIntegrationTests struct { - testutil.IntegrationTester - - genesisTime time.Time - addrs []sdk.AccAddress -} - -func TestBorrowIntegration(t *testing.T) { - suite.Run(t, new(BorrowIntegrationTests)) -} - -// SetupTest is run automatically before each suite test -func (suite *BorrowIntegrationTests) SetupTest() { - _, suite.addrs = app.GeneratePrivKeyAddressPairs(5) - - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *BorrowIntegrationTests) TestSingleUserAccumulatesRewardsAfterSyncing() { - userA := suite.addrs[0] - - authBulder := app.NewAuthBankGenesisBuilder(). - WithSimpleModuleAccount(kavadisttypes.ModuleName, cs(c("hard", 1e18))). // Fill kavadist with enough coins to pay out any reward - WithSimpleAccount(userA, cs(c("bnb", 1e12))) // give the user some coins - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithMultipliers(types.MultipliersPerDenoms{{ - Denom: "hard", - Multipliers: types.Multipliers{types.NewMultiplier("large", 12, d("1.0"))}, // keep payout at 1.0 to make maths easier - }}). - WithSimpleBorrowRewardPeriod("bnb", cs(c("hard", 1e6))) // only borrow rewards - - suite.SetApp() - suite.WithGenesisTime(suite.genesisTime) - suite.StartChain( - NewPricefeedGenStateMultiFromTime(suite.App.AppCodec(), suite.genesisTime), - NewHardGenStateMulti(suite.genesisTime).BuildMarshalled(suite.App.AppCodec()), - authBulder.BuildMarshalled(suite.App.AppCodec()), - incentBuilder.BuildMarshalled(suite.App.AppCodec()), - ) - - // Create a borrow (need to first deposit to allow it) - suite.NoError(suite.DeliverHardMsgDeposit(userA, cs(c("bnb", 1e11)))) - suite.NoError(suite.DeliverHardMsgBorrow(userA, cs(c("bnb", 1e10)))) - - // Let time pass to accumulate interest on the borrow - // Use one long block instead of many to reduce any rounding errors, and speed up tests. - suite.NextBlockAfter(1e6 * time.Second) // about 12 days - - // User borrows and repays just to sync their borrow. - suite.NoError(suite.DeliverHardMsgRepay(userA, cs(c("bnb", 1)))) - suite.NoError(suite.DeliverHardMsgBorrow(userA, cs(c("bnb", 1)))) - - // Accumulate more rewards. - // The user still has the same percentage of all borrows (100%) so their rewards should be the same as in the previous block. - suite.NextBlockAfter(1e6 * time.Second) // about 12 days - - msg := types.NewMsgClaimHardReward(userA.String(), types.Selections{ - types.NewSelection("hard", "large"), - }) - - // User claims all their rewards - suite.Require().NoError(suite.DeliverIncentiveMsg(&msg)) - - // The users has always had 100% of borrows, so they should receive all rewards for the previous two blocks. - // Total rewards for each block is block duration * rewards per second - accuracy := 1e-10 // using a very high accuracy to flag future small calculation changes - suite.BalanceInEpsilon(userA, cs(c("bnb", 1e12-1e11+1e10), c("hard", 2*1e6*1e6)), accuracy) -} - -// Test suite used for all keeper tests -type BorrowRewardsTestSuite struct { - suite.Suite - - keeper keeper.Keeper - hardKeeper hardkeeper.Keeper - committeeKeeper committeekeeper.Keeper - - app app.TestApp - ctx sdk.Context - - genesisTime time.Time - addrs []sdk.AccAddress -} - -// SetupTest is run automatically before each suite test -func (suite *BorrowRewardsTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - _, suite.addrs = app.GeneratePrivKeyAddressPairs(5) - - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *BorrowRewardsTestSuite) SetupApp() { - suite.app = app.NewTestApp() - - suite.keeper = suite.app.GetIncentiveKeeper() - suite.hardKeeper = suite.app.GetHardKeeper() - suite.committeeKeeper = suite.app.GetCommitteeKeeper() - - suite.ctx = suite.app.NewContext(true, tmproto.Header{Height: 1, Time: suite.genesisTime}) -} - -func (suite *BorrowRewardsTestSuite) SetupWithGenState(authBuilder *app.AuthBankGenesisBuilder, incentBuilder testutil.IncentiveGenesisBuilder, hardBuilder testutil.HardGenesisBuilder) { - suite.SetupApp() - - suite.app.InitializeFromGenesisStatesWithTime( - suite.genesisTime, - authBuilder.BuildMarshalled(suite.app.AppCodec()), - NewPricefeedGenStateMultiFromTime(suite.app.AppCodec(), suite.genesisTime), - hardBuilder.BuildMarshalled(suite.app.AppCodec()), - NewCommitteeGenesisState(suite.app.AppCodec(), 1, suite.addrs[:2]...), - incentBuilder.BuildMarshalled(suite.app.AppCodec()), - ) -} - -func (suite *BorrowRewardsTestSuite) TestAccumulateHardBorrowRewards() { - type args struct { - borrow sdk.Coin - rewardsPerSecond sdk.Coins - timeElapsed int - expectedRewardIndexes types.RewardIndexes - } - type test struct { - name string - args args - } - testCases := []test{ - { - "single reward denom: 7 seconds", - args{ - borrow: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 7, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.000000856478000001"))}, - }, - }, - { - "single reward denom: 1 day", - args{ - borrow: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 86400, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.010571385600010177"))}, - }, - }, - { - "single reward denom: 0 seconds", - args{ - borrow: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 0, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.0"))}, - }, - }, - { - "multiple reward denoms: 7 seconds", - args{ - borrow: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - timeElapsed: 7, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.000000856478000001")), - types.NewRewardIndex("ukava", d("0.000000856478000001")), - }, - }, - }, - { - "multiple reward denoms: 1 day", - args{ - borrow: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - timeElapsed: 86400, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.010571385600010177")), - types.NewRewardIndex("ukava", d("0.010571385600010177")), - }, - }, - }, - { - "multiple reward denoms: 0 seconds", - args{ - borrow: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - timeElapsed: 0, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - types.NewRewardIndex("ukava", d("0.0")), - }, - }, - }, - { - "multiple reward denoms with different rewards per second: 1 day", - args{ - borrow: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 555555)), - timeElapsed: 86400, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.010571385600010177")), - types.NewRewardIndex("ukava", d("0.047999952000046210")), - }, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder().WithSimpleAccount( - userAddr, - cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15)), - ) - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleBorrowRewardPeriod(tc.args.borrow.Denom, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder, NewHardGenStateMulti(suite.genesisTime)) - - // User deposits and borrows to increase total borrowed amount - err := suite.hardKeeper.Deposit(suite.ctx, userAddr, sdk.NewCoins(sdk.NewCoin(tc.args.borrow.Denom, tc.args.borrow.Amount.Mul(sdkmath.NewInt(2))))) - suite.Require().NoError(err) - err = suite.hardKeeper.Borrow(suite.ctx, userAddr, sdk.NewCoins(tc.args.borrow)) - suite.Require().NoError(err) - - // Set up chain context at future time - runAtTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed)) - runCtx := suite.ctx.WithBlockTime(runAtTime) - - // Run Hard begin blocker in order to update the denom's index factor - hard.BeginBlocker(runCtx, suite.hardKeeper) - - // Accumulate hard borrow rewards for the deposit denom - multiRewardPeriod, found := suite.keeper.GetHardBorrowRewardPeriods(runCtx, tc.args.borrow.Denom) - suite.Require().True(found) - suite.keeper.AccumulateHardBorrowRewards(runCtx, multiRewardPeriod) - - // Check that each expected reward index matches the current stored reward index for the denom - globalRewardIndexes, found := suite.keeper.GetHardBorrowRewardIndexes(runCtx, tc.args.borrow.Denom) - suite.Require().True(found) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - globalRewardIndex, found := globalRewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, globalRewardIndex) - } - }) - } -} - -func (suite *BorrowRewardsTestSuite) TestInitializeHardBorrowRewards() { - type args struct { - moneyMarketRewardDenoms map[string]sdk.Coins - deposit sdk.Coins - borrow sdk.Coins - expectedClaimBorrowRewardIndexes types.MultiRewardIndexes - } - type test struct { - name string - args args - } - - standardMoneyMarketRewardDenoms := map[string]sdk.Coins{ - "bnb": cs(c("hard", 1)), - "btcb": cs(c("hard", 1), c("ukava", 1)), - } - - testCases := []test{ - { - "single deposit denom, single reward denom", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("bnb", 1000000000000)), - borrow: cs(c("bnb", 100000000000)), - expectedClaimBorrowRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "bnb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - }, - ), - }, - }, - }, - { - "single deposit denom, multiple reward denoms", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("btcb", 1000000000000)), - borrow: cs(c("btcb", 100000000000)), - expectedClaimBorrowRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "btcb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - types.NewRewardIndex("ukava", d("0.0")), - }, - ), - }, - }, - }, - { - "single deposit denom, no reward denoms", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("xrp", 1000000000000)), - borrow: cs(c("xrp", 100000000000)), - expectedClaimBorrowRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "xrp", - nil, - ), - }, - }, - }, - { - "multiple deposit denoms, multiple overlapping reward denoms", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("bnb", 1000000000000), c("btcb", 1000000000000)), - borrow: cs(c("bnb", 100000000000), c("btcb", 100000000000)), - expectedClaimBorrowRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "bnb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - }, - ), - types.NewMultiRewardIndex( - "btcb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - types.NewRewardIndex("ukava", d("0.0")), - }, - ), - }, - }, - }, - { - "multiple deposit denoms, correct discrete reward denoms", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("bnb", 1000000000000), c("xrp", 1000000000000)), - borrow: cs(c("bnb", 100000000000), c("xrp", 100000000000)), - expectedClaimBorrowRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "bnb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - }, - ), - types.NewMultiRewardIndex( - "xrp", - nil, - ), - }, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder().WithSimpleAccount( - userAddr, - cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15)), - ) - - incentBuilder := testutil.NewIncentiveGenesisBuilder().WithGenesisTime(suite.genesisTime) - for moneyMarketDenom, rewardsPerSecond := range tc.args.moneyMarketRewardDenoms { - incentBuilder = incentBuilder.WithSimpleBorrowRewardPeriod(moneyMarketDenom, rewardsPerSecond) - } - - suite.SetupWithGenState(authBuilder, incentBuilder, NewHardGenStateMulti(suite.genesisTime)) - - // User deposits - err := suite.hardKeeper.Deposit(suite.ctx, userAddr, tc.args.deposit) - suite.Require().NoError(err) - // User borrows - err = suite.hardKeeper.Borrow(suite.ctx, userAddr, tc.args.borrow) - suite.Require().NoError(err) - - claim, foundClaim := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(foundClaim) - suite.Require().Equal(tc.args.expectedClaimBorrowRewardIndexes, claim.BorrowRewardIndexes) - }) - } -} - -func (suite *BorrowRewardsTestSuite) TestSynchronizeHardBorrowReward() { - type args struct { - incentiveBorrowRewardDenom string - borrow sdk.Coin - rewardsPerSecond sdk.Coins - blockTimes []int - expectedRewardIndexes types.RewardIndexes - expectedRewards sdk.Coins - updateRewardsViaCommmittee bool - updatedBaseDenom string - updatedRewardsPerSecond sdk.Coins - updatedExpectedRewardIndexes types.RewardIndexes - updatedExpectedRewards sdk.Coins - updatedTimeDuration int - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "single reward denom: 10 blocks", - args{ - incentiveBorrowRewardDenom: "bnb", - borrow: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.001223540000173228"))}, - expectedRewards: cs(c("hard", 12235400)), - updateRewardsViaCommmittee: false, - }, - }, - { - "single reward denom: 10 blocks - long block time", - args{ - incentiveBorrowRewardDenom: "bnb", - borrow: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("10.571385603126235340"))}, - expectedRewards: cs(c("hard", 105713856031)), - }, - }, - { - "single reward denom: user reward index updated when reward is zero", - args{ - incentiveBorrowRewardDenom: "ukava", - borrow: c("ukava", 1), // borrow a tiny amount so that rewards round to zero - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.122354003908172328"))}, - expectedRewards: cs(), - updateRewardsViaCommmittee: false, - }, - }, - { - "multiple reward denoms: 10 blocks", - args{ - incentiveBorrowRewardDenom: "bnb", - borrow: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.001223540000173228")), - types.NewRewardIndex("ukava", d("0.001223540000173228")), - }, - expectedRewards: cs(c("hard", 12235400), c("ukava", 12235400)), - }, - }, - { - "multiple reward denoms: 10 blocks - long block time", - args{ - incentiveBorrowRewardDenom: "bnb", - borrow: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("10.571385603126235340")), - types.NewRewardIndex("ukava", d("10.571385603126235340")), - }, - expectedRewards: cs(c("hard", 105713856031), c("ukava", 105713856031)), - }, - }, - { - "multiple reward denoms with different rewards per second: 10 blocks", - args{ - incentiveBorrowRewardDenom: "bnb", - borrow: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 555555)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.001223540000173228")), - types.NewRewardIndex("ukava", d("0.005555550000786558")), - }, - expectedRewards: cs(c("hard", 12235400), c("ukava", 55555500)), - }, - }, - { - "denom is in incentive's hard borrow reward params and has rewards; add new reward type", - args{ - incentiveBorrowRewardDenom: "bnb", - borrow: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{86400}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("1.057138560060101160")), - }, - expectedRewards: cs(c("hard", 10571385601)), - updateRewardsViaCommmittee: true, - updatedBaseDenom: "bnb", - updatedRewardsPerSecond: cs(c("hard", 122354), c("ukava", 100000)), - updatedExpectedRewards: cs(c("hard", 21142771202), c("ukava", 8640000000)), - updatedExpectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("2.114277120120202320")), - types.NewRewardIndex("ukava", d("0.864000000049120715")), - }, - updatedTimeDuration: 86400, - }, - }, - { - "denom is in hard's money market params but not in incentive's hard supply reward params; add reward", - args{ - incentiveBorrowRewardDenom: "bnb", - borrow: c("zzz", 10000000000), - rewardsPerSecond: nil, - blockTimes: []int{100}, - expectedRewardIndexes: types.RewardIndexes{}, - expectedRewards: sdk.Coins{}, - updateRewardsViaCommmittee: true, - updatedBaseDenom: "zzz", - updatedRewardsPerSecond: cs(c("hard", 100000)), - updatedExpectedRewards: cs(c("hard", 8640000000)), - updatedExpectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.864000000049803065")), - }, - updatedTimeDuration: 86400, - }, - }, - { - "denom is in hard's money market params but not in incentive's hard supply reward params; add multiple reward types", - args{ - incentiveBorrowRewardDenom: "bnb", - borrow: c("zzz", 10000000000), - rewardsPerSecond: nil, - blockTimes: []int{100}, - expectedRewardIndexes: types.RewardIndexes{}, - expectedRewards: sdk.Coins{}, - updateRewardsViaCommmittee: true, - updatedBaseDenom: "zzz", - updatedRewardsPerSecond: cs(c("hard", 100000), c("ukava", 100500), c("swap", 500)), - updatedExpectedRewards: cs(c("hard", 8640000000), c("ukava", 8683200001), c("swap", 43200000)), - updatedExpectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.864000000049803065")), - types.NewRewardIndex("ukava", d("0.868320000050052081")), - types.NewRewardIndex("swap", d("0.004320000000249015")), - }, - updatedTimeDuration: 86400, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[2], cs(c("ukava", 1e9))). - WithSimpleAccount(userAddr, cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15))) - - incentBuilder := testutil.NewIncentiveGenesisBuilder().WithGenesisTime(suite.genesisTime) - if tc.args.rewardsPerSecond != nil { - incentBuilder = incentBuilder.WithSimpleBorrowRewardPeriod(tc.args.incentiveBorrowRewardDenom, tc.args.rewardsPerSecond) - } - // Set the minimum borrow to 0 to allow testing small borrows - hardBuilder := NewHardGenStateMulti(suite.genesisTime).WithMinBorrow(sdk.ZeroDec()) - - suite.SetupWithGenState(authBuilder, incentBuilder, hardBuilder) - - // Borrow a fixed amount from another user to dilute primary user's rewards per second. - suite.Require().NoError( - suite.hardKeeper.Deposit(suite.ctx, suite.addrs[2], cs(c("ukava", 200_000_000))), - ) - suite.Require().NoError( - suite.hardKeeper.Borrow(suite.ctx, suite.addrs[2], cs(c("ukava", 100_000_000))), - ) - - // User deposits and borrows to increase total borrowed amount - err := suite.hardKeeper.Deposit(suite.ctx, userAddr, sdk.NewCoins(sdk.NewCoin(tc.args.borrow.Denom, tc.args.borrow.Amount.Mul(sdkmath.NewInt(2))))) - suite.Require().NoError(err) - err = suite.hardKeeper.Borrow(suite.ctx, userAddr, sdk.NewCoins(tc.args.borrow)) - suite.Require().NoError(err) - - // Check that Hard hooks initialized a HardLiquidityProviderClaim - claim, found := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - multiRewardIndex, _ := claim.BorrowRewardIndexes.GetRewardIndex(tc.args.borrow.Denom) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - currRewardIndex, found := multiRewardIndex.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(sdk.ZeroDec(), currRewardIndex.RewardFactor) - } - - // Run accumulator at several intervals - var timeElapsed int - previousBlockTime := suite.ctx.BlockTime() - for _, t := range tc.args.blockTimes { - timeElapsed += t - updatedBlockTime := previousBlockTime.Add(time.Duration(int(time.Second) * t)) - previousBlockTime = updatedBlockTime - blockCtx := suite.ctx.WithBlockTime(updatedBlockTime) - - // Run Hard begin blocker for each block ctx to update denom's interest factor - hard.BeginBlocker(blockCtx, suite.hardKeeper) - - // Accumulate hard borrow-side rewards - multiRewardPeriod, found := suite.keeper.GetHardBorrowRewardPeriods(blockCtx, tc.args.borrow.Denom) - if found { - suite.keeper.AccumulateHardBorrowRewards(blockCtx, multiRewardPeriod) - } - } - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - - // After we've accumulated, run synchronize - borrow, found := suite.hardKeeper.GetBorrow(suite.ctx, userAddr) - suite.Require().True(found) - suite.Require().NotPanics(func() { - suite.keeper.SynchronizeHardBorrowReward(suite.ctx, borrow) - }) - - // Check that the global reward index's reward factor and user's claim have been updated as expected - claim, found = suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - globalRewardIndexes, foundGlobalRewardIndexes := suite.keeper.GetHardBorrowRewardIndexes(suite.ctx, tc.args.borrow.Denom) - if len(tc.args.rewardsPerSecond) > 0 { - suite.Require().True(foundGlobalRewardIndexes) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - // Check that global reward index has been updated as expected - globalRewardIndex, found := globalRewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, globalRewardIndex) - - // Check that the user's claim's reward index matches the corresponding global reward index - multiRewardIndex, found := claim.BorrowRewardIndexes.GetRewardIndex(tc.args.borrow.Denom) - suite.Require().True(found) - rewardIndex, found := multiRewardIndex.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, rewardIndex) - - // Check that the user's claim holds the expected amount of reward coins - suite.Require().Equal( - tc.args.expectedRewards.AmountOf(expectedRewardIndex.CollateralType), - claim.Reward.AmountOf(expectedRewardIndex.CollateralType), - ) - } - } - - // Only test cases with reward param updates continue past this point - if !tc.args.updateRewardsViaCommmittee { - return - } - - // If are no initial rewards per second, add new rewards through a committee param change - // 1. Construct incentive's new HardBorrowRewardPeriods param - currIncentiveHardBorrowRewardPeriods := suite.keeper.GetParams(suite.ctx).HardBorrowRewardPeriods - multiRewardPeriod, found := currIncentiveHardBorrowRewardPeriods.GetMultiRewardPeriod(tc.args.borrow.Denom) - if found { - // Borrow denom's reward period exists, but it doesn't have any rewards per second - index, found := currIncentiveHardBorrowRewardPeriods.GetMultiRewardPeriodIndex(tc.args.borrow.Denom) - suite.Require().True(found) - multiRewardPeriod.RewardsPerSecond = tc.args.updatedRewardsPerSecond - currIncentiveHardBorrowRewardPeriods[index] = multiRewardPeriod - } else { - // Borrow denom's reward period does not exist - _, found := currIncentiveHardBorrowRewardPeriods.GetMultiRewardPeriodIndex(tc.args.borrow.Denom) - suite.Require().False(found) - newMultiRewardPeriod := types.NewMultiRewardPeriod(true, tc.args.borrow.Denom, suite.genesisTime, suite.genesisTime.Add(time.Hour*24*365*4), tc.args.updatedRewardsPerSecond) - currIncentiveHardBorrowRewardPeriods = append(currIncentiveHardBorrowRewardPeriods, newMultiRewardPeriod) - } - - // 2. Construct the parameter change proposal to update HardBorrowRewardPeriods param - pubProposal := proposaltypes.NewParameterChangeProposal( - "Update hard borrow rewards", "Adds a new reward coin to the incentive module's hard borrow rewards.", - []proposaltypes.ParamChange{ - { - Subspace: types.ModuleName, // target incentive module - Key: string(types.KeyHardBorrowRewardPeriods), // target hard borrow rewards key - Value: string(suite.app.LegacyAmino().MustMarshalJSON(currIncentiveHardBorrowRewardPeriods)), - }, - }, - ) - - // 3. Ensure proposal is properly formed - err = suite.committeeKeeper.ValidatePubProposal(suite.ctx, pubProposal) - suite.Require().NoError(err) - - // 4. Committee creates proposal - committeeMemberOne := suite.addrs[0] - committeeMemberTwo := suite.addrs[1] - proposalID, err := suite.committeeKeeper.SubmitProposal(suite.ctx, committeeMemberOne, 1, pubProposal) - suite.Require().NoError(err) - - // 5. Committee votes and passes proposal - err = suite.committeeKeeper.AddVote(suite.ctx, proposalID, committeeMemberOne, committeetypes.VOTE_TYPE_YES) - suite.Require().NoError(err) - err = suite.committeeKeeper.AddVote(suite.ctx, proposalID, committeeMemberTwo, committeetypes.VOTE_TYPE_YES) - suite.Require().NoError(err) - - // 6. Check proposal passed - com, found := suite.committeeKeeper.GetCommittee(suite.ctx, 1) - suite.Require().True(found) - proposalPasses := suite.committeeKeeper.GetProposalResult(suite.ctx, proposalID, com) - suite.Require().NoError(err) - suite.Require().True(proposalPasses) - - // 7. Run committee module's begin blocker to enact proposal - suite.NotPanics(func() { - committee.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}, suite.committeeKeeper) - }) - - // We need to accumulate hard supply-side rewards again - multiRewardPeriod, found = suite.keeper.GetHardBorrowRewardPeriods(suite.ctx, tc.args.borrow.Denom) - suite.Require().True(found) - - // But new borrow denoms don't have their PreviousHardBorrowRewardAccrualTime set yet, - // so we need to call the accumulation method once to set the initial reward accrual time - if tc.args.borrow.Denom != tc.args.incentiveBorrowRewardDenom { - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, multiRewardPeriod) - } - - // Now we can jump forward in time and accumulate rewards - updatedBlockTime = previousBlockTime.Add(time.Duration(int(time.Second) * tc.args.updatedTimeDuration)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - suite.keeper.AccumulateHardBorrowRewards(suite.ctx, multiRewardPeriod) - - // After we've accumulated, run synchronize - borrow, found = suite.hardKeeper.GetBorrow(suite.ctx, userAddr) - suite.Require().True(found) - suite.Require().NotPanics(func() { - suite.keeper.SynchronizeHardBorrowReward(suite.ctx, borrow) - }) - - // Check that the global reward index's reward factor and user's claim have been updated as expected - globalRewardIndexes, found = suite.keeper.GetHardBorrowRewardIndexes(suite.ctx, tc.args.borrow.Denom) - suite.Require().True(found) - claim, found = suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - - for _, expectedRewardIndex := range tc.args.updatedExpectedRewardIndexes { - // Check that global reward index has been updated as expected - globalRewardIndex, found := globalRewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, globalRewardIndex) - // Check that the user's claim's reward index matches the corresponding global reward index - multiRewardIndex, found := claim.BorrowRewardIndexes.GetRewardIndex(tc.args.borrow.Denom) - suite.Require().True(found) - rewardIndex, found := multiRewardIndex.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, rewardIndex) - - // Check that the user's claim holds the expected amount of reward coins - suite.Require().Equal( - tc.args.updatedExpectedRewards.AmountOf(expectedRewardIndex.CollateralType), - claim.Reward.AmountOf(expectedRewardIndex.CollateralType), - ) - } - }) - } -} - -func (suite *BorrowRewardsTestSuite) TestUpdateHardBorrowIndexDenoms() { - type withdrawModification struct { - coins sdk.Coins - repay bool - } - - type args struct { - initialDeposit sdk.Coins - firstBorrow sdk.Coins - modification withdrawModification - rewardsPerSecond sdk.Coins - expectedBorrowIndexDenoms []string - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "single reward denom: update adds one borrow reward index", - args{ - initialDeposit: cs(c("bnb", 10000000000)), - firstBorrow: cs(c("bnb", 50000000)), - modification: withdrawModification{coins: cs(c("ukava", 500000000))}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedBorrowIndexDenoms: []string{"bnb", "ukava"}, - }, - }, - { - "single reward denom: update adds multiple borrow supply reward indexes", - args{ - initialDeposit: cs(c("btcb", 10000000000)), - firstBorrow: cs(c("btcb", 50000000)), - modification: withdrawModification{coins: cs(c("ukava", 500000000), c("bnb", 50000000000), c("xrp", 50000000000))}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedBorrowIndexDenoms: []string{"btcb", "ukava", "bnb", "xrp"}, - }, - }, - { - "single reward denom: update doesn't add duplicate borrow reward index for same denom", - args{ - initialDeposit: cs(c("bnb", 100000000000)), - firstBorrow: cs(c("bnb", 50000000)), - modification: withdrawModification{coins: cs(c("bnb", 50000000000))}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedBorrowIndexDenoms: []string{"bnb"}, - }, - }, - { - "multiple reward denoms: update adds one borrow reward index", - args{ - initialDeposit: cs(c("bnb", 10000000000)), - firstBorrow: cs(c("bnb", 50000000)), - modification: withdrawModification{coins: cs(c("ukava", 500000000))}, - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - expectedBorrowIndexDenoms: []string{"bnb", "ukava"}, - }, - }, - { - "multiple reward denoms: update adds multiple borrow supply reward indexes", - args{ - initialDeposit: cs(c("btcb", 10000000000)), - firstBorrow: cs(c("btcb", 50000000)), - modification: withdrawModification{coins: cs(c("ukava", 500000000), c("bnb", 50000000000), c("xrp", 50000000000))}, - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - expectedBorrowIndexDenoms: []string{"btcb", "ukava", "bnb", "xrp"}, - }, - }, - { - "multiple reward denoms: update doesn't add duplicate borrow reward index for same denom", - args{ - initialDeposit: cs(c("bnb", 100000000000)), - firstBorrow: cs(c("bnb", 50000000)), - modification: withdrawModification{coins: cs(c("bnb", 50000000000))}, - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - expectedBorrowIndexDenoms: []string{"bnb"}, - }, - }, - { - "single reward denom: fully repaying a denom deletes the denom's supply reward index", - args{ - initialDeposit: cs(c("bnb", 1000000000)), - firstBorrow: cs(c("bnb", 100000000)), - modification: withdrawModification{coins: cs(c("bnb", 1100000000)), repay: true}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedBorrowIndexDenoms: []string{}, - }, - }, - { - "single reward denom: fully repaying a denom deletes only the denom's supply reward index", - args{ - initialDeposit: cs(c("bnb", 1000000000)), - firstBorrow: cs(c("bnb", 100000000), c("ukava", 10000000)), - modification: withdrawModification{coins: cs(c("bnb", 1100000000)), repay: true}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedBorrowIndexDenoms: []string{"ukava"}, - }, - }, - { - "multiple reward denoms: fully repaying a denom deletes the denom's supply reward index", - args{ - initialDeposit: cs(c("bnb", 1000000000)), - firstBorrow: cs(c("bnb", 100000000), c("ukava", 10000000)), - modification: withdrawModification{coins: cs(c("bnb", 1100000000)), repay: true}, - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - expectedBorrowIndexDenoms: []string{"ukava"}, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount( - userAddr, - cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15)), - ). - WithSimpleAccount( - suite.addrs[0], - cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15)), - ) - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleBorrowRewardPeriod("bnb", tc.args.rewardsPerSecond). - WithSimpleBorrowRewardPeriod("ukava", tc.args.rewardsPerSecond). - WithSimpleBorrowRewardPeriod("btcb", tc.args.rewardsPerSecond). - WithSimpleBorrowRewardPeriod("xrp", tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder, NewHardGenStateMulti(suite.genesisTime)) - - // Fill the hard supply to allow user to borrow - err := suite.hardKeeper.Deposit(suite.ctx, suite.addrs[0], tc.args.firstBorrow.Add(tc.args.modification.coins...)) - suite.Require().NoError(err) - - // User deposits initial funds (so that user can borrow) - err = suite.hardKeeper.Deposit(suite.ctx, userAddr, tc.args.initialDeposit) - suite.Require().NoError(err) - - // Confirm that claim exists but no borrow reward indexes have been added - claimAfterDeposit, found := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - suite.Require().Equal(0, len(claimAfterDeposit.BorrowRewardIndexes)) - - // User borrows (first time) - err = suite.hardKeeper.Borrow(suite.ctx, userAddr, tc.args.firstBorrow) - suite.Require().NoError(err) - - // Confirm that claim's borrow reward indexes have been updated - claimAfterFirstBorrow, found := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - for _, coin := range tc.args.firstBorrow { - _, hasIndex := claimAfterFirstBorrow.HasBorrowRewardIndex(coin.Denom) - suite.Require().True(hasIndex) - } - suite.Require().True(len(claimAfterFirstBorrow.BorrowRewardIndexes) == len(tc.args.firstBorrow)) - - // User modifies their Borrow by either repaying or borrowing more - if tc.args.modification.repay { - err = suite.hardKeeper.Repay(suite.ctx, userAddr, userAddr, tc.args.modification.coins) - } else { - err = suite.hardKeeper.Borrow(suite.ctx, userAddr, tc.args.modification.coins) - } - suite.Require().NoError(err) - - // Confirm that claim's borrow reward indexes contain expected values - claimAfterModification, found := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - for _, coin := range tc.args.modification.coins { - _, hasIndex := claimAfterModification.HasBorrowRewardIndex(coin.Denom) - if tc.args.modification.repay { - // Only false if denom is repaid in full - if tc.args.modification.coins.AmountOf(coin.Denom).GTE(tc.args.firstBorrow.AmountOf(coin.Denom)) { - suite.Require().False(hasIndex) - } - } else { - suite.Require().True(hasIndex) - } - } - suite.Require().True(len(claimAfterModification.BorrowRewardIndexes) == len(tc.args.expectedBorrowIndexDenoms)) - }) - } -} - -func (suite *BorrowRewardsTestSuite) TestSimulateHardBorrowRewardSynchronization() { - type args struct { - borrow sdk.Coin - rewardsPerSecond sdk.Coins - blockTimes []int - expectedRewardIndexes types.RewardIndexes - expectedRewards sdk.Coins - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "10 blocks", - args{ - borrow: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.001223540000173228"))}, - expectedRewards: cs(c("hard", 12235400)), - }, - }, - { - "10 blocks - long block time", - args{ - borrow: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("10.571385603126235340"))}, - expectedRewards: cs(c("hard", 105713856031)), - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder().WithSimpleAccount(userAddr, cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15))) - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleBorrowRewardPeriod(tc.args.borrow.Denom, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder, NewHardGenStateMulti(suite.genesisTime)) - - // User deposits and borrows to increase total borrowed amount - err := suite.hardKeeper.Deposit(suite.ctx, userAddr, sdk.NewCoins(sdk.NewCoin(tc.args.borrow.Denom, tc.args.borrow.Amount.Mul(sdkmath.NewInt(2))))) - suite.Require().NoError(err) - err = suite.hardKeeper.Borrow(suite.ctx, userAddr, sdk.NewCoins(tc.args.borrow)) - suite.Require().NoError(err) - - // Run accumulator at several intervals - var timeElapsed int - previousBlockTime := suite.ctx.BlockTime() - for _, t := range tc.args.blockTimes { - timeElapsed += t - updatedBlockTime := previousBlockTime.Add(time.Duration(int(time.Second) * t)) - previousBlockTime = updatedBlockTime - blockCtx := suite.ctx.WithBlockTime(updatedBlockTime) - - // Run Hard begin blocker for each block ctx to update denom's interest factor - hard.BeginBlocker(blockCtx, suite.hardKeeper) - - // Accumulate hard borrow-side rewards - multiRewardPeriod, found := suite.keeper.GetHardBorrowRewardPeriods(blockCtx, tc.args.borrow.Denom) - suite.Require().True(found) - suite.keeper.AccumulateHardBorrowRewards(blockCtx, multiRewardPeriod) - } - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - - // Confirm that the user's claim hasn't been synced - claimPre, foundPre := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(foundPre) - multiRewardIndexPre, _ := claimPre.BorrowRewardIndexes.GetRewardIndex(tc.args.borrow.Denom) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - currRewardIndex, found := multiRewardIndexPre.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(sdk.ZeroDec(), currRewardIndex.RewardFactor) - } - - // Check that the synced claim held in memory has properly simulated syncing - syncedClaim := suite.keeper.SimulateHardSynchronization(suite.ctx, claimPre) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - // Check that the user's claim's reward index matches the expected reward index - multiRewardIndex, found := syncedClaim.BorrowRewardIndexes.GetRewardIndex(tc.args.borrow.Denom) - suite.Require().True(found) - rewardIndex, found := multiRewardIndex.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, rewardIndex) - - // Check that the user's claim holds the expected amount of reward coins - suite.Require().Equal( - tc.args.expectedRewards.AmountOf(expectedRewardIndex.CollateralType), - syncedClaim.Reward.AmountOf(expectedRewardIndex.CollateralType), - ) - } - }) - } -} - -func TestBorrowRewardsTestSuite(t *testing.T) { - suite.Run(t, new(BorrowRewardsTestSuite)) -} diff --git a/x/incentive/keeper/rewards_borrow_update_test.go b/x/incentive/keeper/rewards_borrow_update_test.go deleted file mode 100644 index 571937c3..00000000 --- a/x/incentive/keeper/rewards_borrow_update_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// UpdateHardBorrowIndexDenomsTests runs unit tests for the keeper.UpdateHardBorrowIndexDenoms method -type UpdateHardBorrowIndexDenomsTests struct { - unitTester -} - -func TestUpdateHardBorrowIndexDenoms(t *testing.T) { - suite.Run(t, new(UpdateHardBorrowIndexDenomsTests)) -} - -func (suite *UpdateHardBorrowIndexDenomsTests) TestClaimIndexesAreRemovedForDenomsNoLongerBorrowed() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - BorrowRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - suite.storeGlobalBorrowIndexes(claim.BorrowRewardIndexes) - - // remove one denom from the indexes already in the borrow - expectedIndexes := claim.BorrowRewardIndexes[1:] - borrow := NewBorrowBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(expectedIndexes)...). - Build() - - suite.keeper.UpdateHardBorrowIndexDenoms(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(expectedIndexes, syncedClaim.BorrowRewardIndexes) -} - -func (suite *UpdateHardBorrowIndexDenomsTests) TestClaimIndexesAreAddedForNewlyBorrowedDenoms() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - BorrowRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - globalIndexes := appendUniqueMultiRewardIndex(claim.BorrowRewardIndexes) - suite.storeGlobalBorrowIndexes(globalIndexes) - - borrow := NewBorrowBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.UpdateHardBorrowIndexDenoms(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.BorrowRewardIndexes) -} - -func (suite *UpdateHardBorrowIndexDenomsTests) TestClaimIndexesAreUnchangedWhenBorrowedDenomsUnchanged() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - BorrowRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - // Set global indexes with same denoms but different values. - // UpdateHardBorrowIndexDenoms should ignore the new values. - suite.storeGlobalBorrowIndexes(increaseAllRewardFactors(claim.BorrowRewardIndexes)) - - borrow := NewBorrowBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(claim.BorrowRewardIndexes)...). - Build() - - suite.keeper.UpdateHardBorrowIndexDenoms(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(claim.BorrowRewardIndexes, syncedClaim.BorrowRewardIndexes) -} - -func (suite *UpdateHardBorrowIndexDenomsTests) TestEmptyClaimIndexesAreAddedForNewlyBorrowedButNotRewardedDenoms() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - BorrowRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - suite.storeGlobalBorrowIndexes(claim.BorrowRewardIndexes) - - // add a denom to the borrowed amount that is not in the global or claim's indexes - expectedIndexes := appendUniqueEmptyMultiRewardIndex(claim.BorrowRewardIndexes) - borrowedDenoms := extractCollateralTypes(expectedIndexes) - borrow := NewBorrowBuilder(claim.Owner). - WithArbitrarySourceShares(borrowedDenoms...). - Build() - - suite.keeper.UpdateHardBorrowIndexDenoms(suite.ctx, borrow) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(expectedIndexes, syncedClaim.BorrowRewardIndexes) -} diff --git a/x/incentive/keeper/rewards_delegator.go b/x/incentive/keeper/rewards_delegator.go deleted file mode 100644 index 47867f99..00000000 --- a/x/incentive/keeper/rewards_delegator.go +++ /dev/null @@ -1,208 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// AccumulateDelegatorRewards calculates new rewards to distribute this block and updates the global indexes to reflect this. -// The provided rewardPeriod must be valid to avoid panics in calculating time durations. -func (k Keeper) AccumulateDelegatorRewards(ctx sdk.Context, rewardPeriod types.MultiRewardPeriod) { - previousAccrualTime, found := k.GetPreviousDelegatorRewardAccrualTime(ctx, rewardPeriod.CollateralType) - if !found { - previousAccrualTime = ctx.BlockTime() - } - - indexes, found := k.GetDelegatorRewardIndexes(ctx, rewardPeriod.CollateralType) - if !found { - indexes = types.RewardIndexes{} - } - - acc := types.NewAccumulator(previousAccrualTime, indexes) - - totalSource := k.getDelegatorTotalSourceShares(ctx, rewardPeriod.CollateralType) - - acc.Accumulate(rewardPeriod, totalSource, ctx.BlockTime()) - - k.SetPreviousDelegatorRewardAccrualTime(ctx, rewardPeriod.CollateralType, acc.PreviousAccumulationTime) - if len(acc.Indexes) > 0 { - // the store panics when setting empty or nil indexes - k.SetDelegatorRewardIndexes(ctx, rewardPeriod.CollateralType, acc.Indexes) - } -} - -// getDelegatorTotalSourceShares fetches the sum of all source shares for a delegator reward. -// In the case of delegation, this is the total tokens staked to bonded validators. -func (k Keeper) getDelegatorTotalSourceShares(ctx sdk.Context, denom string) sdk.Dec { - totalBonded := k.stakingKeeper.TotalBondedTokens(ctx) - - return sdk.NewDecFromInt(totalBonded) -} - -// InitializeDelegatorReward initializes the reward index of a delegator claim -func (k Keeper) InitializeDelegatorReward(ctx sdk.Context, delegator sdk.AccAddress) { - claim, found := k.GetDelegatorClaim(ctx, delegator) - if !found { - claim = types.NewDelegatorClaim(delegator, sdk.Coins{}, nil) - } else { - k.SynchronizeDelegatorRewards(ctx, delegator, nil, false) - claim, _ = k.GetDelegatorClaim(ctx, delegator) - } - - var rewardIndexes types.MultiRewardIndexes - globalRewardIndexes, found := k.GetDelegatorRewardIndexes(ctx, types.BondDenom) - if !found { - globalRewardIndexes = types.RewardIndexes{} - } - rewardIndexes = rewardIndexes.With(types.BondDenom, globalRewardIndexes) - claim.RewardIndexes = rewardIndexes - k.SetDelegatorClaim(ctx, claim) -} - -// SynchronizeDelegatorClaim is a wrapper around SynchronizeDelegatorRewards that returns the synced claim -func (k Keeper) SynchronizeDelegatorClaim(ctx sdk.Context, claim types.DelegatorClaim) (types.DelegatorClaim, error) { - k.SynchronizeDelegatorRewards(ctx, claim.Owner, nil, false) - - claim, found := k.GetDelegatorClaim(ctx, claim.Owner) - if !found { - return claim, types.ErrClaimNotFound - } - return claim, nil -} - -// SynchronizeDelegatorRewards updates the claim object by adding any accumulated rewards, and setting the reward indexes to the global values. -// valAddr and shouldIncludeValidator are used to ignore or include delegations to a particular validator when summing up the total delegation. -// Normally only delegations to Bonded validators are included in the total. This is needed as staking hooks are sometimes called on the wrong -// side of a validator's state update (from this module's perspective). -func (k Keeper) SynchronizeDelegatorRewards(ctx sdk.Context, delegator sdk.AccAddress, valAddr sdk.ValAddress, shouldIncludeValidator bool) { - claim, found := k.GetDelegatorClaim(ctx, delegator) - if !found { - return - } - - globalRewardIndexes, found := k.GetDelegatorRewardIndexes(ctx, types.BondDenom) - if !found { - // The global factor is only not found if - // - the bond denom has not started accumulating rewards yet (either there is no reward specified in params, or the reward start time hasn't been hit) - // - OR it was wrongly deleted from state (factors should never be removed while unsynced claims exist) - // If not found we could either skip this sync, or assume the global factor is zero. - // Skipping will avoid storing unnecessary factors in the claim for non rewarded denoms. - // And in the event a global factor is wrongly deleted, it will avoid this function panicking when calculating rewards. - return - } - - userRewardIndexes, found := claim.RewardIndexes.Get(types.BondDenom) - if !found { - // Normally the reward indexes should always be found. - // However if there were no delegator rewards (ie no reward period in params) then a reward period is added, existing claims will not have the factor. - // So given the reward period was just added, assume the starting value for any global reward indexes, which is an empty slice. - userRewardIndexes = types.RewardIndexes{} - } - - totalDelegated := k.GetTotalDelegated(ctx, delegator, valAddr, shouldIncludeValidator) - - rewardsEarned, err := k.CalculateRewards(userRewardIndexes, globalRewardIndexes, totalDelegated) - if err != nil { - // Global reward factors should never decrease, as it would lead to a negative update to claim.Rewards. - // This panics if a global reward factor decreases or disappears between the old and new indexes. - panic(fmt.Sprintf("corrupted global reward indexes found: %v", err)) - } - - claim.Reward = claim.Reward.Add(rewardsEarned...) - claim.RewardIndexes = claim.RewardIndexes.With(types.BondDenom, globalRewardIndexes) - k.SetDelegatorClaim(ctx, claim) -} - -func (k Keeper) GetTotalDelegated(ctx sdk.Context, delegator sdk.AccAddress, valAddr sdk.ValAddress, shouldIncludeValidator bool) sdk.Dec { - totalDelegated := sdk.ZeroDec() - - delegations := k.stakingKeeper.GetDelegatorDelegations(ctx, delegator, 200) - for _, delegation := range delegations { - validator, found := k.stakingKeeper.GetValidator(ctx, delegation.GetValidatorAddr()) - if !found { - continue - } - - if validator.GetOperator().Equals(valAddr) { - if shouldIncludeValidator { - // do nothing, so the validator is included regardless of bonded status - } else { - // skip this validator - continue - } - } else { - // skip any not bonded validator - if validator.GetStatus() != stakingtypes.Bonded { - continue - } - } - - if validator.GetTokens().IsZero() { - continue - } - - delegatedTokens := validator.TokensFromShares(delegation.GetShares()) - if delegatedTokens.IsNegative() { - continue - } - totalDelegated = totalDelegated.Add(delegatedTokens) - } - return totalDelegated -} - -// SimulateDelegatorSynchronization calculates a user's outstanding delegator rewards by simulating reward synchronization -func (k Keeper) SimulateDelegatorSynchronization(ctx sdk.Context, claim types.DelegatorClaim) types.DelegatorClaim { - for _, ri := range claim.RewardIndexes { - // For each Delegator reward index (there's only one: the bond denom 'ukava') - globalRewardIndexes, foundGlobalRewardIndexes := k.GetDelegatorRewardIndexes(ctx, ri.CollateralType) - if !foundGlobalRewardIndexes { - continue - } - - userRewardIndexes, foundUserRewardIndexes := claim.RewardIndexes.GetRewardIndex(ri.CollateralType) - if !foundUserRewardIndexes { - continue - } - - userRewardIndexIndex, foundUserRewardIndexIndex := claim.RewardIndexes.GetRewardIndexIndex(ri.CollateralType) - if !foundUserRewardIndexIndex { - continue - } - - amtDelegated := k.GetTotalDelegated(ctx, claim.GetOwner(), sdk.ValAddress(claim.Owner.String()), true) - - for _, globalRewardIndex := range globalRewardIndexes { - userRewardIndex, foundUserRewardIndex := userRewardIndexes.RewardIndexes.GetRewardIndex(globalRewardIndex.CollateralType) - if !foundUserRewardIndex { - userRewardIndex = types.NewRewardIndex(globalRewardIndex.CollateralType, sdk.ZeroDec()) - userRewardIndexes.RewardIndexes = append(userRewardIndexes.RewardIndexes, userRewardIndex) - claim.RewardIndexes[userRewardIndexIndex].RewardIndexes = append(claim.RewardIndexes[userRewardIndexIndex].RewardIndexes, userRewardIndex) - } - - globalRewardFactor := globalRewardIndex.RewardFactor - userRewardFactor := userRewardIndex.RewardFactor - rewardsAccumulatedFactor := globalRewardFactor.Sub(userRewardFactor) - if rewardsAccumulatedFactor.IsZero() { - continue - } - - rewardsEarned := rewardsAccumulatedFactor.Mul(amtDelegated).RoundInt() - if rewardsEarned.IsZero() || rewardsEarned.IsNegative() { - continue - } - - factorIndex, foundFactorIndex := userRewardIndexes.RewardIndexes.GetFactorIndex(globalRewardIndex.CollateralType) - if !foundFactorIndex { - continue - } - claim.RewardIndexes[userRewardIndexIndex].RewardIndexes[factorIndex].RewardFactor = globalRewardIndex.RewardFactor - newRewardsCoin := sdk.NewCoin(userRewardIndex.CollateralType, rewardsEarned) - claim.Reward = claim.Reward.Add(newRewardsCoin) - } - } - return claim -} diff --git a/x/incentive/keeper/rewards_delegator_accum_test.go b/x/incentive/keeper/rewards_delegator_accum_test.go deleted file mode 100644 index 2e586dbe..00000000 --- a/x/incentive/keeper/rewards_delegator_accum_test.go +++ /dev/null @@ -1,307 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -type AccumulateDelegatorRewardsTests struct { - unitTester -} - -func (suite *AccumulateDelegatorRewardsTests) storedTimeEquals(denom string, expected time.Time) { - storedTime, found := suite.keeper.GetPreviousDelegatorRewardAccrualTime(suite.ctx, denom) - suite.True(found) - suite.Equal(expected, storedTime) -} - -func (suite *AccumulateDelegatorRewardsTests) storedIndexesEqual(denom string, expected types.RewardIndexes) { - storedIndexes, found := suite.keeper.GetDelegatorRewardIndexes(suite.ctx, denom) - suite.Equal(found, expected != nil) - - if found { - suite.Equal(expected, storedIndexes) - } else { - suite.Empty(storedIndexes) - } -} - -func TestAccumulateDelegatorRewards(t *testing.T) { - suite.Run(t, new(AccumulateDelegatorRewardsTests)) -} - -func (suite *AccumulateDelegatorRewardsTests) TestStateUpdatedWhenBlockTimeHasIncreased() { - stakingKeeper := newFakeStakingKeeper().addBondedTokens(1e6) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - suite.storeGlobalDelegatorIndexes(types.MultiRewardIndexes{ - { - CollateralType: types.BondDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - }) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousDelegatorRewardAccrualTime(suite.ctx, types.BondDenom, previousAccrualTime) - - newAccrualTime := previousAccrualTime.Add(1 * time.Hour) - suite.ctx = suite.ctx.WithBlockTime(newAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - types.BondDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateDelegatorRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(types.BondDenom, newAccrualTime) - suite.storedIndexesEqual(types.BondDenom, types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("7.22"), - }, - { - CollateralType: "ukava", - RewardFactor: d("3.64"), - }, - }) -} - -func (suite *AccumulateDelegatorRewardsTests) TestStateUnchangedWhenBlockTimeHasNotIncreased() { - stakingKeeper := newFakeStakingKeeper().addBondedTokens(1e6) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: types.BondDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalDelegatorIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousDelegatorRewardAccrualTime(suite.ctx, types.BondDenom, previousAccrualTime) - - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - types.BondDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateDelegatorRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(types.BondDenom, previousAccrualTime) - expected, f := previousIndexes.Get(types.BondDenom) - suite.True(f) - suite.storedIndexesEqual(types.BondDenom, expected) -} - -func (suite *AccumulateDelegatorRewardsTests) TestNoAccumulationWhenSourceSharesAreZero() { - stakingKeeper := newFakeStakingKeeper() // zero total bonded - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: types.BondDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalDelegatorIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousDelegatorRewardAccrualTime(suite.ctx, types.BondDenom, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(7 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - types.BondDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateDelegatorRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(types.BondDenom, firstAccrualTime) - expected, f := previousIndexes.Get(types.BondDenom) - suite.True(f) - suite.storedIndexesEqual(types.BondDenom, expected) -} - -func (suite *AccumulateDelegatorRewardsTests) TestStateAddedWhenStateDoesNotExist() { - stakingKeeper := newFakeStakingKeeper().addBondedTokens(1e6) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - period := types.NewMultiRewardPeriod( - true, - types.BondDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), - ) - - firstAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateDelegatorRewards(suite.ctx, period) - - // After the first accumulation only the current block time should be stored. - // The indexes will be empty as no time has passed since the previous block because it didn't exist. - suite.storedTimeEquals(types.BondDenom, firstAccrualTime) - suite.storedIndexesEqual(types.BondDenom, nil) - - secondAccrualTime := firstAccrualTime.Add(10 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(secondAccrualTime) - - suite.keeper.AccumulateDelegatorRewards(suite.ctx, period) - - // After the second accumulation both current block time and indexes should be stored. - suite.storedTimeEquals(types.BondDenom, secondAccrualTime) - suite.storedIndexesEqual(types.BondDenom, types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.01"), - }, - }) -} - -func (suite *AccumulateDelegatorRewardsTests) TestNoPanicWhenStateDoesNotExist() { - stakingKeeper := newFakeStakingKeeper() - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - period := types.NewMultiRewardPeriod( - true, - types.BondDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(), - ) - - accrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(accrualTime) - - // Accumulate with no source shares and no rewards per second will result in no increment to the indexes. - // No increment and no previous indexes stored, results in an updated of nil. Setting this in the state panics. - // Check there is no panic. - suite.NotPanics(func() { - suite.keeper.AccumulateDelegatorRewards(suite.ctx, period) - }) - - suite.storedTimeEquals(types.BondDenom, accrualTime) - suite.storedIndexesEqual(types.BondDenom, nil) -} - -func (suite *AccumulateDelegatorRewardsTests) TestNoAccumulationWhenBeforeStartTime() { - stakingKeeper := newFakeStakingKeeper().addBondedTokens(1e6) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: types.BondDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalDelegatorIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousDelegatorRewardAccrualTime(suite.ctx, types.BondDenom, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(10 * time.Second) - - period := types.NewMultiRewardPeriod( - true, - types.BondDenom, - firstAccrualTime.Add(time.Nanosecond), // start time after accrual time - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateDelegatorRewards(suite.ctx, period) - - // The accrual time should be updated, but the indexes unchanged - suite.storedTimeEquals(types.BondDenom, firstAccrualTime) - expectedIndexes, f := previousIndexes.Get(types.BondDenom) - suite.True(f) - suite.storedIndexesEqual(types.BondDenom, expectedIndexes) -} - -func (suite *AccumulateDelegatorRewardsTests) TestPanicWhenCurrentTimeLessThanPrevious() { - stakingKeeper := newFakeStakingKeeper().addBondedTokens(1e6) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousDelegatorRewardAccrualTime(suite.ctx, types.BondDenom, previousAccrualTime) - - firstAccrualTime := time.Time{} - - period := types.NewMultiRewardPeriod( - true, - types.BondDenom, - time.Time{}, // start time after accrual time - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.Panics(func() { - suite.keeper.AccumulateDelegatorRewards(suite.ctx, period) - }) -} diff --git a/x/incentive/keeper/rewards_delegator_init_test.go b/x/incentive/keeper/rewards_delegator_init_test.go deleted file mode 100644 index 84ece1a8..00000000 --- a/x/incentive/keeper/rewards_delegator_init_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package keeper_test - -import ( - "testing" - - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// InitializeDelegatorRewardTests runs unit tests for the keeper.InitializeDelegatorReward method -// -// inputs -// - claim in store if it exists (only claim.DelegatorRewardIndexes) -// - global indexes in store -// - delegator function arg -// -// outputs -// - sets or creates a claim -type InitializeDelegatorRewardTests struct { - unitTester -} - -func TestInitializeDelegatorReward(t *testing.T) { - suite.Run(t, new(InitializeDelegatorRewardTests)) -} - -// Hardcoded to use bond denom -func (suite *InitializeDelegatorRewardTests) storeGlobalDelegatorFactor(multiRewardIndexes types.MultiRewardIndexes) { - multiRewardIndex, _ := multiRewardIndexes.GetRewardIndex(types.BondDenom) - suite.keeper.SetDelegatorRewardIndexes(suite.ctx, types.BondDenom, multiRewardIndex.RewardIndexes) -} - -func (suite *InitializeDelegatorRewardTests) TestClaimIndexesAreSetWhenClaimDoesNotExist() { - globalIndex := arbitraryDelegatorRewardIndexes - suite.storeGlobalDelegatorIndexes(globalIndex) - - delegator := arbitraryAddress() - suite.keeper.InitializeDelegatorReward(suite.ctx, delegator) - - syncedClaim, f := suite.keeper.GetDelegatorClaim(suite.ctx, delegator) - suite.True(f) - suite.Equal(globalIndex, syncedClaim.RewardIndexes) -} - -func (suite *InitializeDelegatorRewardTests) TestClaimIsSyncedAndIndexesAreSetWhenClaimDoesExist() { - validatorAddress := arbitraryValidatorAddress() - sk := &fakeStakingKeeper{ - delegations: stakingtypes.Delegations{{ - ValidatorAddress: validatorAddress.String(), - Shares: d("1000"), - }}, - validators: stakingtypes.Validators{{ - OperatorAddress: validatorAddress.String(), - Status: stakingtypes.Bonded, - Tokens: i(1000), - DelegatorShares: d("1000"), - }}, - } - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, sk, nil, nil, nil, nil) - - claim := types.DelegatorClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - RewardIndexes: arbitraryDelegatorRewardIndexes, - } - suite.storeDelegatorClaim(claim) - - // Set the global factor to a value different to one in claim so - // we can detect if it is overwritten. - rewardIndexes, _ := claim.RewardIndexes.Get(types.BondDenom) - globalIndexes := increaseRewardFactors(rewardIndexes) - - // Update the claim object with the new global factor - bondIndex, _ := claim.RewardIndexes.GetRewardIndexIndex(types.BondDenom) - claim.RewardIndexes[bondIndex].RewardIndexes = globalIndexes - suite.storeGlobalDelegatorFactor(claim.RewardIndexes) - - suite.keeper.InitializeDelegatorReward(suite.ctx, claim.Owner) - - syncedClaim, _ := suite.keeper.GetDelegatorClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.RewardIndexes[bondIndex].RewardIndexes) - suite.Truef(syncedClaim.Reward.IsAllGT(claim.Reward), "'%s' not greater than '%s'", syncedClaim.Reward, claim.Reward) -} - -// arbitraryDelegatorRewardIndexes contains only one reward index as there is only ever one bond denom -var arbitraryDelegatorRewardIndexes = types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - types.BondDenom, - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.2")), - types.NewRewardIndex("swp", d("0.2")), - }, - ), -} diff --git a/x/incentive/keeper/rewards_delegator_sync_test.go b/x/incentive/keeper/rewards_delegator_sync_test.go deleted file mode 100644 index e2f9b898..00000000 --- a/x/incentive/keeper/rewards_delegator_sync_test.go +++ /dev/null @@ -1,396 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// SynchronizeDelegatorRewardTests runs unit tests for the keeper.SynchronizeDelegatorReward method -// -// inputs -// - claim in store if it exists (only claim.DelegatorRewardIndexes and claim.Reward) -// - global index in store -// - function args: delegator address, validator address, shouldIncludeValidator flag -// - delegator's delegations and the corresponding validators -// -// outputs -// - sets or creates a claim -type SynchronizeDelegatorRewardTests struct { - unitTester -} - -func TestSynchronizeDelegatorReward(t *testing.T) { - suite.Run(t, new(SynchronizeDelegatorRewardTests)) -} - -func (suite *SynchronizeDelegatorRewardTests) storeGlobalDelegatorFactor(multiRewardIndexes types.MultiRewardIndexes) { - multiRewardIndex, _ := multiRewardIndexes.GetRewardIndex(types.BondDenom) - suite.keeper.SetDelegatorRewardIndexes(suite.ctx, types.BondDenom, multiRewardIndex.RewardIndexes) -} - -func (suite *SynchronizeDelegatorRewardTests) TestClaimIndexesAreUnchangedWhenGlobalFactorUnchanged() { - delegator := arbitraryAddress() - - stakingKeeper := &fakeStakingKeeper{} // use an empty staking keeper that returns no delegations - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - claim := types.DelegatorClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: delegator, - }, - RewardIndexes: arbitraryDelegatorRewardIndexes, - } - suite.storeDelegatorClaim(claim) - - suite.storeGlobalDelegatorFactor(claim.RewardIndexes) - - suite.keeper.SynchronizeDelegatorRewards(suite.ctx, claim.Owner, nil, false) - - syncedClaim, _ := suite.keeper.GetDelegatorClaim(suite.ctx, claim.Owner) - suite.Equal(claim.RewardIndexes, syncedClaim.RewardIndexes) -} - -func (suite *SynchronizeDelegatorRewardTests) TestClaimIndexesAreUpdatedWhenGlobalFactorIncreased() { - delegator := arbitraryAddress() - - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, &fakeStakingKeeper{}, nil, nil, nil, nil) - - claim := types.DelegatorClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: delegator, - }, - RewardIndexes: arbitraryDelegatorRewardIndexes, - } - suite.storeDelegatorClaim(claim) - - rewardIndexes, _ := claim.RewardIndexes.Get(types.BondDenom) - globalIndexes := increaseRewardFactors(rewardIndexes) - - // Update the claim object with the new global factor - bondIndex, _ := claim.RewardIndexes.GetRewardIndexIndex(types.BondDenom) - claim.RewardIndexes[bondIndex].RewardIndexes = globalIndexes - suite.storeGlobalDelegatorFactor(claim.RewardIndexes) - - suite.keeper.SynchronizeDelegatorRewards(suite.ctx, claim.Owner, nil, false) - - syncedClaim, _ := suite.keeper.GetDelegatorClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.RewardIndexes[bondIndex].RewardIndexes) -} - -func (suite *SynchronizeDelegatorRewardTests) TestRewardIsUnchangedWhenGlobalFactorUnchanged() { - delegator := arbitraryAddress() - validatorAddress := arbitraryValidatorAddress() - stakingKeeper := &fakeStakingKeeper{ - delegations: stakingtypes.Delegations{ - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddress.String(), - Shares: d("1000"), - }, - }, - validators: stakingtypes.Validators{ - unslashedBondedValidator(validatorAddress), - }, - } - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - claim := types.DelegatorClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: delegator, - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{{ - CollateralType: types.BondDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", RewardFactor: d("0.1"), - }, - { - CollateralType: "swp", RewardFactor: d("0.2"), - }, - }, - }}, - } - suite.storeDelegatorClaim(claim) - - suite.storeGlobalDelegatorFactor(claim.RewardIndexes) - - suite.keeper.SynchronizeDelegatorRewards(suite.ctx, claim.Owner, nil, false) - - syncedClaim, _ := suite.keeper.GetDelegatorClaim(suite.ctx, claim.Owner) - - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *SynchronizeDelegatorRewardTests) TestRewardIsIncreasedWhenNewRewardAdded() { - delegator := arbitraryAddress() - validatorAddress := arbitraryValidatorAddress() - stakingKeeper := &fakeStakingKeeper{ - delegations: stakingtypes.Delegations{ - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddress.String(), - Shares: d("1000"), - }, - }, - validators: stakingtypes.Validators{ - unslashedBondedValidator(validatorAddress), - }, - } - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - claim := types.DelegatorClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: delegator, - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{}, - } - suite.storeDelegatorClaim(claim) - - newGlobalIndexes := types.MultiRewardIndexes{{ - CollateralType: types.BondDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", RewardFactor: d("0.1"), - }, - { - CollateralType: "swp", RewardFactor: d("0.2"), - }, - }, - }} - suite.storeGlobalDelegatorIndexes(newGlobalIndexes) - - suite.keeper.SynchronizeDelegatorRewards(suite.ctx, claim.Owner, nil, false) - - syncedClaim, _ := suite.keeper.GetDelegatorClaim(suite.ctx, claim.Owner) - - suite.Equal(newGlobalIndexes, syncedClaim.RewardIndexes) - suite.Equal( - cs(c("hard", 100), c("swp", 200)).Add(claim.Reward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeDelegatorRewardTests) TestRewardIsIncreasedWhenGlobalFactorIncreased() { - delegator := arbitraryAddress() - validatorAddress := arbitraryValidatorAddress() - stakingKeeper := &fakeStakingKeeper{ - delegations: stakingtypes.Delegations{ - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddress.String(), - Shares: d("1000"), - }, - }, - validators: stakingtypes.Validators{ - unslashedBondedValidator(validatorAddress), - }, - } - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - claim := types.DelegatorClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: delegator, - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{{ - CollateralType: types.BondDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", RewardFactor: d("0.1"), - }, - { - CollateralType: "swp", RewardFactor: d("0.2"), - }, - }, - }}, - } - suite.storeDelegatorClaim(claim) - - suite.storeGlobalDelegatorIndexes( - types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - types.BondDenom, - types.RewardIndexes{ - { - CollateralType: "hard", RewardFactor: d("0.2"), - }, - { - CollateralType: "swp", RewardFactor: d("0.4"), - }, - }, - ), - }, - ) - - suite.keeper.SynchronizeDelegatorRewards(suite.ctx, claim.Owner, nil, false) - - syncedClaim, _ := suite.keeper.GetDelegatorClaim(suite.ctx, claim.Owner) - - suite.Equal( - cs(c("hard", 100), c("swp", 200)).Add(claim.Reward...), - syncedClaim.Reward, - ) -} - -func unslashedBondedValidator(address sdk.ValAddress) stakingtypes.Validator { - return stakingtypes.Validator{ - OperatorAddress: address.String(), - Status: stakingtypes.Bonded, - - // Set the tokens and shares equal so then - // a _delegator's_ token amount is equal to their shares amount - Tokens: i(1e12), - DelegatorShares: sdk.NewDec(1e12), - } -} - -func unslashedNotBondedValidator(address sdk.ValAddress) stakingtypes.Validator { - return stakingtypes.Validator{ - OperatorAddress: address.String(), - Status: stakingtypes.Unbonding, - - // Set the tokens and shares equal so then - // a _delegator's_ token amount is equal to their shares amount - Tokens: i(1e12), - DelegatorShares: sdk.NewDec(1e12), - } -} - -func (suite *SynchronizeDelegatorRewardTests) TestGetDelegatedWhenValAddrIsNil() { - // when valAddr is nil, get total delegated to bonded validators - delegator := arbitraryAddress() - validatorAddresses := generateValidatorAddresses(4) - stakingKeeper := &fakeStakingKeeper{ - delegations: stakingtypes.Delegations{ - // bonded - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[0].String(), - Shares: d("1"), - }, - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[1].String(), - Shares: d("10"), - }, - // not bonded - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[2].String(), - Shares: d("100"), - }, - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[3].String(), - Shares: d("1000"), - }, - }, - validators: stakingtypes.Validators{ - unslashedBondedValidator(validatorAddresses[0]), - unslashedBondedValidator(validatorAddresses[1]), - unslashedNotBondedValidator(validatorAddresses[2]), - unslashedNotBondedValidator(validatorAddresses[3]), - }, - } - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - suite.Equal( - d("11"), // delegation to bonded validators - suite.keeper.GetTotalDelegated(suite.ctx, delegator, nil, false), - ) -} - -func (suite *SynchronizeDelegatorRewardTests) TestGetDelegatedWhenExcludingAValidator() { - // when valAddr is x, get total delegated to bonded validators excluding those to x - delegator := arbitraryAddress() - validatorAddresses := generateValidatorAddresses(4) - stakingKeeper := &fakeStakingKeeper{ - delegations: stakingtypes.Delegations{ - // bonded - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[0].String(), - Shares: d("1"), - }, - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[1].String(), - Shares: d("10"), - }, - // not bonded - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[2].String(), - Shares: d("100"), - }, - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[3].String(), - Shares: d("1000"), - }, - }, - validators: stakingtypes.Validators{ - unslashedBondedValidator(validatorAddresses[0]), - unslashedBondedValidator(validatorAddresses[1]), - unslashedNotBondedValidator(validatorAddresses[2]), - unslashedNotBondedValidator(validatorAddresses[3]), - }, - } - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - suite.Equal( - d("10"), - suite.keeper.GetTotalDelegated(suite.ctx, delegator, validatorAddresses[0], false), - ) -} - -func (suite *SynchronizeDelegatorRewardTests) TestGetDelegatedWhenIncludingAValidator() { - // when valAddr is x, get total delegated to bonded validators including those to x - delegator := arbitraryAddress() - validatorAddresses := generateValidatorAddresses(4) - stakingKeeper := &fakeStakingKeeper{ - delegations: stakingtypes.Delegations{ - // bonded - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[0].String(), - Shares: d("1"), - }, - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[1].String(), - Shares: d("10"), - }, - // not bonded - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[2].String(), - Shares: d("100"), - }, - { - DelegatorAddress: delegator.String(), - ValidatorAddress: validatorAddresses[3].String(), - Shares: d("1000"), - }, - }, - validators: stakingtypes.Validators{ - unslashedBondedValidator(validatorAddresses[0]), - unslashedBondedValidator(validatorAddresses[1]), - unslashedNotBondedValidator(validatorAddresses[2]), - unslashedNotBondedValidator(validatorAddresses[3]), - }, - } - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, stakingKeeper, nil, nil, nil, nil) - - suite.Equal( - d("111"), - suite.keeper.GetTotalDelegated(suite.ctx, delegator, validatorAddresses[2], true), - ) -} diff --git a/x/incentive/keeper/rewards_delegator_test.go b/x/incentive/keeper/rewards_delegator_test.go deleted file mode 100644 index 75238e13..00000000 --- a/x/incentive/keeper/rewards_delegator_test.go +++ /dev/null @@ -1,796 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/incentive/keeper" - "github.com/0glabs/0g-chain/x/incentive/testutil" - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// Test suite used for all keeper tests -type DelegatorRewardsTestSuite struct { - suite.Suite - - keeper keeper.Keeper - stakingKeeper *stakingkeeper.Keeper - - app app.TestApp - ctx sdk.Context - - genesisTime time.Time - addrs []sdk.AccAddress - validatorAddrs []sdk.ValAddress -} - -// SetupTest is run automatically before each suite test -func (suite *DelegatorRewardsTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - _, allAddrs := app.GeneratePrivKeyAddressPairs(10) - suite.addrs = allAddrs[:5] - for _, a := range allAddrs[5:] { - suite.validatorAddrs = append(suite.validatorAddrs, sdk.ValAddress(a)) - } - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *DelegatorRewardsTestSuite) SetupApp() { - suite.app = app.NewTestApp() - - suite.keeper = suite.app.GetIncentiveKeeper() - suite.stakingKeeper = suite.app.GetStakingKeeper() - - suite.ctx = suite.app.NewContext(true, tmproto.Header{Height: 1, Time: suite.genesisTime, ChainID: app.TestChainId}) -} - -func (suite *DelegatorRewardsTestSuite) SetupWithGenState(authBuilder *app.AuthBankGenesisBuilder, incentBuilder testutil.IncentiveGenesisBuilder) { - suite.SetupApp() - - suite.app.InitializeFromGenesisStatesWithTime( - suite.genesisTime, - authBuilder.BuildMarshalled(suite.app.AppCodec()), - NewStakingGenesisState(suite.app.AppCodec()), - incentBuilder.BuildMarshalled(suite.app.AppCodec()), - ) -} - -func (suite *DelegatorRewardsTestSuite) TestAccumulateDelegatorRewards() { - type args struct { - delegation sdk.Coin - rewardsPerSecond sdk.Coins - timeElapsed int - expectedRewardIndexes types.RewardIndexes - } - type test struct { - name string - args args - } - testCases := []test{ - { - "7 seconds", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 7, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.428239000000000000")), - }, - }, - }, - { - "1 day", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 86400, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("5285.692800000000000000")), - }, - }, - }, - { - "0 seconds", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 0, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - }, - }, - }, - { - "multiple reward coins", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354), c("swp", 567889)), - timeElapsed: 7, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.428239000000000000")), - types.NewRewardIndex("swp", d("1.987611500000000000")), - }, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[0], cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[0]), cs(c("ukava", 1e9))) - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleDelegatorRewardPeriod(tc.args.delegation.Denom, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder) - - err := suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[0], tc.args.delegation) - suite.Require().NoError(err) - err = suite.deliverMsgDelegate(suite.ctx, suite.addrs[0], suite.validatorAddrs[0], tc.args.delegation) - suite.Require().NoError(err) - - // Delete genesis validator to not influence rewards - suite.app.DeleteGenesisValidator(suite.T(), suite.ctx) - - staking.EndBlocker(suite.ctx, suite.stakingKeeper) - - // Set up chain context at future time - runAtTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed)) - runCtx := suite.ctx.WithBlockTime(runAtTime) - - rewardPeriods, found := suite.keeper.GetDelegatorRewardPeriods(runCtx, tc.args.delegation.Denom) - suite.Require().True(found) - suite.keeper.AccumulateDelegatorRewards(runCtx, rewardPeriods) - - rewardIndexes, _ := suite.keeper.GetDelegatorRewardIndexes(runCtx, tc.args.delegation.Denom) - suite.Require().Equal(tc.args.expectedRewardIndexes, rewardIndexes) - }) - } -} - -func (suite *DelegatorRewardsTestSuite) TestSynchronizeDelegatorReward() { - type args struct { - delegation sdk.Coin - rewardsPerSecond sdk.Coins - blockTimes []int - expectedRewardIndexes types.RewardIndexes - expectedRewards sdk.Coins - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "10 blocks", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("6.117700000000000000")), - }, - expectedRewards: cs(c("hard", 6117700)), - }, - }, - { - "10 blocks - long block time", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("52856.928000000000000000")), - }, - expectedRewards: cs(c("hard", 52856928000)), - }, - }, - { - "delegator reward index updated when reward is zero", - args{ - delegation: c("ukava", 1), - rewardsPerSecond: cs(c("hard", 1)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.000099999900000100")), - }, - expectedRewards: nil, - }, - }, - { - "multiple reward coins", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354), c("swp", 56789)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("6.117700000000000000")), - types.NewRewardIndex("swp", d("2.839450000000000000")), - }, - expectedRewards: cs(c("hard", 6117700), c("swp", 2839450)), - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[0], cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[0]), cs(c("ukava", 1e9))) - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleDelegatorRewardPeriod(tc.args.delegation.Denom, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder) - - // Create validator account - staking.BeginBlocker(suite.ctx, suite.stakingKeeper) - selfDelegationCoins := c("ukava", 1_000_000) - err := suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[0], selfDelegationCoins) - suite.Require().NoError(err) - staking.EndBlocker(suite.ctx, suite.stakingKeeper) - - // Delete genesis validator to not influence rewards - suite.app.DeleteGenesisValidator(suite.T(), suite.ctx) - - // Delegator delegates - err = suite.deliverMsgDelegate(suite.ctx, suite.addrs[0], suite.validatorAddrs[0], tc.args.delegation) - suite.Require().NoError(err) - - // Check that validator account has been created and delegation was successful - valAcc, found := suite.stakingKeeper.GetValidator(suite.ctx, suite.validatorAddrs[0]) - suite.True(found) - suite.Require().Equal(valAcc.Status, stakingtypes.Bonded) - suite.Require().Equal(valAcc.Tokens, tc.args.delegation.Amount.Add(selfDelegationCoins.Amount)) - - // Check that Staking hooks initialized a DelegatorClaim - claim, found := suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - for _, rewardIndex := range claim.RewardIndexes[0].RewardIndexes { - suite.Require().Equal(sdk.ZeroDec(), rewardIndex.RewardFactor) - } - - // Run accumulator at several intervals - var timeElapsed int - previousBlockTime := suite.ctx.BlockTime() - for _, t := range tc.args.blockTimes { - timeElapsed += t - updatedBlockTime := previousBlockTime.Add(time.Duration(int(time.Second) * t)) - previousBlockTime = updatedBlockTime - blockCtx := suite.ctx.WithBlockTime(updatedBlockTime) - - rewardPeriods, found := suite.keeper.GetDelegatorRewardPeriods(blockCtx, tc.args.delegation.Denom) - suite.Require().True(found) - - suite.keeper.AccumulateDelegatorRewards(blockCtx, rewardPeriods) - } - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - - // After we've accumulated, run synchronize - suite.Require().NotPanics(func() { - suite.keeper.SynchronizeDelegatorRewards(suite.ctx, suite.addrs[0], nil, false) - }) - - // Check that reward factor and claim have been updated as expected - rewardIndexes, _ := suite.keeper.GetDelegatorRewardIndexes(suite.ctx, tc.args.delegation.Denom) - for i, rewardPerSecond := range tc.args.rewardsPerSecond { - rewardFactor, _ := rewardIndexes.Get(rewardPerSecond.Denom) - suite.Require().Equal(tc.args.expectedRewardIndexes[i].RewardFactor, rewardFactor) - } - - claim, found = suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - for i, delegatorRewardIndex := range claim.RewardIndexes[0].RewardIndexes { - suite.Require().Equal(tc.args.expectedRewardIndexes[i].RewardFactor, delegatorRewardIndex.RewardFactor) - } - suite.Require().Equal(tc.args.expectedRewards, claim.Reward) - }) - } -} - -func (suite *DelegatorRewardsTestSuite) TestSimulateDelegatorRewardSynchronization() { - type args struct { - delegation sdk.Coin - rewardsPerSecond sdk.Coins - blockTimes []int - expectedRewardIndexes types.RewardIndexes - expectedRewards sdk.Coins - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "10 blocks", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("6.117700000000000000"))}, - expectedRewards: cs(c("hard", 6117700)), - }, - }, - { - "10 blocks - long block time", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("52856.928000000000000000"))}, - expectedRewards: cs(c("hard", 52856928000)), - }, - }, - { - "multiple rewards coins", - args{ - delegation: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354), c("swp", 56789)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("6.117700000000000000")), - types.NewRewardIndex("swp", d("2.839450000000000000")), - }, - expectedRewards: cs(c("hard", 6117700), c("swp", 2839450)), - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[0], cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[0]), cs(c("ukava", 1e9))) - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleDelegatorRewardPeriod(tc.args.delegation.Denom, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder) - - // Delegator delegates - err := suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[0], tc.args.delegation) - suite.Require().NoError(err) - err = suite.deliverMsgDelegate(suite.ctx, suite.addrs[0], suite.validatorAddrs[0], tc.args.delegation) - suite.Require().NoError(err) - - // Delete genesis validator to not influence rewards - suite.app.DeleteGenesisValidator(suite.T(), suite.ctx) - - staking.EndBlocker(suite.ctx, suite.stakingKeeper) - - // Check that Staking hooks initialized a DelegatorClaim - claim, found := suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - for _, rewardIndex := range claim.RewardIndexes[0].RewardIndexes { - suite.Require().Equal(sdk.ZeroDec(), rewardIndex.RewardFactor) - } - - // Run accumulator at several intervals - var timeElapsed int - previousBlockTime := suite.ctx.BlockTime() - for _, t := range tc.args.blockTimes { - timeElapsed += t - updatedBlockTime := previousBlockTime.Add(time.Duration(int(time.Second) * t)) - previousBlockTime = updatedBlockTime - blockCtx := suite.ctx.WithBlockTime(updatedBlockTime) - - // Accumulate delegator rewards - rewardPeriods, found := suite.keeper.GetDelegatorRewardPeriods(blockCtx, tc.args.delegation.Denom) - suite.Require().True(found) - suite.keeper.AccumulateDelegatorRewards(blockCtx, rewardPeriods) - } - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - - // Check that the synced claim held in memory has properly simulated syncing - syncedClaim := suite.keeper.SimulateDelegatorSynchronization(suite.ctx, claim) - - for i, expectedRewardIndex := range tc.args.expectedRewardIndexes { - // Check that the user's claim's reward index matches the expected reward index - multiRewardIndex, found := syncedClaim.RewardIndexes.Get(types.BondDenom) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, multiRewardIndex[i]) - - // Check that the user's claim holds the expected amount of reward coins - suite.Require().Equal( - tc.args.expectedRewards.AmountOf(expectedRewardIndex.CollateralType), - syncedClaim.Reward.AmountOf(expectedRewardIndex.CollateralType), - ) - } - }) - } -} - -func (suite *DelegatorRewardsTestSuite) deliverMsgCreateValidator(ctx sdk.Context, address sdk.ValAddress, selfDelegation sdk.Coin) error { - msg, err := stakingtypes.NewMsgCreateValidator( - address, - ed25519.GenPrivKey().PubKey(), - selfDelegation, - stakingtypes.Description{}, - stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - sdkmath.NewInt(1_000_000), - ) - if err != nil { - return err - } - - msgServer := stakingkeeper.NewMsgServerImpl(suite.stakingKeeper) - _, err = msgServer.CreateValidator(sdk.WrapSDKContext(suite.ctx), msg) - return err -} - -func (suite *DelegatorRewardsTestSuite) deliverMsgDelegate(ctx sdk.Context, delegator sdk.AccAddress, validator sdk.ValAddress, amount sdk.Coin) error { - msg := stakingtypes.NewMsgDelegate( - delegator, - validator, - amount, - ) - - msgServer := stakingkeeper.NewMsgServerImpl(suite.stakingKeeper) - _, err := msgServer.Delegate(sdk.WrapSDKContext(suite.ctx), msg) - return err -} - -func (suite *DelegatorRewardsTestSuite) deliverMsgRedelegate(ctx sdk.Context, delegator sdk.AccAddress, sourceValidator, destinationValidator sdk.ValAddress, amount sdk.Coin) error { - msg := stakingtypes.NewMsgBeginRedelegate( - delegator, - sourceValidator, - destinationValidator, - amount, - ) - - msgServer := stakingkeeper.NewMsgServerImpl(suite.stakingKeeper) - _, err := msgServer.BeginRedelegate(sdk.WrapSDKContext(suite.ctx), msg) - return err -} - -// given a user has a delegation to a bonded validator, when the validator starts unbonding, the user does not accumulate rewards -func (suite *DelegatorRewardsTestSuite) TestUnbondingValidatorSyncsClaim() { - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[0], cs(c("ukava", 1e9))). - WithSimpleAccount(suite.addrs[2], cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[0]), cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[1]), cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[2]), cs(c("ukava", 1e9))) - - rewardsPerSecond := cs(c("hard", 122354)) - bondDenom := "ukava" - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleDelegatorRewardPeriod(bondDenom, rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder) - - blockDuration := 10 * time.Second - - // Reduce the size of the validator set - stakingParams := suite.app.GetStakingKeeper().GetParams(suite.ctx) - stakingParams.MaxValidators = 2 - suite.app.GetStakingKeeper().SetParams(suite.ctx, stakingParams) - - // Create 3 validators - err := suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[0], c(bondDenom, 10_000_000)) - suite.Require().NoError(err) - err = suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[1], c(bondDenom, 5_000_000)) - suite.Require().NoError(err) - err = suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[2], c(bondDenom, 1_000_000)) - suite.Require().NoError(err) - - // End the block so top validators become bonded - _ = suite.app.EndBlocker(suite.ctx, abci.RequestEndBlock{}) - - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime.Add(1 * blockDuration)) - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}) // height and time in header are ignored by module begin blockers - - // Delegate to a bonded validator from the test user. This will initialize their incentive claim. - err = suite.deliverMsgDelegate(suite.ctx, suite.addrs[0], suite.validatorAddrs[1], c(bondDenom, 1_000_000)) - suite.Require().NoError(err) - - // Start a new block to accumulate some delegation rewards for the user. - _ = suite.app.EndBlocker(suite.ctx, abci.RequestEndBlock{}) - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime.Add(2 * blockDuration)) - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}) // height and time in header are ignored by module begin blockers - - // Delegate to the unbonded validator to push it into the bonded validator set, pushing out the user's delegated validator - err = suite.deliverMsgDelegate(suite.ctx, suite.addrs[2], suite.validatorAddrs[2], c(bondDenom, 8_000_000)) - suite.Require().NoError(err) - - // End the block to start unbonding the user's validator - _ = suite.app.EndBlocker(suite.ctx, abci.RequestEndBlock{}) - // but don't start the next block as it will accumulate delegator rewards and we won't be able to tell if the user's reward was synced. - - // Check that the user's claim has been synced. ie rewards added, index updated - claim, found := suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - - rewardIndexes, found := suite.keeper.GetDelegatorRewardIndexes(suite.ctx, bondDenom) - suite.Require().True(found) - globalIndex, found := rewardIndexes.Get(rewardsPerSecond[0].Denom) - suite.Require().True(found) - claimIndex, found := claim.RewardIndexes.GetRewardIndex(bondDenom) - suite.Require().True(found) - suite.Require().Equal(globalIndex, claimIndex.RewardIndexes[0].RewardFactor) - - suite.Require().Equal( - cs(c(rewardsPerSecond[0].Denom, 76471)), - claim.Reward, - ) - - // Run another block and check the claim is not accumulating more rewards - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime.Add(3 * blockDuration)) - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}) - - suite.keeper.SynchronizeDelegatorRewards(suite.ctx, suite.addrs[0], nil, false) - - // rewards are the same as before - laterClaim, found := suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - suite.Require().Equal(claim.Reward, laterClaim.Reward) - - // claim index has been updated to latest global value - laterClaimIndex, found := laterClaim.RewardIndexes.GetRewardIndex(bondDenom) - suite.Require().True(found) - rewardIndexes, found = suite.keeper.GetDelegatorRewardIndexes(suite.ctx, bondDenom) - suite.Require().True(found) - globalIndex, found = rewardIndexes.Get(rewardsPerSecond[0].Denom) - suite.Require().True(found) - suite.Require().Equal(globalIndex, laterClaimIndex.RewardIndexes[0].RewardFactor) -} - -// given a user has a delegation to an unbonded validator, when the validator becomes bonded, the user starts accumulating rewards -func (suite *DelegatorRewardsTestSuite) TestBondingValidatorSyncsClaim() { - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[0], cs(c("ukava", 1e9))). - WithSimpleAccount(suite.addrs[2], cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[0]), cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[1]), cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[2]), cs(c("ukava", 1e9))) - - rewardsPerSecond := cs(c("hard", 122354)) - bondDenom := "ukava" - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleDelegatorRewardPeriod(bondDenom, rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder) - - blockDuration := 10 * time.Second - - // Reduce the size of the validator set - stakingParams := suite.app.GetStakingKeeper().GetParams(suite.ctx) - stakingParams.MaxValidators = 2 - suite.app.GetStakingKeeper().SetParams(suite.ctx, stakingParams) - - // Create 3 validators - err := suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[0], c(bondDenom, 10_000_000)) - suite.Require().NoError(err) - err = suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[1], c(bondDenom, 5_000_000)) - suite.Require().NoError(err) - err = suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[2], c(bondDenom, 1_000_000)) - suite.Require().NoError(err) - - // End the block so top validators become bonded - _ = suite.app.EndBlocker(suite.ctx, abci.RequestEndBlock{}) - - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime.Add(1 * blockDuration)) - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}) // height and time in header are ignored by module begin blockers - - // Delegate to an unbonded validator from the test user. This will initialize their incentive claim. - err = suite.deliverMsgDelegate(suite.ctx, suite.addrs[0], suite.validatorAddrs[2], c(bondDenom, 1_000_000)) - suite.Require().NoError(err) - - // Start a new block to accumulate some delegation rewards globally. - _ = suite.app.EndBlocker(suite.ctx, abci.RequestEndBlock{}) - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime.Add(2 * blockDuration)) - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}) - - // Delegate to the user's unbonded validator to push it into the bonded validator set - err = suite.deliverMsgDelegate(suite.ctx, suite.addrs[2], suite.validatorAddrs[2], c(bondDenom, 4_000_000)) - suite.Require().NoError(err) - - // End the block to bond the user's validator - _ = suite.app.EndBlocker(suite.ctx, abci.RequestEndBlock{}) - // but don't start the next block as it will accumulate delegator rewards and we won't be able to tell if the user's reward was synced. - - // Check that the user's claim has been synced. ie rewards added, index updated - claim, found := suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - - rewardIndexes, found := suite.keeper.GetDelegatorRewardIndexes(suite.ctx, bondDenom) - suite.Require().True(found) - globalIndex, found := rewardIndexes.Get(rewardsPerSecond[0].Denom) - suite.Require().True(found) - claimIndex, found := claim.RewardIndexes.GetRewardIndex(bondDenom) - suite.Require().True(found) - suite.Require().Equal(globalIndex, claimIndex.RewardIndexes[0].RewardFactor) - - suite.Require().Equal( - sdk.Coins(nil), - claim.Reward, - ) - - // Run another block and check the claim is accumulating more rewards - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime.Add(3 * blockDuration)) - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}) - - suite.keeper.SynchronizeDelegatorRewards(suite.ctx, suite.addrs[0], nil, false) - - // rewards are greater than before - laterClaim, found := suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - suite.Require().True(laterClaim.Reward.IsAllGT(claim.Reward)) - - // claim index has been updated to latest global value - laterClaimIndex, found := laterClaim.RewardIndexes.GetRewardIndex(bondDenom) - suite.Require().True(found) - rewardIndexes, found = suite.keeper.GetDelegatorRewardIndexes(suite.ctx, bondDenom) - suite.Require().True(found) - globalIndex, found = rewardIndexes.Get(rewardsPerSecond[0].Denom) - suite.Require().True(found) - suite.Require().Equal(globalIndex, laterClaimIndex.RewardIndexes[0].RewardFactor) -} - -// If a validator is slashed delegators should have their claims synced -func (suite *DelegatorRewardsTestSuite) TestSlashingValidatorSyncsClaim() { - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[0], cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[0]), cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[1]), cs(c("ukava", 1e9))) - - rewardsPerSecond := cs(c("hard", 122354)) - bondDenom := "ukava" - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleDelegatorRewardPeriod(bondDenom, rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder) - - blockDuration := 10 * time.Second - - // Reduce the size of the validator set - stakingParams := suite.app.GetStakingKeeper().GetParams(suite.ctx) - stakingParams.MaxValidators = 2 - suite.app.GetStakingKeeper().SetParams(suite.ctx, stakingParams) - - // Create 2 validators - err := suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[0], c(bondDenom, 10_000_000)) - suite.Require().NoError(err) - err = suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[1], c(bondDenom, 10_000_000)) - suite.Require().NoError(err) - - // End the block so validators become bonded - _ = suite.app.EndBlocker(suite.ctx, abci.RequestEndBlock{}) - - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime.Add(1 * blockDuration)) - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}) // height and time in header are ignored by module begin blockers - - // Delegate to a bonded validator from the test user. This will initialize their incentive claim. - err = suite.deliverMsgDelegate(suite.ctx, suite.addrs[0], suite.validatorAddrs[1], c(bondDenom, 1_000_000)) - suite.Require().NoError(err) - - // Check that claim has been created with synced reward index but no reward coins - initialClaim, found := suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.True(found) - initialGlobalIndex, found := suite.keeper.GetDelegatorRewardIndexes(suite.ctx, bondDenom) - suite.True(found) - initialClaimIndex, found := initialClaim.RewardIndexes.GetRewardIndex(bondDenom) - suite.True(found) - suite.Require().Equal(initialGlobalIndex, initialClaimIndex.RewardIndexes) - suite.True(initialClaim.Reward.Empty()) // Initial claim should not have any rewards - - // Start a new block to accumulate some delegation rewards for the user. - _ = suite.app.EndBlocker(suite.ctx, abci.RequestEndBlock{}) - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime.Add(2 * blockDuration)) - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}) // height and time in header are ignored by module begin blockers - - // Fetch validator and slash them - stakingKeeper := suite.app.GetStakingKeeper() - validator, found := stakingKeeper.GetValidator(suite.ctx, suite.validatorAddrs[1]) - suite.Require().True(found) - suite.Require().True(validator.GetTokens().IsPositive()) - fraction := sdk.NewDecWithPrec(5, 1) - - consAddr, err := validator.GetConsAddr() - suite.Require().NoError(err) - - stakingKeeper.Slash(suite.ctx, consAddr, suite.ctx.BlockHeight(), 10, fraction) - - // Check that the user's claim has been synced. ie rewards added, index updated - claim, found := suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - globalIndex, found := suite.keeper.GetDelegatorRewardIndexes(suite.ctx, bondDenom) - suite.Require().True(found) - claimIndex, found := claim.RewardIndexes.GetRewardIndex(bondDenom) - suite.Require().True(found) - suite.Require().Equal(globalIndex, claimIndex.RewardIndexes) - - // Check that rewards were added - suite.Require().Equal( - cs(c(rewardsPerSecond[0].Denom, 58264)), - claim.Reward, - ) - - // Check that reward factor increased from initial value - suite.True(claimIndex.RewardIndexes[0].RewardFactor.GT(initialClaimIndex.RewardIndexes[0].RewardFactor)) -} - -// Given a delegation to a bonded validator, when a user redelegates everything to another (bonded) validator, the user's claim is synced -func (suite *DelegatorRewardsTestSuite) TestRedelegationSyncsClaim() { - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[0], cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[0]), cs(c("ukava", 1e9))). - WithSimpleAccount(sdk.AccAddress(suite.validatorAddrs[1]), cs(c("ukava", 1e9))) - - rewardsPerSecond := cs(c("hard", 122354)) - bondDenom := "ukava" - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleDelegatorRewardPeriod(bondDenom, rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder) - - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime) - blockDuration := 10 * time.Second - - // Create 2 validators - err := suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[0], c(bondDenom, 10_000_000)) - suite.Require().NoError(err) - err = suite.deliverMsgCreateValidator(suite.ctx, suite.validatorAddrs[1], c(bondDenom, 5_000_000)) - suite.Require().NoError(err) - - // Delete genesis validator to not influence rewards - suite.app.DeleteGenesisValidator(suite.T(), suite.ctx) - - // Delegatefrom the test user. This will initialize their incentive claim. - err = suite.deliverMsgDelegate(suite.ctx, suite.addrs[0], suite.validatorAddrs[0], c(bondDenom, 1_000_000)) - suite.Require().NoError(err) - - // Start a new block to accumulate some delegation rewards globally. - _ = suite.app.EndBlocker(suite.ctx, abci.RequestEndBlock{}) - suite.ctx = suite.ctx.WithBlockTime(suite.genesisTime.Add(1 * blockDuration)) - _ = suite.app.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}) // height and time in header are ignored by module begin blockers - - // Redelegate the user's delegation between the two validators. This should trigger hooks that sync the user's claim. - err = suite.deliverMsgRedelegate(suite.ctx, suite.addrs[0], suite.validatorAddrs[0], suite.validatorAddrs[1], c(bondDenom, 1_000_000)) - suite.Require().NoError(err) - - // Check that the user's claim has been synced. ie rewards added, index updated - claim, found := suite.keeper.GetDelegatorClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - - globalIndex, found := suite.keeper.GetDelegatorRewardIndexes(suite.ctx, bondDenom) - suite.Require().True(found) - claimIndex, found := claim.RewardIndexes.GetRewardIndex(bondDenom) - suite.Require().True(found) - suite.Require().Equal(globalIndex, claimIndex.RewardIndexes) - suite.Require().Equal( - cs(c(rewardsPerSecond[0].Denom, 76471)), - claim.Reward, - ) -} - -func TestDelegatorRewardsTestSuite(t *testing.T) { - suite.Run(t, new(DelegatorRewardsTestSuite)) -} diff --git a/x/incentive/keeper/rewards_earn.go b/x/incentive/keeper/rewards_earn.go deleted file mode 100644 index 9f9e0286..00000000 --- a/x/incentive/keeper/rewards_earn.go +++ /dev/null @@ -1,363 +0,0 @@ -package keeper - -import ( - "errors" - "fmt" - "sort" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - earntypes "github.com/0glabs/0g-chain/x/earn/types" - "github.com/0glabs/0g-chain/x/incentive/types" - - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" -) - -// AccumulateEarnRewards calculates new rewards to distribute this block and updates the global indexes to reflect this. -// The provided rewardPeriod must be valid to avoid panics in calculating time durations. -func (k Keeper) AccumulateEarnRewards(ctx sdk.Context, rewardPeriod types.MultiRewardPeriod) error { - if rewardPeriod.CollateralType == "bkava" { - return k.accumulateEarnBkavaRewards(ctx, rewardPeriod) - } - - k.accumulateEarnRewards( - ctx, - rewardPeriod.CollateralType, - rewardPeriod.Start, - rewardPeriod.End, - sdk.NewDecCoinsFromCoins(rewardPeriod.RewardsPerSecond...), - ) - - return nil -} - -func GetProportionalRewardsPerSecond( - rewardPeriod types.MultiRewardPeriod, - totalBkavaSupply sdkmath.Int, - singleBkavaSupply sdkmath.Int, -) sdk.DecCoins { - // Rate per bkava-xxx = rewardsPerSecond * % of bkava-xxx - // = rewardsPerSecond * (bkava-xxx / total bkava) - // = (rewardsPerSecond * bkava-xxx) / total bkava - - newRate := sdk.NewDecCoins() - - // Prevent division by zero, if there are no total shares then there are no - // rewards. - if totalBkavaSupply.IsZero() { - return newRate - } - - for _, rewardCoin := range rewardPeriod.RewardsPerSecond { - scaledAmount := sdk.NewDecFromInt(rewardCoin.Amount). - Mul(sdk.NewDecFromInt(singleBkavaSupply)). - Quo(sdk.NewDecFromInt(totalBkavaSupply)) - - newRate = newRate.Add(sdk.NewDecCoinFromDec(rewardCoin.Denom, scaledAmount)) - } - - return newRate -} - -// accumulateEarnBkavaRewards does the same as AccumulateEarnRewards but for -// *all* bkava vaults. -func (k Keeper) accumulateEarnBkavaRewards(ctx sdk.Context, rewardPeriod types.MultiRewardPeriod) error { - // All bkava vault denoms - bkavaVaultsDenoms := make(map[string]bool) - - // bkava vault denoms from earn records (non-empty vaults) - k.earnKeeper.IterateVaultRecords(ctx, func(record earntypes.VaultRecord) (stop bool) { - if k.liquidKeeper.IsDerivativeDenom(ctx, record.TotalShares.Denom) { - bkavaVaultsDenoms[record.TotalShares.Denom] = true - } - - return false - }) - - // bkava vault denoms from past incentive indexes, may include vaults - // that were fully withdrawn. - k.IterateEarnRewardIndexes(ctx, func(vaultDenom string, indexes types.RewardIndexes) (stop bool) { - if k.liquidKeeper.IsDerivativeDenom(ctx, vaultDenom) { - bkavaVaultsDenoms[vaultDenom] = true - } - - return false - }) - - totalBkavaValue, err := k.liquidKeeper.GetTotalDerivativeValue(ctx) - if err != nil { - return err - } - - i := 0 - sortedBkavaVaultsDenoms := make([]string, len(bkavaVaultsDenoms)) - for vaultDenom := range bkavaVaultsDenoms { - sortedBkavaVaultsDenoms[i] = vaultDenom - i++ - } - - // Sort the vault denoms to ensure deterministic iteration order. - sort.Strings(sortedBkavaVaultsDenoms) - - // Accumulate rewards for each bkava vault. - for _, bkavaDenom := range sortedBkavaVaultsDenoms { - derivativeValue, err := k.liquidKeeper.GetDerivativeValue(ctx, bkavaDenom) - if err != nil { - return err - } - - k.accumulateBkavaEarnRewards( - ctx, - bkavaDenom, - rewardPeriod.Start, - rewardPeriod.End, - GetProportionalRewardsPerSecond( - rewardPeriod, - totalBkavaValue.Amount, - derivativeValue.Amount, - ), - ) - } - - return nil -} - -func (k Keeper) accumulateBkavaEarnRewards( - ctx sdk.Context, - collateralType string, - periodStart time.Time, - periodEnd time.Time, - periodRewardsPerSecond sdk.DecCoins, -) { - // Collect staking rewards for this validator, does not have any start/end - // period time restrictions. - stakingRewards := k.collectDerivativeStakingRewards(ctx, collateralType) - - // Collect incentive rewards - // **Total rewards** for vault per second, NOT per share - perSecondRewards := k.collectPerSecondRewards( - ctx, - collateralType, - periodStart, - periodEnd, - periodRewardsPerSecond, - ) - - // **Total rewards** for vault per second, NOT per share - rewards := stakingRewards.Add(perSecondRewards...) - - // Distribute rewards by incrementing indexes - indexes, found := k.GetEarnRewardIndexes(ctx, collateralType) - if !found { - indexes = types.RewardIndexes{} - } - - totalSourceShares := k.getEarnTotalSourceShares(ctx, collateralType) - var increment types.RewardIndexes - if totalSourceShares.GT(sdk.ZeroDec()) { - // Divide total rewards by total shares to get the reward **per share** - // Leave as nil if no source shares - increment = types.NewRewardIndexesFromCoins(rewards).Quo(totalSourceShares) - } - updatedIndexes := indexes.Add(increment) - - if len(updatedIndexes) > 0 { - // the store panics when setting empty or nil indexes - k.SetEarnRewardIndexes(ctx, collateralType, updatedIndexes) - } -} - -func (k Keeper) collectDerivativeStakingRewards(ctx sdk.Context, collateralType string) sdk.DecCoins { - rewards, err := k.liquidKeeper.CollectStakingRewardsByDenom(ctx, collateralType, types.IncentiveMacc) - if err != nil { - if !errors.Is(err, distrtypes.ErrNoValidatorDistInfo) && - !errors.Is(err, distrtypes.ErrEmptyDelegationDistInfo) { - panic(fmt.Sprintf("failed to collect staking rewards for %s: %s", collateralType, err)) - } - - // otherwise there's no validator or delegation yet - rewards = nil - } - - // Bug with NewDecCoinsFromCoins when calling passing 0 amount Coin, see - // https://github.com/cosmos/cosmos-sdk/pull/12903 - // Fix is in Cosmos-SDK v0.47.0 - var decCoins sdk.DecCoins - for _, coin := range rewards { - if coin.IsValid() { - decCoins = append(decCoins, sdk.NewDecCoinFromCoin(coin)) - } - } - - return decCoins -} - -func (k Keeper) collectPerSecondRewards( - ctx sdk.Context, - collateralType string, - periodStart time.Time, - periodEnd time.Time, - periodRewardsPerSecond sdk.DecCoins, -) sdk.DecCoins { - previousAccrualTime, found := k.GetEarnRewardAccrualTime(ctx, collateralType) - if !found { - previousAccrualTime = ctx.BlockTime() - } - - rewards, accumulatedTo := types.CalculatePerSecondRewards( - periodStart, - periodEnd, - periodRewardsPerSecond, - previousAccrualTime, - ctx.BlockTime(), - ) - - k.SetEarnRewardAccrualTime(ctx, collateralType, accumulatedTo) - - // Don't need to move funds as they're assumed to be in the IncentiveMacc module account already. - return rewards -} - -func (k Keeper) accumulateEarnRewards( - ctx sdk.Context, - collateralType string, - periodStart time.Time, - periodEnd time.Time, - periodRewardsPerSecond sdk.DecCoins, -) { - previousAccrualTime, found := k.GetEarnRewardAccrualTime(ctx, collateralType) - if !found { - previousAccrualTime = ctx.BlockTime() - } - - indexes, found := k.GetEarnRewardIndexes(ctx, collateralType) - if !found { - indexes = types.RewardIndexes{} - } - - acc := types.NewAccumulator(previousAccrualTime, indexes) - - totalSourceShares := k.getEarnTotalSourceShares(ctx, collateralType) - - acc.AccumulateDecCoins( - periodStart, - periodEnd, - periodRewardsPerSecond, - totalSourceShares, - ctx.BlockTime(), - ) - - k.SetEarnRewardAccrualTime(ctx, collateralType, acc.PreviousAccumulationTime) - if len(acc.Indexes) > 0 { - // the store panics when setting empty or nil indexes - k.SetEarnRewardIndexes(ctx, collateralType, acc.Indexes) - } -} - -// getEarnTotalSourceShares fetches the sum of all source shares for a earn reward. -// In the case of earn, these are the total (earn module) shares in a particular vault. -func (k Keeper) getEarnTotalSourceShares(ctx sdk.Context, vaultDenom string) sdk.Dec { - totalShares, found := k.earnKeeper.GetVaultTotalShares(ctx, vaultDenom) - if !found { - return sdk.ZeroDec() - } - return totalShares.Amount -} - -// InitializeEarnReward creates a new claim with zero rewards and indexes matching the global indexes. -// If the claim already exists it just updates the indexes. -func (k Keeper) InitializeEarnReward(ctx sdk.Context, vaultDenom string, owner sdk.AccAddress) { - claim, found := k.GetEarnClaim(ctx, owner) - if !found { - claim = types.NewEarnClaim(owner, sdk.Coins{}, nil) - } - - globalRewardIndexes, found := k.GetEarnRewardIndexes(ctx, vaultDenom) - if !found { - globalRewardIndexes = types.RewardIndexes{} - } - claim.RewardIndexes = claim.RewardIndexes.With(vaultDenom, globalRewardIndexes) - - k.SetEarnClaim(ctx, claim) -} - -// SynchronizeEarnReward updates the claim object by adding any accumulated rewards -// and updating the reward index value. -func (k Keeper) SynchronizeEarnReward( - ctx sdk.Context, - vaultDenom string, - owner sdk.AccAddress, - shares sdk.Dec, -) { - claim, found := k.GetEarnClaim(ctx, owner) - if !found { - return - } - claim = k.synchronizeEarnReward(ctx, claim, vaultDenom, owner, shares) - - k.SetEarnClaim(ctx, claim) -} - -// synchronizeEarnReward updates the reward and indexes in a earn claim for one vault. -func (k *Keeper) synchronizeEarnReward( - ctx sdk.Context, - claim types.EarnClaim, - vaultDenom string, - owner sdk.AccAddress, - shares sdk.Dec, -) types.EarnClaim { - globalRewardIndexes, found := k.GetEarnRewardIndexes(ctx, vaultDenom) - if !found { - // The global factor is only not found if - // - the vault has not started accumulating rewards yet (either there is no reward specified in params, or the reward start time hasn't been hit) - // - OR it was wrongly deleted from state (factors should never be removed while unsynced claims exist) - // If not found we could either skip this sync, or assume the global factor is zero. - // Skipping will avoid storing unnecessary factors in the claim for non rewarded vaults. - // And in the event a global factor is wrongly deleted, it will avoid this function panicking when calculating rewards. - return claim - } - - userRewardIndexes, found := claim.RewardIndexes.Get(vaultDenom) - if !found { - // Normally the reward indexes should always be found. - // But if a vault was not rewarded then becomes rewarded (ie a reward period is added to params), then the indexes will be missing from claims for that vault. - // So given the reward period was just added, assume the starting value for any global reward indexes, which is an empty slice. - userRewardIndexes = types.RewardIndexes{} - } - - newRewards, err := k.CalculateRewards(userRewardIndexes, globalRewardIndexes, shares) - if err != nil { - // Global reward factors should never decrease, as it would lead to a negative update to claim.Rewards. - // This panics if a global reward factor decreases or disappears between the old and new indexes. - panic(fmt.Sprintf("corrupted global reward indexes found: %v", err)) - } - - claim.Reward = claim.Reward.Add(newRewards...) - claim.RewardIndexes = claim.RewardIndexes.With(vaultDenom, globalRewardIndexes) - - return claim -} - -// GetSynchronizedEarnClaim fetches a earn claim from the store and syncs rewards for all rewarded vaults. -func (k Keeper) GetSynchronizedEarnClaim(ctx sdk.Context, owner sdk.AccAddress) (types.EarnClaim, bool) { - claim, found := k.GetEarnClaim(ctx, owner) - if !found { - return types.EarnClaim{}, false - } - - shares, found := k.earnKeeper.GetVaultAccountShares(ctx, owner) - if !found { - shares = earntypes.NewVaultShares() - } - - k.IterateEarnRewardIndexes(ctx, func(vaultDenom string, _ types.RewardIndexes) bool { - vaultAmount := shares.AmountOf(vaultDenom) - claim = k.synchronizeEarnReward(ctx, claim, vaultDenom, owner, vaultAmount) - - return false - }) - - return claim, true -} diff --git a/x/incentive/keeper/rewards_earn_accum_integration_test.go b/x/incentive/keeper/rewards_earn_accum_integration_test.go deleted file mode 100644 index 9d389b83..00000000 --- a/x/incentive/keeper/rewards_earn_accum_integration_test.go +++ /dev/null @@ -1,649 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - abci "github.com/cometbft/cometbft/abci/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/app" - earntypes "github.com/0glabs/0g-chain/x/earn/types" - "github.com/0glabs/0g-chain/x/incentive/testutil" - "github.com/0glabs/0g-chain/x/incentive/types" -) - -type AccumulateEarnRewardsIntegrationTests struct { - testutil.IntegrationTester - - keeper TestKeeper - userAddrs []sdk.AccAddress - valAddrs []sdk.ValAddress -} - -func TestAccumulateEarnRewardsIntegrationTests(t *testing.T) { - suite.Run(t, new(AccumulateEarnRewardsIntegrationTests)) -} - -func (suite *AccumulateEarnRewardsIntegrationTests) SetupTest() { - suite.IntegrationTester.SetupTest() - - suite.keeper = TestKeeper{ - Keeper: suite.App.GetIncentiveKeeper(), - } - - _, addrs := app.GeneratePrivKeyAddressPairs(5) - suite.userAddrs = addrs[0:2] - suite.valAddrs = []sdk.ValAddress{ - sdk.ValAddress(addrs[2]), - sdk.ValAddress(addrs[3]), - } - - // Setup app with test state - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(addrs[0], cs(c("ukava", 1e12))). - WithSimpleAccount(addrs[1], cs(c("ukava", 1e12))). - WithSimpleAccount(addrs[2], cs(c("ukava", 1e12))). - WithSimpleAccount(addrs[3], cs(c("ukava", 1e12))) - - incentiveBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.GenesisTime). - WithSimpleEarnRewardPeriod("bkava", cs()) - - savingsBuilder := testutil.NewSavingsGenesisBuilder(). - WithSupportedDenoms("bkava") - - earnBuilder := testutil.NewEarnGenesisBuilder(). - WithAllowedVaults(earntypes.AllowedVault{ - Denom: "bkava", - Strategies: earntypes.StrategyTypes{earntypes.STRATEGY_TYPE_SAVINGS}, - IsPrivateVault: false, - AllowedDepositors: nil, - }) - - stakingBuilder := testutil.NewStakingGenesisBuilder() - - mintBuilder := testutil.NewMintGenesisBuilder(). - WithInflationMax(sdk.OneDec()). - WithInflationMin(sdk.OneDec()). - WithMinter(sdk.OneDec(), sdk.ZeroDec()). - WithMintDenom("ukava") - - suite.StartChainWithBuilders( - authBuilder, - incentiveBuilder, - savingsBuilder, - earnBuilder, - stakingBuilder, - mintBuilder, - ) -} - -func (suite *AccumulateEarnRewardsIntegrationTests) TestStateUpdatedWhenBlockTimeHasIncreased() { - suite.AddIncentiveEarnMultiRewardPeriod( - types.NewMultiRewardPeriod( - true, - "bkava", // reward period is set for "bkava" to apply to all vaults - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ), - ) - - derivative0, err := suite.MintLiquidAnyValAddr(suite.userAddrs[0], suite.valAddrs[0], c("ukava", 800000)) - suite.NoError(err) - derivative1, err := suite.MintLiquidAnyValAddr(suite.userAddrs[1], suite.valAddrs[1], c("ukava", 200000)) - suite.NoError(err) - - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[0], derivative0, earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[1], derivative1, earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: derivative0.Denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: derivative1.Denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - - suite.keeper.storeGlobalEarnIndexes(suite.Ctx, globalIndexes) - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, derivative0.Denom, suite.Ctx.BlockTime()) - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, derivative1.Denom, suite.Ctx.BlockTime()) - - val0 := suite.GetAbciValidator(suite.valAddrs[0]) - val1 := suite.GetAbciValidator(suite.valAddrs[1]) - - // Mint tokens, distribute to validators, claim staking rewards - // 1 hour later - _, resBeginBlock := suite.NextBlockAfterWithReq( - 1*time.Hour, - abci.RequestEndBlock{}, - abci.RequestBeginBlock{ - LastCommitInfo: abci.CommitInfo{ - Votes: []abci.VoteInfo{ - { - Validator: val0, - SignedLastBlock: true, - }, - { - Validator: val1, - SignedLastBlock: true, - }, - }, - }, - }, - ) - - validatorRewards, _ := suite.GetBeginBlockClaimedStakingRewards(resBeginBlock) - - suite.Require().Contains(validatorRewards, suite.valAddrs[1].String(), "there should be claim events for validator 0") - suite.Require().Contains(validatorRewards, suite.valAddrs[0].String(), "there should be claim events for validator 1") - - // check time and factors - - suite.StoredEarnTimeEquals(derivative0.Denom, suite.Ctx.BlockTime()) - suite.StoredEarnTimeEquals(derivative1.Denom, suite.Ctx.BlockTime()) - - stakingRewardIndexes0 := sdk.NewDecFromInt(validatorRewards[suite.valAddrs[0].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(derivative0.Amount)) - - stakingRewardIndexes1 := sdk.NewDecFromInt(validatorRewards[suite.valAddrs[1].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(derivative1.Amount)) - - suite.StoredEarnIndexesEqual(derivative0.Denom, types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("7.22"), - }, - { - CollateralType: "ukava", - RewardFactor: d("3.64").Add(stakingRewardIndexes0), - }, - }) - suite.StoredEarnIndexesEqual(derivative1.Denom, types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("7.22"), - }, - { - CollateralType: "ukava", - RewardFactor: d("3.64").Add(stakingRewardIndexes1), - }, - }) -} - -func (suite *AccumulateEarnRewardsIntegrationTests) TestStateUpdatedWhenBlockTimeHasIncreased_partialDeposit() { - suite.AddIncentiveEarnMultiRewardPeriod( - types.NewMultiRewardPeriod( - true, - "bkava", // reward period is set for "bkava" to apply to all vaults - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ), - ) - - // 800000bkava0 minted, 700000 deposited - // 200000bkava1 minted, 100000 deposited - derivative0, err := suite.MintLiquidAnyValAddr(suite.userAddrs[0], suite.valAddrs[0], c("ukava", 800000)) - suite.NoError(err) - derivative1, err := suite.MintLiquidAnyValAddr(suite.userAddrs[1], suite.valAddrs[1], c("ukava", 200000)) - suite.NoError(err) - - depositAmount0 := c(derivative0.Denom, 700000) - depositAmount1 := c(derivative1.Denom, 100000) - - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[0], depositAmount0, earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[1], depositAmount1, earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: derivative0.Denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: derivative1.Denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - - suite.keeper.storeGlobalEarnIndexes(suite.Ctx, globalIndexes) - - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, derivative0.Denom, suite.Ctx.BlockTime()) - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, derivative1.Denom, suite.Ctx.BlockTime()) - - val0 := suite.GetAbciValidator(suite.valAddrs[0]) - val1 := suite.GetAbciValidator(suite.valAddrs[1]) - - // Mint tokens, distribute to validators, claim staking rewards - // 1 hour later - _, resBeginBlock := suite.NextBlockAfterWithReq( - 1*time.Hour, - abci.RequestEndBlock{}, - abci.RequestBeginBlock{ - LastCommitInfo: abci.CommitInfo{ - Votes: []abci.VoteInfo{ - { - Validator: val0, - SignedLastBlock: true, - }, - { - Validator: val1, - SignedLastBlock: true, - }, - }, - }, - }, - ) - - validatorRewards, _ := suite.GetBeginBlockClaimedStakingRewards(resBeginBlock) - - suite.Require().Contains(validatorRewards, suite.valAddrs[1].String(), "there should be claim events for validator 0") - suite.Require().Contains(validatorRewards, suite.valAddrs[0].String(), "there should be claim events for validator 1") - - // check time and factors - - suite.StoredEarnTimeEquals(derivative0.Denom, suite.Ctx.BlockTime()) - suite.StoredEarnTimeEquals(derivative1.Denom, suite.Ctx.BlockTime()) - - // Divided by deposit amounts, not bank supply amounts - stakingRewardIndexes0 := sdk.NewDecFromInt(validatorRewards[suite.valAddrs[0].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(depositAmount0.Amount)) - - stakingRewardIndexes1 := sdk.NewDecFromInt(validatorRewards[suite.valAddrs[1].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(depositAmount1.Amount)) - - // Slightly increased rewards due to less bkava deposited - suite.StoredEarnIndexesEqual(derivative0.Denom, types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("8.248571428571428571"), - }, - { - CollateralType: "ukava", - RewardFactor: d("4.154285714285714286").Add(stakingRewardIndexes0), - }, - }) - - suite.StoredEarnIndexesEqual(derivative1.Denom, types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("14.42"), - }, - { - CollateralType: "ukava", - RewardFactor: d("7.24").Add(stakingRewardIndexes1), - }, - }) -} - -func (suite *AccumulateEarnRewardsIntegrationTests) TestStateUnchangedWhenBlockTimeHasNotIncreased() { - derivative0, err := suite.MintLiquidAnyValAddr(suite.userAddrs[0], suite.valAddrs[0], c("ukava", 1000000)) - suite.NoError(err) - derivative1, err := suite.MintLiquidAnyValAddr(suite.userAddrs[1], suite.valAddrs[1], c("ukava", 1000000)) - suite.NoError(err) - - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[0], derivative0, earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[1], derivative1, earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: derivative0.Denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: derivative1.Denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.keeper.storeGlobalEarnIndexes(suite.Ctx, previousIndexes) - - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, derivative0.Denom, suite.Ctx.BlockTime()) - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, derivative1.Denom, suite.Ctx.BlockTime()) - - period := types.NewMultiRewardPeriod( - true, - "bkava", - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - // Must manually accumulate rewards as BeginBlockers only run when the block time increases - // This does not run any x/mint or x/distribution BeginBlockers - suite.keeper.AccumulateEarnRewards(suite.Ctx, period) - - // check time and factors - - suite.StoredEarnTimeEquals(derivative0.Denom, suite.Ctx.BlockTime()) - suite.StoredEarnTimeEquals(derivative1.Denom, suite.Ctx.BlockTime()) - - expected, f := previousIndexes.Get(derivative0.Denom) - suite.True(f) - suite.StoredEarnIndexesEqual(derivative0.Denom, expected) - - expected, f = previousIndexes.Get(derivative1.Denom) - suite.True(f) - suite.StoredEarnIndexesEqual(derivative1.Denom, expected) -} - -func (suite *AccumulateEarnRewardsIntegrationTests) TestNoAccumulationWhenSourceSharesAreZero() { - suite.AddIncentiveEarnMultiRewardPeriod( - types.NewMultiRewardPeriod( - true, - "bkava", // reward period is set for "bkava" to apply to all vaults - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ), - ) - - derivative0, err := suite.MintLiquidAnyValAddr(suite.userAddrs[0], suite.valAddrs[0], c("ukava", 1000000)) - suite.NoError(err) - derivative1, err := suite.MintLiquidAnyValAddr(suite.userAddrs[1], suite.valAddrs[1], c("ukava", 1000000)) - suite.NoError(err) - - // No earn deposits - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: derivative0.Denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: derivative1.Denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.keeper.storeGlobalEarnIndexes(suite.Ctx, previousIndexes) - - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, derivative0.Denom, suite.Ctx.BlockTime()) - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, derivative1.Denom, suite.Ctx.BlockTime()) - - val0 := suite.GetAbciValidator(suite.valAddrs[0]) - val1 := suite.GetAbciValidator(suite.valAddrs[1]) - - // Mint tokens, distribute to validators, claim staking rewards - // 1 hour later - _, _ = suite.NextBlockAfterWithReq( - 1*time.Hour, - abci.RequestEndBlock{}, - abci.RequestBeginBlock{ - LastCommitInfo: abci.CommitInfo{ - Votes: []abci.VoteInfo{ - { - Validator: val0, - SignedLastBlock: true, - }, - { - Validator: val1, - SignedLastBlock: true, - }, - }, - }, - }, - ) - // check time and factors - - suite.StoredEarnTimeEquals(derivative0.Denom, suite.Ctx.BlockTime()) - suite.StoredEarnTimeEquals(derivative1.Denom, suite.Ctx.BlockTime()) - - expected, f := previousIndexes.Get(derivative0.Denom) - suite.True(f) - suite.StoredEarnIndexesEqual(derivative0.Denom, expected) - - expected, f = previousIndexes.Get(derivative1.Denom) - suite.True(f) - suite.StoredEarnIndexesEqual(derivative1.Denom, expected) -} - -func (suite *AccumulateEarnRewardsIntegrationTests) TestStateAddedWhenStateDoesNotExist() { - suite.AddIncentiveEarnMultiRewardPeriod( - types.NewMultiRewardPeriod( - true, - "bkava", // reward period is set for "bkava" to apply to all vaults - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ), - ) - - derivative0, err := suite.MintLiquidAnyValAddr(suite.userAddrs[0], suite.valAddrs[0], c("ukava", 1000000)) - suite.NoError(err) - derivative1, err := suite.MintLiquidAnyValAddr(suite.userAddrs[1], suite.valAddrs[1], c("ukava", 1000000)) - suite.NoError(err) - - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[0], derivative0, earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[1], derivative1, earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - - val0 := suite.GetAbciValidator(suite.valAddrs[0]) - val1 := suite.GetAbciValidator(suite.valAddrs[1]) - - _, resBeginBlock := suite.NextBlockAfterWithReq( - 1*time.Hour, - abci.RequestEndBlock{}, - abci.RequestBeginBlock{ - LastCommitInfo: abci.CommitInfo{ - Votes: []abci.VoteInfo{ - { - Validator: val0, - SignedLastBlock: true, - }, - { - Validator: val1, - SignedLastBlock: true, - }, - }, - }, - }, - ) - - // After the second accumulation both current block time and indexes should be stored. - suite.StoredEarnTimeEquals(derivative0.Denom, suite.Ctx.BlockTime()) - suite.StoredEarnTimeEquals(derivative1.Denom, suite.Ctx.BlockTime()) - - validatorRewards0, _ := suite.GetBeginBlockClaimedStakingRewards(resBeginBlock) - - firstStakingRewardIndexes0 := sdk.NewDecFromInt(validatorRewards0[suite.valAddrs[0].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(derivative0.Amount)) - - firstStakingRewardIndexes1 := sdk.NewDecFromInt(validatorRewards0[suite.valAddrs[1].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(derivative1.Amount)) - - // After the first accumulation only the current block time should be stored. - // The indexes will be empty as no time has passed since the previous block because it didn't exist. - suite.StoredEarnTimeEquals(derivative0.Denom, suite.Ctx.BlockTime()) - suite.StoredEarnTimeEquals(derivative1.Denom, suite.Ctx.BlockTime()) - - // First accumulation can have staking rewards, but no other rewards - suite.StoredEarnIndexesEqual(derivative0.Denom, types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: firstStakingRewardIndexes0, - }, - }) - suite.StoredEarnIndexesEqual(derivative1.Denom, types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: firstStakingRewardIndexes1, - }, - }) - - _, resBeginBlock = suite.NextBlockAfterWithReq( - 1*time.Hour, - abci.RequestEndBlock{}, - abci.RequestBeginBlock{ - LastCommitInfo: abci.CommitInfo{ - Votes: []abci.VoteInfo{ - { - Validator: val0, - SignedLastBlock: true, - }, - { - Validator: val1, - SignedLastBlock: true, - }, - }, - }, - }, - ) - - // After the second accumulation both current block time and indexes should be stored. - suite.StoredEarnTimeEquals(derivative0.Denom, suite.Ctx.BlockTime()) - suite.StoredEarnTimeEquals(derivative1.Denom, suite.Ctx.BlockTime()) - - validatorRewards1, _ := suite.GetBeginBlockClaimedStakingRewards(resBeginBlock) - - secondStakingRewardIndexes0 := sdk.NewDecFromInt(validatorRewards1[suite.valAddrs[0].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(derivative0.Amount)) - - secondStakingRewardIndexes1 := sdk.NewDecFromInt(validatorRewards1[suite.valAddrs[1].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(derivative1.Amount)) - - // Second accumulation has both staking rewards and incentive rewards - // ukava incentive rewards: 3600 * 1000 / (2 * 1000000) == 1.8 - suite.StoredEarnIndexesEqual(derivative0.Denom, types.RewardIndexes{ - { - CollateralType: "ukava", - // Incentive rewards + both staking rewards - RewardFactor: d("1.8").Add(firstStakingRewardIndexes0).Add(secondStakingRewardIndexes0), - }, - { - CollateralType: "earn", - RewardFactor: d("3.6"), - }, - }) - suite.StoredEarnIndexesEqual(derivative1.Denom, types.RewardIndexes{ - { - CollateralType: "ukava", - // Incentive rewards + both staking rewards - RewardFactor: d("1.8").Add(firstStakingRewardIndexes1).Add(secondStakingRewardIndexes1), - }, - { - CollateralType: "earn", - RewardFactor: d("3.6"), - }, - }) -} - -func (suite *AccumulateEarnRewardsIntegrationTests) TestNoPanicWhenStateDoesNotExist() { - derivative0, err := suite.MintLiquidAnyValAddr(suite.userAddrs[0], suite.valAddrs[0], c("ukava", 1000000)) - suite.NoError(err) - derivative1, err := suite.MintLiquidAnyValAddr(suite.userAddrs[1], suite.valAddrs[1], c("ukava", 1000000)) - suite.NoError(err) - - period := types.NewMultiRewardPeriod( - true, - "bkava", - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(), - ) - - // Accumulate with no earn shares and no rewards per second will result in no increment to the indexes. - // No increment and no previous indexes stored, results in an updated of nil. Setting this in the state panics. - // Check there is no panic. - suite.NotPanics(func() { - // This does not update any state, as there are no bkava vaults - // to iterate over, denoms are unknown - suite.keeper.AccumulateEarnRewards(suite.Ctx, period) - }) - - // Times are not stored for vaults with no state - suite.StoredEarnTimeEquals(derivative0.Denom, time.Time{}) - suite.StoredEarnTimeEquals(derivative1.Denom, time.Time{}) - suite.StoredEarnIndexesEqual(derivative0.Denom, nil) - suite.StoredEarnIndexesEqual(derivative1.Denom, nil) -} diff --git a/x/incentive/keeper/rewards_earn_accum_test.go b/x/incentive/keeper/rewards_earn_accum_test.go deleted file mode 100644 index e4f9ae66..00000000 --- a/x/incentive/keeper/rewards_earn_accum_test.go +++ /dev/null @@ -1,781 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - earntypes "github.com/0glabs/0g-chain/x/earn/types" - "github.com/0glabs/0g-chain/x/incentive/types" -) - -type AccumulateEarnRewardsTests struct { - unitTester -} - -func (suite *AccumulateEarnRewardsTests) storedTimeEquals(vaultDenom string, expected time.Time) { - storedTime, found := suite.keeper.GetEarnRewardAccrualTime(suite.ctx, vaultDenom) - suite.Equal(found, expected != time.Time{}, "expected time is %v but time found = %v", expected, found) - if found { - suite.Equal(expected, storedTime) - } else { - suite.Empty(storedTime) - } -} - -func (suite *AccumulateEarnRewardsTests) storedIndexesEqual(vaultDenom string, expected types.RewardIndexes) { - storedIndexes, found := suite.keeper.GetEarnRewardIndexes(suite.ctx, vaultDenom) - suite.Equal(found, expected != nil, "expected indexes is %v but indexes found = %v", expected, found) - if found { - suite.Equal(expected, storedIndexes) - } else { - suite.Empty(storedIndexes) - } -} - -func TestAccumulateEarnRewards(t *testing.T) { - suite.Run(t, new(AccumulateEarnRewardsTests)) -} - -func (suite *AccumulateEarnRewardsTests) TestStateUpdatedWhenBlockTimeHasIncreased() { - vaultDenom := "usdx" - - earnKeeper := newFakeEarnKeeper().addVault(vaultDenom, earntypes.NewVaultShare(vaultDenom, d("1000000"))) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, earnKeeper) - - suite.storeGlobalEarnIndexes(types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - }) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom, previousAccrualTime) - - newAccrualTime := previousAccrualTime.Add(1 * time.Hour) - suite.ctx = suite.ctx.WithBlockTime(newAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - vaultDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(vaultDenom, newAccrualTime) - suite.storedIndexesEqual(vaultDenom, types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("7.22"), - }, - { - CollateralType: "ukava", - RewardFactor: d("3.64"), - }, - }) -} - -func (suite *AccumulateEarnRewardsTests) TestStateUpdatedWhenBlockTimeHasIncreased_bkava() { - vaultDenom1 := "bkava-meow" - vaultDenom2 := "bkava-woof" - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - earnKeeper := newFakeEarnKeeper(). - addVault(vaultDenom1, earntypes.NewVaultShare(vaultDenom1, d("800000"))). - addVault(vaultDenom2, earntypes.NewVaultShare(vaultDenom2, d("200000"))) - - liquidKeeper := newFakeLiquidKeeper(). - addDerivative(suite.ctx, vaultDenom1, i(800000)). - addDerivative(suite.ctx, vaultDenom2, i(200000)) - - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, liquidKeeper, earnKeeper) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: vaultDenom2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - - suite.storeGlobalEarnIndexes(globalIndexes) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom1, previousAccrualTime) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom2, previousAccrualTime) - - newAccrualTime := previousAccrualTime.Add(1 * time.Hour) - suite.ctx = suite.ctx.WithBlockTime(newAccrualTime) - - rewardPeriod := types.NewMultiRewardPeriod( - true, - "bkava", // reward period is set for "bkava" to apply to all vaults - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - suite.keeper.AccumulateEarnRewards(suite.ctx, rewardPeriod) - - // check time and factors - - suite.storedTimeEquals(vaultDenom1, newAccrualTime) - suite.storedTimeEquals(vaultDenom2, newAccrualTime) - - // Each vault gets the same ukava per second, assuming shares prices are the same. - // The share amount determines how much is actually distributed to the vault. - expectedIndexes := types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("7.22"), - }, - { - CollateralType: "ukava", - RewardFactor: d("3.64"). // base incentive - Add(d("360")), // staking rewards, 10% of total bkava per second - }, - } - - suite.storedIndexesEqual(vaultDenom1, expectedIndexes) - suite.storedIndexesEqual(vaultDenom2, expectedIndexes) -} - -func (suite *AccumulateEarnRewardsTests) TestStateUpdatedWhenBlockTimeHasIncreased_bkava_partialDeposit() { - vaultDenom1 := "bkava-meow" - vaultDenom2 := "bkava-woof" - - vaultDenom1Supply := i(800000) - vaultDenom2Supply := i(200000) - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - liquidKeeper := newFakeLiquidKeeper(). - addDerivative(suite.ctx, vaultDenom1, vaultDenom1Supply). - addDerivative(suite.ctx, vaultDenom2, vaultDenom2Supply) - - vault1Shares := d("700000") - vault2Shares := d("100000") - - // More bkava minted than deposited into earn - // Rewards are higher per-share as a result - earnKeeper := newFakeEarnKeeper(). - addVault(vaultDenom1, earntypes.NewVaultShare(vaultDenom1, vault1Shares)). - addVault(vaultDenom2, earntypes.NewVaultShare(vaultDenom2, vault2Shares)) - - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, liquidKeeper, earnKeeper) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: vaultDenom2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - - suite.storeGlobalEarnIndexes(globalIndexes) - - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom1, previousAccrualTime) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom2, previousAccrualTime) - - newAccrualTime := previousAccrualTime.Add(1 * time.Hour) - suite.ctx = suite.ctx.WithBlockTime(newAccrualTime) - - rewardPeriod := types.NewMultiRewardPeriod( - true, - "bkava", // reward period is set for "bkava" to apply to all vaults - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - suite.keeper.AccumulateEarnRewards(suite.ctx, rewardPeriod) - - // check time and factors - - suite.storedTimeEquals(vaultDenom1, newAccrualTime) - suite.storedTimeEquals(vaultDenom2, newAccrualTime) - - // Slightly increased rewards due to less bkava deposited - suite.storedIndexesEqual(vaultDenom1, types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("8.248571428571428571"), - }, - { - CollateralType: "ukava", - RewardFactor: d("4.154285714285714286"). // base incentive - Add(sdk.NewDecFromInt(vaultDenom1Supply). // staking rewards - QuoInt64(10). - MulInt64(3600). - Quo(vault1Shares), - ), - }, - }) - - // Much higher rewards per share because only a small amount of bkava is - // deposited. The **total** amount of incentives distributed to this vault - // is still the same proportional amount. - - // Fixed amount total rewards distributed to the vault - // Fewer shares deposited -> higher rewards per share - - // 7.2ukava shares per second for 1 hour (started with 0.04) - // total rewards claimable = 7.2 * 100000 shares = 720000 ukava - - // 720000ukava distributed which is 20% of total bkava ukava rewards - // total rewards for *all* bkava vaults for 1 hour - // = 1000ukava per second * 3600 == 3600000ukava - // vaultDenom2 has 20% of the total bkava amount so it should get 20% of 3600000ukava == 720000ukava - - vault2expectedIndexes := types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("14.42"), - }, - { - CollateralType: "ukava", - RewardFactor: d("7.24"). - Add(sdk.NewDecFromInt(vaultDenom2Supply). - QuoInt64(10). - MulInt64(3600). - Quo(vault2Shares), - ), - }, - } - suite.storedIndexesEqual(vaultDenom2, vault2expectedIndexes) -} - -func (suite *AccumulateEarnRewardsTests) TestStateUnchangedWhenBlockTimeHasNotIncreased() { - vaultDenom := "usdx" - - earnKeeper := newFakeEarnKeeper().addVault(vaultDenom, earntypes.NewVaultShare(vaultDenom, d("1000000"))) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, earnKeeper) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom, previousAccrualTime) - - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - vaultDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(vaultDenom, previousAccrualTime) - expected, f := previousIndexes.Get(vaultDenom) - suite.True(f) - suite.storedIndexesEqual(vaultDenom, expected) -} - -func (suite *AccumulateEarnRewardsTests) TestStateUnchangedWhenBlockTimeHasNotIncreased_bkava() { - vaultDenom1 := "bkava-meow" - vaultDenom2 := "bkava-woof" - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - earnKeeper := newFakeEarnKeeper(). - addVault(vaultDenom1, earntypes.NewVaultShare(vaultDenom1, d("1000000"))). - addVault(vaultDenom2, earntypes.NewVaultShare(vaultDenom2, d("1000000"))) - - liquidKeeper := newFakeLiquidKeeper(). - addDerivative(suite.ctx, vaultDenom1, i(1000000)). - addDerivative(suite.ctx, vaultDenom2, i(1000000)) - - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, liquidKeeper, earnKeeper) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: vaultDenom2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(previousIndexes) - - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom1, previousAccrualTime) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom2, previousAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - "bkava", - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(vaultDenom1, previousAccrualTime) - suite.storedTimeEquals(vaultDenom2, previousAccrualTime) - - expected, f := previousIndexes.Get(vaultDenom1) - suite.True(f) - suite.storedIndexesEqual(vaultDenom1, expected) - - expected, f = previousIndexes.Get(vaultDenom2) - suite.True(f) - suite.storedIndexesEqual(vaultDenom2, expected) -} - -func (suite *AccumulateEarnRewardsTests) TestNoAccumulationWhenSourceSharesAreZero() { - vaultDenom := "usdx" - - earnKeeper := newFakeEarnKeeper() // no vault, so no source shares - liquidKeeper := newFakeLiquidKeeper() - - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, liquidKeeper, earnKeeper) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(7 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - vaultDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(vaultDenom, firstAccrualTime) - expected, f := previousIndexes.Get(vaultDenom) - suite.True(f) - suite.storedIndexesEqual(vaultDenom, expected) -} - -func (suite *AccumulateEarnRewardsTests) TestNoAccumulationWhenSourceSharesAreZero_bkava() { - vaultDenom1 := "bkava-meow" - vaultDenom2 := "bkava-woof" - - earnKeeper := newFakeEarnKeeper() // no vault, so no source shares - liquidKeeper := newFakeLiquidKeeper() - - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, liquidKeeper, earnKeeper) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: vaultDenom2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom1, previousAccrualTime) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom2, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(7 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - "bkava", - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - // TODO: There are no bkava vaults to iterate over, so the accrual times are - // not updated - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(vaultDenom1, firstAccrualTime) - suite.storedTimeEquals(vaultDenom2, firstAccrualTime) - - expected, f := previousIndexes.Get(vaultDenom1) - suite.True(f) - suite.storedIndexesEqual(vaultDenom1, expected) - - expected, f = previousIndexes.Get(vaultDenom2) - suite.True(f) - suite.storedIndexesEqual(vaultDenom2, expected) -} - -func (suite *AccumulateEarnRewardsTests) TestStateAddedWhenStateDoesNotExist() { - vaultDenom := "usdx" - - earnKeeper := newFakeEarnKeeper().addVault(vaultDenom, earntypes.NewVaultShare(vaultDenom, d("1000000"))) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, earnKeeper) - - period := types.NewMultiRewardPeriod( - true, - vaultDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), - ) - - firstAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // After the first accumulation only the current block time should be stored. - // The indexes will be empty as no time has passed since the previous block because it didn't exist. - suite.storedTimeEquals(vaultDenom, firstAccrualTime) - suite.storedIndexesEqual(vaultDenom, nil) - - secondAccrualTime := firstAccrualTime.Add(10 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(secondAccrualTime) - - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // After the second accumulation both current block time and indexes should be stored. - suite.storedTimeEquals(vaultDenom, secondAccrualTime) - suite.storedIndexesEqual(vaultDenom, types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.01"), - }, - }) -} - -func (suite *AccumulateEarnRewardsTests) TestStateAddedWhenStateDoesNotExist_bkava() { - vaultDenom1 := "bkava-meow" - vaultDenom2 := "bkava-woof" - - firstAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - earnKeeper := newFakeEarnKeeper(). - addVault(vaultDenom1, earntypes.NewVaultShare(vaultDenom1, d("1000000"))). - addVault(vaultDenom2, earntypes.NewVaultShare(vaultDenom2, d("1000000"))) - - liquidKeeper := newFakeLiquidKeeper(). - addDerivative(suite.ctx, vaultDenom1, i(1000000)). - addDerivative(suite.ctx, vaultDenom2, i(1000000)) - - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, liquidKeeper, earnKeeper) - - period := types.NewMultiRewardPeriod( - true, - "bkava", - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), - ) - - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // After the first accumulation only the current block time should be stored. - // The indexes will be empty as no time has passed since the previous block because it didn't exist. - suite.storedTimeEquals(vaultDenom1, firstAccrualTime) - suite.storedTimeEquals(vaultDenom2, firstAccrualTime) - - suite.storedIndexesEqual(vaultDenom1, nil) - suite.storedIndexesEqual(vaultDenom2, nil) - - secondAccrualTime := firstAccrualTime.Add(10 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(secondAccrualTime) - - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // After the second accumulation both current block time and indexes should be stored. - suite.storedTimeEquals(vaultDenom1, secondAccrualTime) - suite.storedTimeEquals(vaultDenom2, secondAccrualTime) - - expectedIndexes := types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.01"), - }, - { - CollateralType: "ukava", - // 10% of total bkava for rewards per second for 10 seconds - // 1ukava per share per second + regular 0.005ukava incentive rewards - RewardFactor: d("1.005"), - }, - } - - suite.storedIndexesEqual(vaultDenom1, expectedIndexes) - suite.storedIndexesEqual(vaultDenom2, expectedIndexes) -} - -func (suite *AccumulateEarnRewardsTests) TestNoPanicWhenStateDoesNotExist() { - vaultDenom := "usdx" - - earnKeeper := newFakeEarnKeeper() - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, earnKeeper) - - period := types.NewMultiRewardPeriod( - true, - vaultDenom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(), - ) - - accrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(accrualTime) - - // Accumulate with no earn shares and no rewards per second will result in no increment to the indexes. - // No increment and no previous indexes stored, results in an updated of nil. Setting this in the state panics. - // Check there is no panic. - suite.NotPanics(func() { - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - }) - - suite.storedTimeEquals(vaultDenom, accrualTime) - suite.storedIndexesEqual(vaultDenom, nil) -} - -func (suite *AccumulateEarnRewardsTests) TestNoPanicWhenStateDoesNotExist_bkava() { - vaultDenom1 := "bkava-meow" - vaultDenom2 := "bkava-woof" - - earnKeeper := newFakeEarnKeeper() - liquidKeeper := newFakeLiquidKeeper() - - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, liquidKeeper, earnKeeper) - - period := types.NewMultiRewardPeriod( - true, - "bkava", - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(), - ) - - accrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(accrualTime) - - // Accumulate with no earn shares and no rewards per second will result in no increment to the indexes. - // No increment and no previous indexes stored, results in an updated of nil. Setting this in the state panics. - // Check there is no panic. - suite.NotPanics(func() { - // This does not update any state, as there are no bkava vaults - // to iterate over, denoms are unknown - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - }) - - // Times are not stored for vaults with no state - suite.storedTimeEquals(vaultDenom1, time.Time{}) - suite.storedTimeEquals(vaultDenom2, time.Time{}) - suite.storedIndexesEqual(vaultDenom1, nil) - suite.storedIndexesEqual(vaultDenom2, nil) -} - -func (suite *AccumulateEarnRewardsTests) TestNoAccumulationWhenBeforeStartTime() { - vaultDenom := "usdx" - - earnKeeper := newFakeEarnKeeper().addVault(vaultDenom, earntypes.NewVaultShare(vaultDenom, d("1000000"))) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, earnKeeper) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "earn", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(10 * time.Second) - - period := types.NewMultiRewardPeriod( - true, - vaultDenom, - firstAccrualTime.Add(time.Nanosecond), // start time after accrual time - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - - // The accrual time should be updated, but the indexes unchanged - suite.storedTimeEquals(vaultDenom, firstAccrualTime) - expectedIndexes, f := previousIndexes.Get(vaultDenom) - suite.True(f) - suite.storedIndexesEqual(vaultDenom, expectedIndexes) -} - -func (suite *AccumulateEarnRewardsTests) TestPanicWhenCurrentTimeLessThanPrevious() { - vaultDenom := "usdx" - - earnKeeper := newFakeEarnKeeper().addVault(vaultDenom, earntypes.NewVaultShare(vaultDenom, d("1000000"))) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, earnKeeper) - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom, previousAccrualTime) - - firstAccrualTime := time.Time{} - - period := types.NewMultiRewardPeriod( - true, - vaultDenom, - time.Time{}, // start time after accrual time - distantFuture, - cs(c("earn", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.Panics(func() { - suite.keeper.AccumulateEarnRewards(suite.ctx, period) - }) -} diff --git a/x/incentive/keeper/rewards_earn_init_test.go b/x/incentive/keeper/rewards_earn_init_test.go deleted file mode 100644 index f996a55f..00000000 --- a/x/incentive/keeper/rewards_earn_init_test.go +++ /dev/null @@ -1,195 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// InitializeEarnRewardTests runs unit tests for the keeper.InitializeEarnReward method -// -// inputs -// - claim in store if it exists -// - global indexes in store -// -// outputs -// - sets or creates a claim -type InitializeEarnRewardTests struct { - unitTester -} - -func TestInitializeEarnReward(t *testing.T) { - suite.Run(t, new(InitializeEarnRewardTests)) -} - -func (suite *InitializeEarnRewardTests) TestClaimAddedWhenClaimDoesNotExistAndNoRewards() { - // When a claim doesn't exist, and a user deposits to a non-rewarded pool; - // then a claim is added with no rewards and no indexes - - vaultDenom := "usdx" - - // no global indexes stored as this pool is not rewarded - - owner := arbitraryAddress() - - suite.keeper.InitializeEarnReward(suite.ctx, vaultDenom, owner) - - syncedClaim, found := suite.keeper.GetEarnClaim(suite.ctx, owner) - suite.True(found) - // A new claim should have empty indexes. It doesn't strictly need the vaultDenom either. - expectedIndexes := types.MultiRewardIndexes{{ - CollateralType: vaultDenom, - RewardIndexes: nil, - }} - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // a new claim should start with 0 rewards - suite.Equal(sdk.Coins(nil), syncedClaim.Reward) -} - -func (suite *InitializeEarnRewardTests) TestClaimAddedWhenClaimDoesNotExistAndRewardsExist() { - // When a claim doesn't exist, and a user deposits to a rewarded pool; - // then a claim is added with no rewards and indexes matching the global indexes - - vaultDenom := "usdx" - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(globalIndexes) - - owner := arbitraryAddress() - - suite.keeper.InitializeEarnReward(suite.ctx, vaultDenom, owner) - - syncedClaim, found := suite.keeper.GetEarnClaim(suite.ctx, owner) - suite.True(found) - // a new claim should start with the current global indexes - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // a new claim should start with 0 rewards - suite.Equal(sdk.Coins(nil), syncedClaim.Reward) -} - -func (suite *InitializeEarnRewardTests) TestClaimUpdatedWhenClaimExistsAndNoRewards() { - // When a claim exists, and a user deposits to a new non-rewarded pool; - // then the claim's rewards don't change - - preexistingvaultDenom := "preexisting" - preexistingIndexes := types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - } - - newVaultDenom := "btcb:usdx" - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: preexistingvaultDenom, - RewardIndexes: preexistingIndexes, - }, - }, - } - suite.storeEarnClaim(claim) - - // no global indexes stored as the new pool is not rewarded - - suite.keeper.InitializeEarnReward(suite.ctx, newVaultDenom, claim.Owner) - - syncedClaim, _ := suite.keeper.GetEarnClaim(suite.ctx, claim.Owner) - // The preexisting indexes shouldn't be changed. It doesn't strictly need the new vaultDenom either. - expectedIndexes := types.MultiRewardIndexes{ - { - CollateralType: preexistingvaultDenom, - RewardIndexes: preexistingIndexes, - }, - { - CollateralType: newVaultDenom, - RewardIndexes: nil, - }, - } - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // init should never alter the rewards - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *InitializeEarnRewardTests) TestClaimUpdatedWhenClaimExistsAndRewardsExist() { - // When a claim exists, and a user deposits to a new rewarded pool; - // then the claim's rewards don't change and the indexes are updated to match the global indexes - - preexistingvaultDenom := "preexisting" - preexistingIndexes := types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - } - - newVaultDenom := "btcb:usdx" - newIndexes := types.RewardIndexes{ - { - CollateralType: "otherrewarddenom", - RewardFactor: d("1000.001"), - }, - } - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: preexistingvaultDenom, - RewardIndexes: preexistingIndexes, - }, - }, - } - suite.storeEarnClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: preexistingvaultDenom, - RewardIndexes: increaseRewardFactors(preexistingIndexes), - }, - { - CollateralType: newVaultDenom, - RewardIndexes: newIndexes, - }, - } - suite.storeGlobalEarnIndexes(globalIndexes) - - suite.keeper.InitializeEarnReward(suite.ctx, newVaultDenom, claim.Owner) - - syncedClaim, _ := suite.keeper.GetEarnClaim(suite.ctx, claim.Owner) - // only the indexes for the new pool should be updated - expectedIndexes := types.MultiRewardIndexes{ - { - CollateralType: preexistingvaultDenom, - RewardIndexes: preexistingIndexes, - }, - { - CollateralType: newVaultDenom, - RewardIndexes: newIndexes, - }, - } - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // init should never alter the rewards - suite.Equal(claim.Reward, syncedClaim.Reward) -} diff --git a/x/incentive/keeper/rewards_earn_proportional_test.go b/x/incentive/keeper/rewards_earn_proportional_test.go deleted file mode 100644 index 83225b59..00000000 --- a/x/incentive/keeper/rewards_earn_proportional_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/0glabs/0g-chain/x/incentive/keeper" - "github.com/0glabs/0g-chain/x/incentive/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestGetProportionalRewardPeriod(t *testing.T) { - tests := []struct { - name string - giveRewardPeriod types.MultiRewardPeriod - giveTotalBkavaSupply sdkmath.Int - giveSingleBkavaSupply sdkmath.Int - wantRewardsPerSecond sdk.DecCoins - }{ - { - "full amount", - types.NewMultiRewardPeriod( - true, - "", - time.Time{}, - time.Time{}, - cs(c("ukava", 100), c("hard", 200)), - ), - i(100), - i(100), - toDcs(c("ukava", 100), c("hard", 200)), - }, - { - "3/4 amount", - types.NewMultiRewardPeriod( - true, - "", - time.Time{}, - time.Time{}, - cs(c("ukava", 100), c("hard", 200)), - ), - i(10_000000), - i(7_500000), - toDcs(c("ukava", 75), c("hard", 150)), - }, - { - "half amount", - types.NewMultiRewardPeriod( - true, - "", - time.Time{}, - time.Time{}, - cs(c("ukava", 100), c("hard", 200)), - ), - i(100), - i(50), - toDcs(c("ukava", 50), c("hard", 100)), - }, - { - "under 1 unit", - types.NewMultiRewardPeriod( - true, - "", - time.Time{}, - time.Time{}, - cs(c("ukava", 100), c("hard", 200)), - ), - i(1000), // total bkava - i(1), // bkava supply of this specific vault - dcs(dc("ukava", "0.1"), dc("hard", "0.2")), // rewards per second rounded to 0 if under 1ukava/1hard - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - rewardsPerSecond := keeper.GetProportionalRewardsPerSecond( - tt.giveRewardPeriod, - tt.giveTotalBkavaSupply, - tt.giveSingleBkavaSupply, - ) - - require.Equal(t, tt.wantRewardsPerSecond, rewardsPerSecond) - }) - } -} diff --git a/x/incentive/keeper/rewards_earn_staking_integration_test.go b/x/incentive/keeper/rewards_earn_staking_integration_test.go deleted file mode 100644 index e8cb6fc6..00000000 --- a/x/incentive/keeper/rewards_earn_staking_integration_test.go +++ /dev/null @@ -1,191 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/0glabs/0g-chain/app" - earntypes "github.com/0glabs/0g-chain/x/earn/types" - "github.com/0glabs/0g-chain/x/incentive/testutil" - "github.com/0glabs/0g-chain/x/incentive/types" - abci "github.com/cometbft/cometbft/abci/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" -) - -type EarnStakingRewardsIntegrationTestSuite struct { - testutil.IntegrationTester - - keeper TestKeeper - userAddrs []sdk.AccAddress - valAddrs []sdk.ValAddress -} - -func TestEarnStakingRewardsIntegrationTestSuite(t *testing.T) { - suite.Run(t, new(EarnStakingRewardsIntegrationTestSuite)) -} - -func (suite *EarnStakingRewardsIntegrationTestSuite) SetupTest() { - suite.IntegrationTester.SetupTest() - - suite.keeper = TestKeeper{ - Keeper: suite.App.GetIncentiveKeeper(), - } - - _, addrs := app.GeneratePrivKeyAddressPairs(5) - suite.userAddrs = addrs[0:2] - suite.valAddrs = []sdk.ValAddress{ - sdk.ValAddress(addrs[2]), - sdk.ValAddress(addrs[3]), - } - - // Setup app with test state - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(addrs[0], cs(c("ukava", 1e12))). - WithSimpleAccount(addrs[1], cs(c("ukava", 1e12))). - WithSimpleAccount(addrs[2], cs(c("ukava", 1e12))). - WithSimpleAccount(addrs[3], cs(c("ukava", 1e12))) - - incentiveBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.GenesisTime). - WithSimpleEarnRewardPeriod("bkava", cs()) - - savingsBuilder := testutil.NewSavingsGenesisBuilder(). - WithSupportedDenoms("bkava") - - earnBuilder := testutil.NewEarnGenesisBuilder(). - WithAllowedVaults(earntypes.AllowedVault{ - Denom: "bkava", - Strategies: earntypes.StrategyTypes{earntypes.STRATEGY_TYPE_SAVINGS}, - IsPrivateVault: false, - AllowedDepositors: nil, - }) - - stakingBuilder := testutil.NewStakingGenesisBuilder() - - mintBuilder := testutil.NewMintGenesisBuilder(). - WithInflationMax(sdk.OneDec()). - WithInflationMin(sdk.OneDec()). - WithMinter(sdk.OneDec(), sdk.ZeroDec()). - WithMintDenom("ukava") - - suite.StartChainWithBuilders( - authBuilder, - incentiveBuilder, - savingsBuilder, - earnBuilder, - stakingBuilder, - mintBuilder, - ) -} - -func (suite *EarnStakingRewardsIntegrationTestSuite) TestStakingRewardsDistributed() { - // derivative 1: 8 total staked, 7 to earn, 1 not in earn - // derivative 2: 2 total staked, 1 to earn, 1 not in earn - userMintAmount0 := c("ukava", 8e9) - userMintAmount1 := c("ukava", 2e9) - - userDepositAmount0 := i(7e9) - userDepositAmount1 := i(1e9) - - // Create two validators - derivative0, err := suite.MintLiquidAnyValAddr(suite.userAddrs[0], suite.valAddrs[0], userMintAmount0) - suite.Require().NoError(err) - - derivative1, err := suite.MintLiquidAnyValAddr(suite.userAddrs[0], suite.valAddrs[1], userMintAmount1) - suite.Require().NoError(err) - - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[0], sdk.NewCoin(derivative0.Denom, userDepositAmount0), earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - err = suite.DeliverEarnMsgDeposit(suite.userAddrs[0], sdk.NewCoin(derivative1.Denom, userDepositAmount1), earntypes.STRATEGY_TYPE_SAVINGS) - suite.NoError(err) - - // Get derivative denoms - lq := suite.App.GetLiquidKeeper() - vaultDenom1 := lq.GetLiquidStakingTokenDenom(suite.valAddrs[0]) - vaultDenom2 := lq.GetLiquidStakingTokenDenom(suite.valAddrs[1]) - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.Ctx = suite.Ctx.WithBlockTime(previousAccrualTime) - - initialVault1RewardFactor := d("0.04") - initialVault2RewardFactor := d("0.04") - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: initialVault1RewardFactor, - }, - }, - }, - { - CollateralType: vaultDenom2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: initialVault2RewardFactor, - }, - }, - }, - } - - suite.keeper.storeGlobalEarnIndexes(suite.Ctx, globalIndexes) - - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, vaultDenom1, suite.Ctx.BlockTime()) - suite.keeper.SetEarnRewardAccrualTime(suite.Ctx, vaultDenom2, suite.Ctx.BlockTime()) - - val := suite.GetAbciValidator(suite.valAddrs[0]) - - // Mint tokens, distribute to validators, claim staking rewards - // 1 hour later - _, resBeginBlock := suite.NextBlockAfterWithReq( - 1*time.Hour, - abci.RequestEndBlock{}, - abci.RequestBeginBlock{ - LastCommitInfo: abci.CommitInfo{ - Votes: []abci.VoteInfo{{ - Validator: val, - SignedLastBlock: true, - }}, - }, - }, - ) - - // check time and factors - suite.StoredEarnTimeEquals(vaultDenom1, suite.Ctx.BlockTime()) - suite.StoredEarnTimeEquals(vaultDenom2, suite.Ctx.BlockTime()) - - validatorRewards, _ := suite.GetBeginBlockClaimedStakingRewards(resBeginBlock) - - suite.Require().Contains(validatorRewards, suite.valAddrs[0].String(), "there should be claim events for validator 1") - suite.Require().Contains(validatorRewards, suite.valAddrs[1].String(), "there should be claim events for validator 2") - - // Total staking rewards / total source shares (**deposited in earn** not total minted) - // types.RewardIndexes.Quo() uses Dec.Quo() which uses bankers rounding. - // So we need to use Dec.Quo() to also round vs Dec.QuoInt() which truncates - expectedIndexes1 := sdk.NewDecFromInt(validatorRewards[suite.valAddrs[0].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(userDepositAmount0)) - - expectedIndexes2 := sdk.NewDecFromInt(validatorRewards[suite.valAddrs[1].String()]. - AmountOf("ukava")). - Quo(sdk.NewDecFromInt(userDepositAmount1)) - - // Only contains staking rewards - suite.StoredEarnIndexesEqual(vaultDenom1, types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: initialVault1RewardFactor.Add(expectedIndexes1), - }, - }) - - suite.StoredEarnIndexesEqual(vaultDenom2, types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: initialVault2RewardFactor.Add(expectedIndexes2), - }, - }) -} diff --git a/x/incentive/keeper/rewards_earn_staking_test.go b/x/incentive/keeper/rewards_earn_staking_test.go deleted file mode 100644 index cbf249e6..00000000 --- a/x/incentive/keeper/rewards_earn_staking_test.go +++ /dev/null @@ -1,104 +0,0 @@ -package keeper_test - -import ( - "time" - - earntypes "github.com/0glabs/0g-chain/x/earn/types" - "github.com/0glabs/0g-chain/x/incentive/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func (suite *AccumulateEarnRewardsTests) TestStakingRewardsDistributed() { - vaultDenom1 := "bkava-meow" - vaultDenom2 := "bkava-woof" - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - vaultDenom1Supply := i(800000) - vaultDenom2Supply := i(200000) - - liquidKeeper := newFakeLiquidKeeper(). - addDerivative(suite.ctx, vaultDenom1, vaultDenom1Supply). - addDerivative(suite.ctx, vaultDenom2, vaultDenom2Supply) - - vault1Shares := d("700000") - vault2Shares := d("100000") - - // More bkava minted than deposited into earn - // Rewards are higher per-share as a result - earnKeeper := newFakeEarnKeeper(). - addVault(vaultDenom1, earntypes.NewVaultShare(vaultDenom1, vault1Shares)). - addVault(vaultDenom2, earntypes.NewVaultShare(vaultDenom2, vault2Shares)) - - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, liquidKeeper, earnKeeper) - - initialVault1RewardFactor := d("0.04") - initialVault2RewardFactor := d("0.04") - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: initialVault1RewardFactor, - }, - }, - }, - { - CollateralType: vaultDenom2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: initialVault2RewardFactor, - }, - }, - }, - } - - suite.storeGlobalEarnIndexes(globalIndexes) - - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom1, previousAccrualTime) - suite.keeper.SetEarnRewardAccrualTime(suite.ctx, vaultDenom2, previousAccrualTime) - - newAccrualTime := previousAccrualTime.Add(1 * time.Hour) - suite.ctx = suite.ctx.WithBlockTime(newAccrualTime) - - rewardPeriod := types.NewMultiRewardPeriod( - true, - "bkava", // reward period is set for "bkava" to apply to all vaults - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(), // no incentives, so only the staking rewards are distributed - ) - suite.keeper.AccumulateEarnRewards(suite.ctx, rewardPeriod) - - // check time and factors - - suite.storedTimeEquals(vaultDenom1, newAccrualTime) - suite.storedTimeEquals(vaultDenom2, newAccrualTime) - - // Only contains staking rewards - suite.storedIndexesEqual(vaultDenom1, types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: initialVault1RewardFactor. - Add(sdk.NewDecFromInt(vaultDenom1Supply). - QuoInt64(10). - MulInt64(3600). - Quo(vault1Shares)), - }, - }) - - suite.storedIndexesEqual(vaultDenom2, types.RewardIndexes{ - { - CollateralType: "ukava", - RewardFactor: initialVault2RewardFactor. - Add(sdk.NewDecFromInt(vaultDenom2Supply). - QuoInt64(10). - MulInt64(3600). - Quo(vault2Shares)), - }, - }) -} diff --git a/x/incentive/keeper/rewards_earn_sync_test.go b/x/incentive/keeper/rewards_earn_sync_test.go deleted file mode 100644 index 51c4ddbd..00000000 --- a/x/incentive/keeper/rewards_earn_sync_test.go +++ /dev/null @@ -1,473 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - earntypes "github.com/0glabs/0g-chain/x/earn/types" - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// SynchronizeEarnRewardTests runs unit tests for the keeper.SynchronizeEarnReward method -// -// inputs -// - claim in store (only claim.RewardIndexes, claim.Reward) -// - global indexes in store -// - shares function arg -// -// outputs -// - sets a claim -type SynchronizeEarnRewardTests struct { - unitTester -} - -func TestSynchronizeEarnReward(t *testing.T) { - suite.Run(t, new(SynchronizeEarnRewardTests)) -} - -func (suite *SynchronizeEarnRewardTests) TestClaimUpdatedWhenGlobalIndexesHaveIncreased() { - // This is the normal case - // Given some time has passed (meaning the global indexes have increased) - // When the claim is synced - // The user earns rewards for the time passed, and the claim indexes are updated - - originalReward := arbitraryCoins() - vaultDenom := "cats" - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeEarnClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("2000.002"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(globalIndexes) - - userShares := d("1000000000") - - suite.keeper.SynchronizeEarnReward(suite.ctx, vaultDenom, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetEarnClaim(suite.ctx, claim.Owner) - // indexes updated from global - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // new reward is (new index - old index) * user shares - suite.Equal( - cs(c("rewarddenom", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeEarnRewardTests) TestClaimUnchangedWhenGlobalIndexesUnchanged() { - // It should be safe to call SynchronizeEarnReward multiple times - - vaultDenom := "cats" - unchangingIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - } - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: unchangingIndexes, - } - suite.storeEarnClaim(claim) - - suite.storeGlobalEarnIndexes(unchangingIndexes) - - userShares := d("1000000000") - - suite.keeper.SynchronizeEarnReward(suite.ctx, vaultDenom, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetEarnClaim(suite.ctx, claim.Owner) - // claim should have the same rewards and indexes as before - suite.Equal(claim, syncedClaim) -} - -func (suite *SynchronizeEarnRewardTests) TestClaimUpdatedWhenNewRewardAdded() { - // When a new reward is added (via gov) for a vault the user has already deposited to, and the claim is synced; - // Then the user earns rewards for the time since the reward was added, and the indexes are added to the claim. - - originalReward := arbitraryCoins() - newlyRewardVaultDenom := "newlyRewardedVault" - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: "currentlyRewardedVault", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeEarnClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: "currentlyRewardedVault", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - }, - }, - { - CollateralType: newlyRewardVaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(globalIndexes) - - userShares := d("1000000000") - - suite.keeper.SynchronizeEarnReward(suite.ctx, newlyRewardVaultDenom, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetEarnClaim(suite.ctx, claim.Owner) - // the new indexes should be added to the claim, but the old ones should be unchanged - newlyRewrdedIndexes, _ := globalIndexes.Get(newlyRewardVaultDenom) - expectedIndexes := claim.RewardIndexes.With(newlyRewardVaultDenom, newlyRewrdedIndexes) - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // new reward is (new index - old index) * shares for the synced vault - // The old index for `newlyrewarded` isn't in the claim, so it's added starting at 0 for calculating the reward. - suite.Equal( - cs(c("otherreward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeEarnRewardTests) TestClaimUnchangedWhenNoReward() { - // When a vault is not rewarded but the user has deposited to that vault, and the claim is synced; - // Then the claim should be the same. - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeEarnClaim(claim) - - vaultDenom := "nonRewardVault" - // No global indexes stored as this vault is not rewarded - - userShares := d("1000000000") - - suite.keeper.SynchronizeEarnReward(suite.ctx, vaultDenom, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetEarnClaim(suite.ctx, claim.Owner) - suite.Equal(claim, syncedClaim) -} - -func (suite *SynchronizeEarnRewardTests) TestClaimUpdatedWhenNewRewardDenomAdded() { - // When a new reward coin is added (via gov) to an already rewarded vault (that the user has already deposited to), and the claim is synced; - // Then the user earns rewards for the time since the reward was added, and the new indexes are added. - - originalReward := arbitraryCoins() - vaultDenom := "cats" - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeEarnClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(globalIndexes) - - userShares := d("1000000000") - - suite.keeper.SynchronizeEarnReward(suite.ctx, vaultDenom, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetEarnClaim(suite.ctx, claim.Owner) - // indexes should have the new reward denom added - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // new reward is (new index - old index) * shares - // The old index for `otherreward` isn't in the claim, so it's added starting at 0 for calculating the reward. - suite.Equal( - cs(c("reward", 1_000_001_000_000), c("otherreward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeEarnRewardTests) TestClaimUpdatedWhenGlobalIndexesIncreasedAndSourceIsZero() { - // Given some time has passed (meaning the global indexes have increased) - // When the claim is synced, but the user has no shares - // The user earns no rewards for the time passed, but the claim indexes are updated - - vaultDenom := "cats" - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeEarnClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("2000.002"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(globalIndexes) - - userShares := d("0") - - suite.keeper.SynchronizeEarnReward(suite.ctx, vaultDenom, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetEarnClaim(suite.ctx, claim.Owner) - // indexes updated from global - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // reward is unchanged - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *SynchronizeEarnRewardTests) TestGetSyncedClaim_ClaimUnchangedWhenNoGlobalIndexes() { - vaultDenom_1 := "usdx" - owner := arbitraryAddress() - - earnKeeper := newFakeEarnKeeper(). - addDeposit(owner, earntypes.NewVaultShare("usdx", d("1000000000"))) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, earnKeeper) - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: owner, - Reward: nil, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: vaultDenom_1, - RewardIndexes: nil, // this state only happens because Init stores empty indexes - }, - }, - } - suite.storeEarnClaim(claim) - - // no global indexes for any vault - - syncedClaim, f := suite.keeper.GetSynchronizedEarnClaim(suite.ctx, claim.Owner) - suite.True(f) - - // indexes are unchanged - suite.Equal(claim.RewardIndexes, syncedClaim.RewardIndexes) - // reward is unchanged - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *SynchronizeEarnRewardTests) TestGetSyncedClaim_ClaimUpdatedWhenMissingIndexAndHasNoSourceShares() { - vaultDenom_1 := "usdx" - vaultDenom_2 := "ukava" - owner := arbitraryAddress() - - // owner has no shares in any vault - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, newFakeEarnKeeper()) - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: owner, - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: vaultDenom_1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom1", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeEarnClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: vaultDenom_1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom1", - RewardFactor: d("2000.002"), - }, - }, - }, - { - CollateralType: vaultDenom_2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom2", - RewardFactor: d("2000.002"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(globalIndexes) - - syncedClaim, f := suite.keeper.GetSynchronizedEarnClaim(suite.ctx, claim.Owner) - suite.True(f) - - // indexes updated from global - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // reward is unchanged - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *SynchronizeEarnRewardTests) TestGetSyncedClaim_ClaimUpdatedWhenMissingIndexButHasSourceShares() { - VaultDenom_1 := "usdx" - VaultDenom_2 := "ukava" - owner := arbitraryAddress() - - earnKeeper := newFakeEarnKeeper(). - addVault(VaultDenom_1, earntypes.NewVaultShare(VaultDenom_1, d("1000000000"))). - addVault(VaultDenom_2, earntypes.NewVaultShare(VaultDenom_2, d("1000000000"))). - addDeposit(owner, earntypes.NewVaultShare(VaultDenom_1, d("1000000000"))). - addDeposit(owner, earntypes.NewVaultShare(VaultDenom_2, d("1000000000"))) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, earnKeeper) - - claim := types.EarnClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: owner, - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: VaultDenom_1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom1", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeEarnClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: VaultDenom_1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom1", - RewardFactor: d("2000.002"), - }, - }, - }, - { - CollateralType: VaultDenom_2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom2", - RewardFactor: d("2000.002"), - }, - }, - }, - } - suite.storeGlobalEarnIndexes(globalIndexes) - - syncedClaim, f := suite.keeper.GetSynchronizedEarnClaim(suite.ctx, claim.Owner) - suite.True(f) - - // indexes updated from global - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // reward is incremented - expectedReward := cs(c("rewarddenom1", 1_000_001_000_000), c("rewarddenom2", 2_000_002_000_000)) - suite.Equal(claim.Reward.Add(expectedReward...), syncedClaim.Reward) -} diff --git a/x/incentive/keeper/rewards_savings.go b/x/incentive/keeper/rewards_savings.go deleted file mode 100644 index 04d7229c..00000000 --- a/x/incentive/keeper/rewards_savings.go +++ /dev/null @@ -1,150 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/incentive/types" - savingstypes "github.com/0glabs/0g-chain/x/savings/types" -) - -// AccumulateSavingsRewards calculates new rewards to distribute this block and updates the global indexes -func (k Keeper) AccumulateSavingsRewards(ctx sdk.Context, rewardPeriod types.MultiRewardPeriod) { - previousAccrualTime, found := k.GetSavingsRewardAccrualTime(ctx, rewardPeriod.CollateralType) - if !found { - previousAccrualTime = ctx.BlockTime() - } - - indexes, found := k.GetSavingsRewardIndexes(ctx, rewardPeriod.CollateralType) - if !found { - indexes = types.RewardIndexes{} - } - - acc := types.NewAccumulator(previousAccrualTime, indexes) - - savingsMacc := k.accountKeeper.GetModuleAccount(ctx, savingstypes.ModuleName) - maccCoins := k.bankKeeper.GetAllBalances(ctx, savingsMacc.GetAddress()) - denomBalance := maccCoins.AmountOf(rewardPeriod.CollateralType) - - acc.Accumulate(rewardPeriod, sdk.NewDecFromInt(denomBalance), ctx.BlockTime()) - - k.SetSavingsRewardAccrualTime(ctx, rewardPeriod.CollateralType, acc.PreviousAccumulationTime) - - if len(acc.Indexes) > 0 { - // the store panics when setting empty or nil indexes - k.SetSavingsRewardIndexes(ctx, rewardPeriod.CollateralType, acc.Indexes) - } -} - -// InitializeSavingsReward initializes a savings claim by creating the claim and -// setting the reward factor indexes -func (k Keeper) InitializeSavingsReward(ctx sdk.Context, deposit savingstypes.Deposit) { - claim, found := k.GetSavingsClaim(ctx, deposit.Depositor) - if !found { - claim = types.NewSavingsClaim(deposit.Depositor, sdk.Coins{}, nil) - } - - rewardIndexes := claim.RewardIndexes - for _, coin := range deposit.Amount { - globalRewardIndexes, found := k.GetSavingsRewardIndexes(ctx, coin.Denom) - if !found { - globalRewardIndexes = types.RewardIndexes{} - } - rewardIndexes = rewardIndexes.With(coin.Denom, globalRewardIndexes) - } - claim.RewardIndexes = rewardIndexes - - k.SetSavingsClaim(ctx, claim) -} - -// SynchronizeSavingsReward updates the claim object by adding any accumulated rewards -// and updating the reward index value -func (k Keeper) SynchronizeSavingsReward(ctx sdk.Context, deposit savingstypes.Deposit, incomingDenoms []string) { - claim, found := k.GetSavingsClaim(ctx, deposit.Depositor) - if !found { - return - } - - // Set the reward factor on claim to the global reward factor for each incoming denom - for _, denom := range incomingDenoms { - globalRewardIndexes, found := k.GetSavingsRewardIndexes(ctx, denom) - if !found { - globalRewardIndexes = types.RewardIndexes{} - } - claim.RewardIndexes = claim.RewardIndexes.With(denom, globalRewardIndexes) - } - - // Existing denoms have their reward indexes + reward amount synced - existingDenoms := setDifference(getDenoms(deposit.Amount), incomingDenoms) - for _, denom := range existingDenoms { - claim = k.synchronizeSingleSavingsReward(ctx, claim, denom, sdk.NewDecFromInt(deposit.Amount.AmountOf(denom))) - } - - k.SetSavingsClaim(ctx, claim) -} - -// synchronizeSingleSavingsReward synchronizes a single rewarded savings denom in a savings claim. -// It returns the claim without setting in the store. -// The public methods for accessing and modifying claims are preferred over this one. Direct modification of claims is easy to get wrong. -func (k Keeper) synchronizeSingleSavingsReward(ctx sdk.Context, claim types.SavingsClaim, denom string, sourceShares sdk.Dec) types.SavingsClaim { - globalRewardIndexes, found := k.GetSavingsRewardIndexes(ctx, denom) - if !found { - // The global factor is only not found if - // - the savings denom has not started accumulating rewards yet (either there is no reward specified in params, or the reward start time hasn't been hit) - // - OR it was wrongly deleted from state (factors should never be removed while unsynced claims exist) - // If not found we could either skip this sync, or assume the global factor is zero. - // Skipping will avoid storing unnecessary factors in the claim for non rewarded denoms. - // And in the event a global factor is wrongly deleted, it will avoid this function panicking when calculating rewards. - return claim - } - - userRewardIndexes, found := claim.RewardIndexes.Get(denom) - if !found { - // Normally the reward indexes should always be found. - // But if a denom was not rewarded then becomes rewarded (ie a reward period is added to params), then the indexes will be missing from claims for that supplied denom. - // So given the reward period was just added, assume the starting value for any global reward indexes, which is an empty slice. - userRewardIndexes = types.RewardIndexes{} - } - - newRewards, err := k.CalculateRewards(userRewardIndexes, globalRewardIndexes, sourceShares) - if err != nil { - // Global reward factors should never decrease, as it would lead to a negative update to claim.Rewards. - // This panics if a global reward factor decreases or disappears between the old and new indexes. - panic(fmt.Sprintf("corrupted global reward indexes found: %v", err)) - } - - claim.Reward = claim.Reward.Add(newRewards...) - claim.RewardIndexes = claim.RewardIndexes.With(denom, globalRewardIndexes) - - return claim -} - -// GetSynchronizedSavingsClaim fetches a savings claim from the store and syncs rewards for all rewarded pools. -func (k Keeper) GetSynchronizedSavingsClaim(ctx sdk.Context, owner sdk.AccAddress) (types.SavingsClaim, bool) { - claim, found := k.GetSavingsClaim(ctx, owner) - if !found { - return types.SavingsClaim{}, false - } - - deposit, found := k.savingsKeeper.GetDeposit(ctx, owner) - if !found { - return types.SavingsClaim{}, false - } - - for _, coin := range deposit.Amount { - claim = k.synchronizeSingleSavingsReward(ctx, claim, coin.Denom, sdk.NewDecFromInt(coin.Amount)) - } - - return claim, true -} - -// SynchronizeSavingsClaim syncs a savings reward claim from its store -func (k Keeper) SynchronizeSavingsClaim(ctx sdk.Context, owner sdk.AccAddress) { - deposit, found := k.savingsKeeper.GetDeposit(ctx, owner) - if !found { - return - } - - k.SynchronizeSavingsReward(ctx, deposit, []string{}) -} diff --git a/x/incentive/keeper/rewards_savings_accum_test.go b/x/incentive/keeper/rewards_savings_accum_test.go deleted file mode 100644 index 7de9a425..00000000 --- a/x/incentive/keeper/rewards_savings_accum_test.go +++ /dev/null @@ -1,163 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - savingskeeper "github.com/0glabs/0g-chain/x/savings/keeper" - savingstypes "github.com/0glabs/0g-chain/x/savings/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/incentive/keeper" - "github.com/0glabs/0g-chain/x/incentive/testutil" - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// Test suite used for all keeper tests -type SavingsRewardsTestSuite struct { - suite.Suite - - keeper keeper.Keeper - savingsKeeper savingskeeper.Keeper - - app app.TestApp - ctx sdk.Context - - genesisTime time.Time - addrs []sdk.AccAddress -} - -// SetupTest is run automatically before each suite test -func (suite *SavingsRewardsTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - _, allAddrs := app.GeneratePrivKeyAddressPairs(10) - suite.addrs = allAddrs[:5] - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *SavingsRewardsTestSuite) SetupApp() { - suite.app = app.NewTestApp() - - suite.keeper = suite.app.GetIncentiveKeeper() - suite.savingsKeeper = suite.app.GetSavingsKeeper() - - suite.ctx = suite.app.NewContext(true, tmproto.Header{Height: 1, Time: suite.genesisTime}) -} - -func (suite *SavingsRewardsTestSuite) SetupWithGenState(authBuilder *app.AuthBankGenesisBuilder, incentBuilder testutil.IncentiveGenesisBuilder, - savingsGenesis savingstypes.GenesisState, -) { - suite.SetupApp() - - suite.app.InitializeFromGenesisStatesWithTime( - suite.genesisTime, - authBuilder.BuildMarshalled(suite.app.AppCodec()), - app.GenesisState{savingstypes.ModuleName: suite.app.AppCodec().MustMarshalJSON(&savingsGenesis)}, - incentBuilder.BuildMarshalled(suite.app.AppCodec()), - ) -} - -func (suite *SavingsRewardsTestSuite) TestAccumulateSavingsRewards() { - type args struct { - deposit sdk.Coin - rewardsPerSecond sdk.Coins - timeElapsed int - expectedRewardIndexes types.RewardIndexes - } - type test struct { - name string - args args - } - testCases := []test{ - { - "7 seconds", - args{ - deposit: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 7, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.856478000000000000")), - }, - }, - }, - { - "1 day", - args{ - deposit: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 86400, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("10571.385600000000000000")), - }, - }, - }, - { - "0 seconds", - args{ - deposit: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 0, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - }, - }, - }, - { - "multiple reward coins", - args{ - deposit: c("ukava", 1_000_000), - rewardsPerSecond: cs(c("hard", 122354), c("bnb", 567889)), - timeElapsed: 7, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("bnb", d("3.97522300000000000")), - types.NewRewardIndex("hard", d("0.856478000000000000")), - }, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - params := savingstypes.NewParams( - []string{"ukava"}, - ) - deposits := savingstypes.Deposits{ - savingstypes.NewDeposit( - suite.addrs[0], - sdk.NewCoins(tc.args.deposit), - ), - } - savingsGenesis := savingstypes.NewGenesisState(params, deposits) - - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[0], cs(c("ukava", 1e9))). - WithSimpleModuleAccount(savingstypes.ModuleName, sdk.NewCoins(tc.args.deposit)) - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleSavingsRewardPeriod(tc.args.deposit.Denom, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder, savingsGenesis) - - // Set up chain context at future time - runAtTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed)) - runCtx := suite.ctx.WithBlockTime(runAtTime) - - rewardPeriods, found := suite.keeper.GetSavingsRewardPeriods(runCtx, tc.args.deposit.Denom) - suite.Require().True(found) - suite.keeper.AccumulateSavingsRewards(runCtx, rewardPeriods) - - rewardIndexes, _ := suite.keeper.GetSavingsRewardIndexes(runCtx, tc.args.deposit.Denom) - suite.Require().Equal(tc.args.expectedRewardIndexes, rewardIndexes) - }) - } -} - -func TestSavingsRewardsTestSuite(t *testing.T) { - suite.Run(t, new(SavingsRewardsTestSuite)) -} diff --git a/x/incentive/keeper/rewards_savings_init_test.go b/x/incentive/keeper/rewards_savings_init_test.go deleted file mode 100644 index 26e4cfcb..00000000 --- a/x/incentive/keeper/rewards_savings_init_test.go +++ /dev/null @@ -1,194 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/incentive/types" - savingstypes "github.com/0glabs/0g-chain/x/savings/types" -) - -// InitializeSavingsRewardTests runs unit tests for the keeper.InitializeSavingsReward method -type InitializeSavingsRewardTests struct { - unitTester -} - -func TestInitializeSavingsRewardTests(t *testing.T) { - suite.Run(t, new(InitializeSavingsRewardTests)) -} - -func (suite *InitializeSavingsRewardTests) TestClaimAddedWhenClaimDoesNotExistAndNoRewards() { - // When a claim doesn't exist, and a user deposits to a non-rewarded pool; - // then a claim is added with no rewards and no indexes - - // no global indexes stored as this pool is not rewarded - - owner := arbitraryAddress() - - amount := sdk.NewCoin("test", sdk.OneInt()) - deposit := savingstypes.NewDeposit(owner, sdk.NewCoins(amount)) - - suite.keeper.InitializeSavingsReward(suite.ctx, deposit) - - syncedClaim, found := suite.keeper.GetSavingsClaim(suite.ctx, owner) - suite.True(found) - // A new claim should have empty indexes. It doesn't strictly need the poolID either. - expectedIndexes := types.MultiRewardIndexes{{ - CollateralType: amount.Denom, - RewardIndexes: nil, - }} - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // a new claim should start with 0 rewards - suite.Equal(sdk.Coins(nil), syncedClaim.Reward) -} - -func (suite *InitializeSavingsRewardTests) TestClaimAddedWhenClaimDoesNotExistAndRewardsExist() { - // When a claim doesn't exist, and a user deposits to a rewarded pool; - // then a claim is added with no rewards and indexes matching the global indexes - - amount := sdk.NewCoin("test", sdk.OneInt()) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: amount.Denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalSavingsIndexes(globalIndexes) - - owner := arbitraryAddress() - - deposit := savingstypes.NewDeposit(owner, sdk.NewCoins(amount)) - suite.keeper.InitializeSavingsReward(suite.ctx, deposit) - - syncedClaim, found := suite.keeper.GetSavingsClaim(suite.ctx, owner) - suite.True(found) - // a new claim should start with the current global indexes - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // a new claim should start with 0 rewards - suite.Equal(sdk.Coins(nil), syncedClaim.Reward) -} - -func (suite *InitializeSavingsRewardTests) TestClaimUpdatedWhenClaimExistsAndNoRewards() { - // When a claim exists, and a user deposits to a new non-rewarded denom; - // then the claim's rewards don't change - - preexistingDenom := "preexisting" - preexistingIndexes := types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - } - - claim := types.SavingsClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: preexistingDenom, - RewardIndexes: preexistingIndexes, - }, - }, - } - suite.storeSavingsClaim(claim) - - // no global indexes stored as the new denom is not rewarded - newDenom := "test" - deposit := savingstypes.NewDeposit(claim.Owner, sdk.NewCoins(sdk.NewCoin(newDenom, sdk.OneInt()))) - suite.keeper.InitializeSavingsReward(suite.ctx, deposit) - - syncedClaim, found := suite.keeper.GetSavingsClaim(suite.ctx, claim.Owner) - suite.True(found) - - // The preexisting indexes shouldn't be changed. It doesn't strictly need the new denom either. - expectedIndexes := types.MultiRewardIndexes{ - { - CollateralType: preexistingDenom, - RewardIndexes: preexistingIndexes, - }, - { - CollateralType: newDenom, - RewardIndexes: nil, - }, - } - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // init should never alter the rewards - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *InitializeSavingsRewardTests) TestClaimUpdatedWhenClaimExistsAndRewardsExist() { - // When a claim exists, and a user deposits to a new rewarded denom; - // then the claim's rewards don't change and the indexes are updated to match the global indexes - - preexistingDenom := "preexisting" - preexistingIndexes := types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - } - - newDenom := "test" - newIndexes := types.RewardIndexes{ - { - CollateralType: "otherrewarddenom", - RewardFactor: d("1000.001"), - }, - } - - claim := types.SavingsClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: preexistingDenom, - RewardIndexes: preexistingIndexes, - }, - }, - } - suite.storeSavingsClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: preexistingDenom, - RewardIndexes: increaseRewardFactors(preexistingIndexes), - }, - { - CollateralType: newDenom, - RewardIndexes: newIndexes, - }, - } - suite.storeGlobalSavingsIndexes(globalIndexes) - - deposit := savingstypes.NewDeposit(claim.Owner, sdk.NewCoins(sdk.NewCoin(newDenom, sdk.OneInt()))) - suite.keeper.InitializeSavingsReward(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetSavingsClaim(suite.ctx, claim.Owner) - // only the indexes for the new denom should be updated - expectedIndexes := types.MultiRewardIndexes{ - { - CollateralType: preexistingDenom, - RewardIndexes: preexistingIndexes, - }, - { - CollateralType: newDenom, - RewardIndexes: newIndexes, - }, - } - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // init should never alter the rewards - suite.Equal(claim.Reward, syncedClaim.Reward) -} diff --git a/x/incentive/keeper/rewards_savings_sync_test.go b/x/incentive/keeper/rewards_savings_sync_test.go deleted file mode 100644 index a14d458d..00000000 --- a/x/incentive/keeper/rewards_savings_sync_test.go +++ /dev/null @@ -1,245 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/incentive/types" - savingstypes "github.com/0glabs/0g-chain/x/savings/types" -) - -// SynchronizeSavingsRewardTests runs unit tests for the keeper.SynchronizeSavingsReward method -type SynchronizeSavingsRewardTests struct { - unitTester -} - -func TestSynchronizeSavingsReward(t *testing.T) { - suite.Run(t, new(SynchronizeSavingsRewardTests)) -} - -func (suite *SynchronizeSavingsRewardTests) TestClaimUpdatedWhenGlobalIndexesHaveIncreased() { - // This is the normal case - // Given some time has passed (meaning the global indexes have increased) - // When the claim is synced - // The user earns rewards for the time passed, and the claim indexes are updated - - originalReward := arbitraryCoins() - denom := "test" - - claim := types.SavingsClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeSavingsClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("2000.002"), - }, - }, - }, - } - suite.storeGlobalSavingsIndexes(globalIndexes) - - userShares := i(1e9) - deposit := savingstypes.NewDeposit(claim.Owner, sdk.NewCoins(sdk.NewCoin(denom, userShares))) - suite.keeper.SynchronizeSavingsReward(suite.ctx, deposit, []string{}) - - syncedClaim, _ := suite.keeper.GetSavingsClaim(suite.ctx, claim.Owner) - // indexes updated from global - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // new reward is (new index - old index) * user shares - suite.Equal( - cs(c("rewarddenom", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeSavingsRewardTests) TestClaimUnchangedWhenGlobalIndexesUnchanged() { - denom := "test" - unchangingIndexes := types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - } - - claim := types.SavingsClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: unchangingIndexes, - } - suite.storeSavingsClaim(claim) - - suite.storeGlobalSavingsIndexes(unchangingIndexes) - - userShares := i(1e9) - deposit := savingstypes.NewDeposit(claim.Owner, sdk.NewCoins(sdk.NewCoin(denom, userShares))) - suite.keeper.SynchronizeSavingsReward(suite.ctx, deposit, []string{}) - - syncedClaim, _ := suite.keeper.GetSavingsClaim(suite.ctx, claim.Owner) - // claim should have the same rewards and indexes as before - suite.Equal(claim, syncedClaim) -} - -func (suite *SynchronizeSavingsRewardTests) TestClaimUpdatedWhenNewRewardAdded() { - originalReward := arbitraryCoins() - newlyRewardedDenom := "newlyRewardedDenom" - - claim := types.SavingsClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: "currentlyRewardedDenom", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeSavingsClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: "currentlyRewardedDenom", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - }, - }, - { - CollateralType: newlyRewardedDenom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalSavingsIndexes(globalIndexes) - - userShares := i(1e9) - deposit := savingstypes.NewDeposit(claim.Owner, - sdk.NewCoins( - sdk.NewCoin("currentlyRewardedDenom", userShares), - sdk.NewCoin(newlyRewardedDenom, userShares), - ), - ) - - suite.keeper.SynchronizeSavingsReward(suite.ctx, deposit, []string{newlyRewardedDenom}) - - syncedClaim, _ := suite.keeper.GetSavingsClaim(suite.ctx, claim.Owner) - // the new indexes should be added to the claim and the old ones should be updated - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // new reward is (new index - old index) * shares for the synced deposit - // The old index for `newlyrewarded` isn't in the claim, so it's added starting at 0 for calculating the reward. - suite.Equal( - cs(c("reward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeSavingsRewardTests) TestClaimUpdatedWhenNewRewardDenomAdded() { - // When a new reward coin is added (via gov) to an already rewarded denom (that the user has already deposited to), and the claim is synced; - // Then the user earns rewards for the time since the reward was added, and the new indexes are added. - - originalReward := arbitraryCoins() - denom := "base" - - claim := types.SavingsClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeSavingsClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalSavingsIndexes(globalIndexes) - - userShares := i(1e9) - deposit := savingstypes.NewDeposit(claim.Owner, sdk.NewCoins(sdk.NewCoin(denom, userShares))) - suite.keeper.SynchronizeSavingsReward(suite.ctx, deposit, []string{}) - - syncedClaim, _ := suite.keeper.GetSavingsClaim(suite.ctx, claim.Owner) - // indexes should have the new reward denom added - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // new reward is (new index - old index) * shares - // The old index for `otherreward` isn't in the claim, so it's added starting at 0 for calculating the reward. - suite.Equal( - cs(c("reward", 1_000_001_000_000), c("otherreward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func getDenoms(coins sdk.Coins) []string { - denoms := []string{} - for _, coin := range coins { - denoms = append(denoms, coin.Denom) - } - return denoms -} diff --git a/x/incentive/keeper/rewards_supply.go b/x/incentive/keeper/rewards_supply.go deleted file mode 100644 index a9e3458b..00000000 --- a/x/incentive/keeper/rewards_supply.go +++ /dev/null @@ -1,312 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - hardtypes "github.com/0glabs/0g-chain/x/hard/types" - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// AccumulateHardSupplyRewards calculates new rewards to distribute this block and updates the global indexes to reflect this. -// The provided rewardPeriod must be valid to avoid panics in calculating time durations. -func (k Keeper) AccumulateHardSupplyRewards(ctx sdk.Context, rewardPeriod types.MultiRewardPeriod) { - previousAccrualTime, found := k.GetPreviousHardSupplyRewardAccrualTime(ctx, rewardPeriod.CollateralType) - if !found { - previousAccrualTime = ctx.BlockTime() - } - - indexes, found := k.GetHardSupplyRewardIndexes(ctx, rewardPeriod.CollateralType) - if !found { - indexes = types.RewardIndexes{} - } - - acc := types.NewAccumulator(previousAccrualTime, indexes) - - totalSource := k.getHardSupplyTotalSourceShares(ctx, rewardPeriod.CollateralType) - - acc.Accumulate(rewardPeriod, totalSource, ctx.BlockTime()) - - k.SetPreviousHardSupplyRewardAccrualTime(ctx, rewardPeriod.CollateralType, acc.PreviousAccumulationTime) - if len(acc.Indexes) > 0 { - // the store panics when setting empty or nil indexes - k.SetHardSupplyRewardIndexes(ctx, rewardPeriod.CollateralType, acc.Indexes) - } -} - -// getHardSupplyTotalSourceShares fetches the sum of all source shares for a supply reward. -// In the case of hard supply, this is the total supplied divided by the supply interest factor. -// This gives the "pre interest" value of the total supplied. -func (k Keeper) getHardSupplyTotalSourceShares(ctx sdk.Context, denom string) sdk.Dec { - totalSuppliedCoins, found := k.hardKeeper.GetSuppliedCoins(ctx) - if !found { - // assume no coins have been supplied - totalSuppliedCoins = sdk.NewCoins() - } - totalSupplied := totalSuppliedCoins.AmountOf(denom) - - interestFactor, found := k.hardKeeper.GetSupplyInterestFactor(ctx, denom) - if !found { - // assume nothing has been borrowed so the factor starts at it's default value - interestFactor = sdk.OneDec() - } - - // return supplied/factor to get the "pre interest" value of the current total supplied - return sdk.NewDecFromInt(totalSupplied).Quo(interestFactor) -} - -// InitializeHardSupplyReward initializes the supply-side of a hard liquidity provider claim -// by creating the claim and setting the supply reward factor index -func (k Keeper) InitializeHardSupplyReward(ctx sdk.Context, deposit hardtypes.Deposit) { - claim, found := k.GetHardLiquidityProviderClaim(ctx, deposit.Depositor) - if !found { - claim = types.NewHardLiquidityProviderClaim(deposit.Depositor, sdk.Coins{}, nil, nil) - } - - var supplyRewardIndexes types.MultiRewardIndexes - for _, coin := range deposit.Amount { - globalRewardIndexes, found := k.GetHardSupplyRewardIndexes(ctx, coin.Denom) - if !found { - globalRewardIndexes = types.RewardIndexes{} - } - supplyRewardIndexes = supplyRewardIndexes.With(coin.Denom, globalRewardIndexes) - } - - claim.SupplyRewardIndexes = supplyRewardIndexes - k.SetHardLiquidityProviderClaim(ctx, claim) -} - -// SynchronizeHardSupplyReward updates the claim object by adding any accumulated rewards -// and updating the reward index value -func (k Keeper) SynchronizeHardSupplyReward(ctx sdk.Context, deposit hardtypes.Deposit) { - claim, found := k.GetHardLiquidityProviderClaim(ctx, deposit.Depositor) - if !found { - return - } - - // Source shares for hard deposits is their normalized deposit amount - normalizedDeposit, err := deposit.NormalizedDeposit() - if err != nil { - panic(fmt.Sprintf("during deposit reward sync, could not get normalized deposit for %s: %s", deposit.Depositor, err.Error())) - } - - for _, normedDeposit := range normalizedDeposit { - claim = k.synchronizeSingleHardSupplyReward(ctx, claim, normedDeposit.Denom, normedDeposit.Amount) - } - k.SetHardLiquidityProviderClaim(ctx, claim) -} - -// synchronizeSingleHardSupplyReward synchronizes a single rewarded supply denom in a hard claim. -// It returns the claim without setting in the store. -// The public methods for accessing and modifying claims are preferred over this one. Direct modification of claims is easy to get wrong. -func (k Keeper) synchronizeSingleHardSupplyReward(ctx sdk.Context, claim types.HardLiquidityProviderClaim, denom string, sourceShares sdk.Dec) types.HardLiquidityProviderClaim { - globalRewardIndexes, found := k.GetHardSupplyRewardIndexes(ctx, denom) - if !found { - // The global factor is only not found if - // - the supply denom has not started accumulating rewards yet (either there is no reward specified in params, or the reward start time hasn't been hit) - // - OR it was wrongly deleted from state (factors should never be removed while unsynced claims exist) - // If not found we could either skip this sync, or assume the global factor is zero. - // Skipping will avoid storing unnecessary factors in the claim for non rewarded denoms. - // And in the event a global factor is wrongly deleted, it will avoid this function panicking when calculating rewards. - return claim - } - - userRewardIndexes, found := claim.SupplyRewardIndexes.Get(denom) - if !found { - // Normally the reward indexes should always be found. - // But if a denom was not rewarded then becomes rewarded (ie a reward period is added to params), then the indexes will be missing from claims for that supplied denom. - // So given the reward period was just added, assume the starting value for any global reward indexes, which is an empty slice. - userRewardIndexes = types.RewardIndexes{} - } - - newRewards, err := k.CalculateRewards(userRewardIndexes, globalRewardIndexes, sourceShares) - if err != nil { - // Global reward factors should never decrease, as it would lead to a negative update to claim.Rewards. - // This panics if a global reward factor decreases or disappears between the old and new indexes. - panic(fmt.Sprintf("corrupted global reward indexes found: %v", err)) - } - - claim.Reward = claim.Reward.Add(newRewards...) - claim.SupplyRewardIndexes = claim.SupplyRewardIndexes.With(denom, globalRewardIndexes) - - return claim -} - -// UpdateHardSupplyIndexDenoms adds any new deposit denoms to the claim's supply reward index -func (k Keeper) UpdateHardSupplyIndexDenoms(ctx sdk.Context, deposit hardtypes.Deposit) { - claim, found := k.GetHardLiquidityProviderClaim(ctx, deposit.Depositor) - if !found { - claim = types.NewHardLiquidityProviderClaim(deposit.Depositor, sdk.Coins{}, nil, nil) - } - - depositDenoms := getDenoms(deposit.Amount) - supplyRewardIndexDenoms := claim.SupplyRewardIndexes.GetCollateralTypes() - - supplyRewardIndexes := claim.SupplyRewardIndexes - - // Create a new multi-reward index in the claim for every new deposit denom - uniqueDepositDenoms := setDifference(depositDenoms, supplyRewardIndexDenoms) - - for _, denom := range uniqueDepositDenoms { - globalSupplyRewardIndexes, found := k.GetHardSupplyRewardIndexes(ctx, denom) - if !found { - globalSupplyRewardIndexes = types.RewardIndexes{} - } - supplyRewardIndexes = supplyRewardIndexes.With(denom, globalSupplyRewardIndexes) - } - - // Delete multi-reward index from claim if the collateral type is no longer deposited - uniqueSupplyRewardDenoms := setDifference(supplyRewardIndexDenoms, depositDenoms) - - for _, denom := range uniqueSupplyRewardDenoms { - supplyRewardIndexes = supplyRewardIndexes.RemoveRewardIndex(denom) - } - - claim.SupplyRewardIndexes = supplyRewardIndexes - k.SetHardLiquidityProviderClaim(ctx, claim) -} - -// SynchronizeHardLiquidityProviderClaim adds any accumulated rewards -func (k Keeper) SynchronizeHardLiquidityProviderClaim(ctx sdk.Context, owner sdk.AccAddress) { - // Synchronize any hard liquidity supply-side rewards - deposit, foundDeposit := k.hardKeeper.GetDeposit(ctx, owner) - if foundDeposit { - k.SynchronizeHardSupplyReward(ctx, deposit) - } - - // Synchronize any hard liquidity borrow-side rewards - borrow, foundBorrow := k.hardKeeper.GetBorrow(ctx, owner) - if foundBorrow { - k.SynchronizeHardBorrowReward(ctx, borrow) - } -} - -// SimulateHardSynchronization calculates a user's outstanding hard rewards by simulating reward synchronization -func (k Keeper) SimulateHardSynchronization(ctx sdk.Context, claim types.HardLiquidityProviderClaim) types.HardLiquidityProviderClaim { - // 1. Simulate Hard supply-side rewards - for _, ri := range claim.SupplyRewardIndexes { - globalRewardIndexes, foundGlobalRewardIndexes := k.GetHardSupplyRewardIndexes(ctx, ri.CollateralType) - if !foundGlobalRewardIndexes { - continue - } - - userRewardIndexes, foundUserRewardIndexes := claim.SupplyRewardIndexes.GetRewardIndex(ri.CollateralType) - if !foundUserRewardIndexes { - continue - } - - userRewardIndexIndex, foundUserRewardIndexIndex := claim.SupplyRewardIndexes.GetRewardIndexIndex(ri.CollateralType) - if !foundUserRewardIndexIndex { - continue - } - - for _, globalRewardIndex := range globalRewardIndexes { - userRewardIndex, foundUserRewardIndex := userRewardIndexes.RewardIndexes.GetRewardIndex(globalRewardIndex.CollateralType) - if !foundUserRewardIndex { - userRewardIndex = types.NewRewardIndex(globalRewardIndex.CollateralType, sdk.ZeroDec()) - userRewardIndexes.RewardIndexes = append(userRewardIndexes.RewardIndexes, userRewardIndex) - claim.SupplyRewardIndexes[userRewardIndexIndex].RewardIndexes = append(claim.SupplyRewardIndexes[userRewardIndexIndex].RewardIndexes, userRewardIndex) - } - - globalRewardFactor := globalRewardIndex.RewardFactor - userRewardFactor := userRewardIndex.RewardFactor - rewardsAccumulatedFactor := globalRewardFactor.Sub(userRewardFactor) - if rewardsAccumulatedFactor.IsZero() { - continue - } - deposit, found := k.hardKeeper.GetDeposit(ctx, claim.GetOwner()) - if !found { - continue - } - newRewardsAmount := rewardsAccumulatedFactor.Mul(sdk.NewDecFromInt(deposit.Amount.AmountOf(ri.CollateralType))).RoundInt() - if newRewardsAmount.IsZero() || newRewardsAmount.IsNegative() { - continue - } - - factorIndex, foundFactorIndex := userRewardIndexes.RewardIndexes.GetFactorIndex(globalRewardIndex.CollateralType) - if !foundFactorIndex { - continue - } - claim.SupplyRewardIndexes[userRewardIndexIndex].RewardIndexes[factorIndex].RewardFactor = globalRewardIndex.RewardFactor - newRewardsCoin := sdk.NewCoin(userRewardIndex.CollateralType, newRewardsAmount) - claim.Reward = claim.Reward.Add(newRewardsCoin) - } - } - - // 2. Simulate Hard borrow-side rewards - for _, ri := range claim.BorrowRewardIndexes { - globalRewardIndexes, foundGlobalRewardIndexes := k.GetHardBorrowRewardIndexes(ctx, ri.CollateralType) - if !foundGlobalRewardIndexes { - continue - } - - userRewardIndexes, foundUserRewardIndexes := claim.BorrowRewardIndexes.GetRewardIndex(ri.CollateralType) - if !foundUserRewardIndexes { - continue - } - - userRewardIndexIndex, foundUserRewardIndexIndex := claim.BorrowRewardIndexes.GetRewardIndexIndex(ri.CollateralType) - if !foundUserRewardIndexIndex { - continue - } - - for _, globalRewardIndex := range globalRewardIndexes { - userRewardIndex, foundUserRewardIndex := userRewardIndexes.RewardIndexes.GetRewardIndex(globalRewardIndex.CollateralType) - if !foundUserRewardIndex { - userRewardIndex = types.NewRewardIndex(globalRewardIndex.CollateralType, sdk.ZeroDec()) - userRewardIndexes.RewardIndexes = append(userRewardIndexes.RewardIndexes, userRewardIndex) - claim.BorrowRewardIndexes[userRewardIndexIndex].RewardIndexes = append(claim.BorrowRewardIndexes[userRewardIndexIndex].RewardIndexes, userRewardIndex) - } - - globalRewardFactor := globalRewardIndex.RewardFactor - userRewardFactor := userRewardIndex.RewardFactor - rewardsAccumulatedFactor := globalRewardFactor.Sub(userRewardFactor) - if rewardsAccumulatedFactor.IsZero() { - continue - } - borrow, found := k.hardKeeper.GetBorrow(ctx, claim.GetOwner()) - if !found { - continue - } - newRewardsAmount := rewardsAccumulatedFactor.Mul(sdk.NewDecFromInt(borrow.Amount.AmountOf(ri.CollateralType))).RoundInt() - if newRewardsAmount.IsZero() || newRewardsAmount.IsNegative() { - continue - } - - factorIndex, foundFactorIndex := userRewardIndexes.RewardIndexes.GetFactorIndex(globalRewardIndex.CollateralType) - if !foundFactorIndex { - continue - } - claim.BorrowRewardIndexes[userRewardIndexIndex].RewardIndexes[factorIndex].RewardFactor = globalRewardIndex.RewardFactor - newRewardsCoin := sdk.NewCoin(userRewardIndex.CollateralType, newRewardsAmount) - claim.Reward = claim.Reward.Add(newRewardsCoin) - } - } - - return claim -} - -// Set setDifference: A - B -func setDifference(a, b []string) (diff []string) { - m := make(map[string]bool) - - for _, item := range b { - m[item] = true - } - - for _, item := range a { - if _, ok := m[item]; !ok { - diff = append(diff, item) - } - } - return -} - -func getDenoms(coins sdk.Coins) []string { - denoms := []string{} - for _, coin := range coins { - denoms = append(denoms, coin.Denom) - } - return denoms -} diff --git a/x/incentive/keeper/rewards_supply_accum_test.go b/x/incentive/keeper/rewards_supply_accum_test.go deleted file mode 100644 index ef845190..00000000 --- a/x/incentive/keeper/rewards_supply_accum_test.go +++ /dev/null @@ -1,321 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -type AccumulateSupplyRewardsTests struct { - unitTester -} - -func (suite *AccumulateSupplyRewardsTests) storedTimeEquals(denom string, expected time.Time) { - storedTime, found := suite.keeper.GetPreviousHardSupplyRewardAccrualTime(suite.ctx, denom) - suite.True(found) - suite.Equal(expected, storedTime) -} - -func (suite *AccumulateSupplyRewardsTests) storedIndexesEqual(denom string, expected types.RewardIndexes) { - storedIndexes, found := suite.keeper.GetHardSupplyRewardIndexes(suite.ctx, denom) - suite.Equal(found, expected != nil) - - if found { - suite.Equal(expected, storedIndexes) - } else { - suite.Empty(storedIndexes) - } -} - -func TestAccumulateSupplyRewards(t *testing.T) { - suite.Run(t, new(AccumulateSupplyRewardsTests)) -} - -func (suite *AccumulateSupplyRewardsTests) TestStateUpdatedWhenBlockTimeHasIncreased() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalSupply(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - suite.storeGlobalSupplyIndexes(types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - }) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardSupplyRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - newAccrualTime := previousAccrualTime.Add(1 * time.Hour) - suite.ctx = suite.ctx.WithBlockTime(newAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(denom, newAccrualTime) - suite.storedIndexesEqual(denom, types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("7.22"), - }, - { - CollateralType: "ukava", - RewardFactor: d("3.64"), - }, - }) -} - -func (suite *AccumulateSupplyRewardsTests) TestStateUnchangedWhenBlockTimeHasNotIncreased() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalSupply(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalSupplyIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardSupplyRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(denom, previousAccrualTime) - expected, f := previousIndexes.Get(denom) - suite.True(f) - suite.storedIndexesEqual(denom, expected) -} - -func (suite *AccumulateSupplyRewardsTests) TestNoAccumulationWhenSourceSharesAreZero() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper() // zero total supplys - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalSupplyIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardSupplyRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(7 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(denom, firstAccrualTime) - expected, f := previousIndexes.Get(denom) - suite.True(f) - suite.storedIndexesEqual(denom, expected) -} - -func (suite *AccumulateSupplyRewardsTests) TestStateAddedWhenStateDoesNotExist() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalSupply(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), - ) - - firstAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, period) - - // After the first accumulation only the current block time should be stored. - // The indexes will be empty as no time has passed since the previous block because it didn't exist. - suite.storedTimeEquals(denom, firstAccrualTime) - suite.storedIndexesEqual(denom, nil) - - secondAccrualTime := firstAccrualTime.Add(10 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(secondAccrualTime) - - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, period) - - // After the second accumulation both current block time and indexes should be stored. - suite.storedTimeEquals(denom, secondAccrualTime) - suite.storedIndexesEqual(denom, types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.01"), - }, - }) -} - -func (suite *AccumulateSupplyRewardsTests) TestNoPanicWhenStateDoesNotExist() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper() - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(), - ) - - accrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(accrualTime) - - // Accumulate with no source shares and no rewards per second will result in no increment to the indexes. - // No increment and no previous indexes stored, results in an updated of nil. Setting this in the state panics. - // Check there is no panic. - suite.NotPanics(func() { - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, period) - }) - - suite.storedTimeEquals(denom, accrualTime) - suite.storedIndexesEqual(denom, nil) -} - -func (suite *AccumulateSupplyRewardsTests) TestNoAccumulationWhenBeforeStartTime() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalSupply(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: denom, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalSupplyIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardSupplyRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(10 * time.Second) - - period := types.NewMultiRewardPeriod( - true, - denom, - firstAccrualTime.Add(time.Nanosecond), // start time after accrual time - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, period) - - // The accrual time should be updated, but the indexes unchanged - suite.storedTimeEquals(denom, firstAccrualTime) - expectedIndexes, f := previousIndexes.Get(denom) - suite.True(f) - suite.storedIndexesEqual(denom, expectedIndexes) -} - -func (suite *AccumulateSupplyRewardsTests) TestPanicWhenCurrentTimeLessThanPrevious() { - denom := "bnb" - - hardKeeper := newFakeHardKeeper().addTotalSupply(c(denom, 1e6), d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, hardKeeper, nil, nil, nil, nil, nil, nil) - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousHardSupplyRewardAccrualTime(suite.ctx, denom, previousAccrualTime) - - firstAccrualTime := time.Time{} - - period := types.NewMultiRewardPeriod( - true, - denom, - time.Time{}, // start time after accrual time - distantFuture, - cs(c("hard", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.Panics(func() { - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, period) - }) -} diff --git a/x/incentive/keeper/rewards_supply_init_test.go b/x/incentive/keeper/rewards_supply_init_test.go deleted file mode 100644 index 2571271f..00000000 --- a/x/incentive/keeper/rewards_supply_init_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// InitializeHardSupplyRewardTests runs unit tests for the keeper.InitializeHardSupplyReward method -type InitializeHardSupplyRewardTests struct { - unitTester -} - -func TestInitializeHardSupplyReward(t *testing.T) { - suite.Run(t, new(InitializeHardSupplyRewardTests)) -} - -func (suite *InitializeHardSupplyRewardTests) TestClaimIndexesAreSetWhenClaimExists() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - // Indexes should always be empty when initialize is called. - // If initialize is called then the user must have repaid their deposit positions, - // which means UpdateHardSupplyIndexDenoms was called and should have remove indexes. - SupplyRewardIndexes: types.MultiRewardIndexes{}, - } - suite.storeHardClaim(claim) - - globalIndexes := nonEmptyMultiRewardIndexes - suite.storeGlobalSupplyIndexes(globalIndexes) - - deposit := NewHardDepositBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.InitializeHardSupplyReward(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.SupplyRewardIndexes) -} - -func (suite *InitializeHardSupplyRewardTests) TestClaimIndexesAreSetWhenClaimDoesNotExist() { - globalIndexes := nonEmptyMultiRewardIndexes - suite.storeGlobalSupplyIndexes(globalIndexes) - - owner := arbitraryAddress() - deposit := NewHardDepositBuilder(owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.InitializeHardSupplyReward(suite.ctx, deposit) - - syncedClaim, found := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, owner) - suite.True(found) - suite.Equal(globalIndexes, syncedClaim.SupplyRewardIndexes) -} - -func (suite *InitializeHardSupplyRewardTests) TestClaimIndexesAreSetEmptyForMissingIndexes() { - globalIndexes := nonEmptyMultiRewardIndexes - suite.storeGlobalSupplyIndexes(globalIndexes) - - owner := arbitraryAddress() - // Supply a denom that is not in the global indexes. - // This happens when a deposit denom has no rewards associated with it. - expectedIndexes := appendUniqueEmptyMultiRewardIndex(globalIndexes) - depositedDenoms := extractCollateralTypes(expectedIndexes) - deposit := NewHardDepositBuilder(owner). - WithArbitrarySourceShares(depositedDenoms...). - Build() - - suite.keeper.InitializeHardSupplyReward(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, owner) - suite.Equal(expectedIndexes, syncedClaim.SupplyRewardIndexes) -} diff --git a/x/incentive/keeper/rewards_supply_sync_test.go b/x/incentive/keeper/rewards_supply_sync_test.go deleted file mode 100644 index 71574cb3..00000000 --- a/x/incentive/keeper/rewards_supply_sync_test.go +++ /dev/null @@ -1,342 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - hardtypes "github.com/0glabs/0g-chain/x/hard/types" - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// SynchronizeHardSupplyRewardTests runs unit tests for the keeper.SynchronizeHardSupplyReward method -type SynchronizeHardSupplyRewardTests struct { - unitTester -} - -func TestSynchronizeHardSupplyReward(t *testing.T) { - suite.Run(t, new(SynchronizeHardSupplyRewardTests)) -} - -func (suite *SynchronizeHardSupplyRewardTests) TestClaimIndexesAreUpdatedWhenGlobalIndexesHaveIncreased() { - // This is the normal case - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - SupplyRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - - globalIndexes := increaseAllRewardFactors(nonEmptyMultiRewardIndexes) - suite.storeGlobalSupplyIndexes(globalIndexes) - deposit := NewHardDepositBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(claim.SupplyRewardIndexes)...). - Build() - - suite.keeper.SynchronizeHardSupplyReward(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.SupplyRewardIndexes) -} - -func (suite *SynchronizeHardSupplyRewardTests) TestClaimIndexesAreUnchangedWhenGlobalIndexesUnchanged() { - // It should be safe to call SynchronizeHardSupplyReward multiple times - - unchangingIndexes := nonEmptyMultiRewardIndexes - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - SupplyRewardIndexes: unchangingIndexes, - } - suite.storeHardClaim(claim) - - suite.storeGlobalSupplyIndexes(unchangingIndexes) - - deposit := NewHardDepositBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(unchangingIndexes)...). - Build() - - suite.keeper.SynchronizeHardSupplyReward(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(unchangingIndexes, syncedClaim.SupplyRewardIndexes) -} - -func (suite *SynchronizeHardSupplyRewardTests) TestClaimIndexesAreUpdatedWhenNewRewardAdded() { - // When a new reward is added (via gov) for a hard deposit denom the user has already deposited, and the claim is synced; - // Then the new reward's index should be added to the claim. - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - SupplyRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - - globalIndexes := appendUniqueMultiRewardIndex(nonEmptyMultiRewardIndexes) - suite.storeGlobalSupplyIndexes(globalIndexes) - - deposit := NewHardDepositBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.SynchronizeHardSupplyReward(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.SupplyRewardIndexes) -} - -func (suite *SynchronizeHardSupplyRewardTests) TestClaimIndexesAreUpdatedWhenNewRewardDenomAdded() { - // When a new reward coin is added (via gov) to an already rewarded deposit denom (that the user has already deposited), and the claim is synced; - // Then the new reward coin's index should be added to the claim. - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - SupplyRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - - globalIndexes := appendUniqueRewardIndexToFirstItem(nonEmptyMultiRewardIndexes) - suite.storeGlobalSupplyIndexes(globalIndexes) - - deposit := NewHardDepositBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.SynchronizeHardSupplyReward(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.SupplyRewardIndexes) -} - -func (suite *SynchronizeHardSupplyRewardTests) TestRewardIsIncrementedWhenGlobalIndexesHaveIncreased() { - // This is the normal case - // Given some time has passed (meaning the global indexes have increased) - // When the claim is synced - // The user earns rewards for the time passed - - originalReward := arbitraryCoins() - - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - SupplyRewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: "depositdenom", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeHardClaim(claim) - - suite.storeGlobalSupplyIndexes(types.MultiRewardIndexes{ - { - CollateralType: "depositdenom", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("2000.002"), - }, - }, - }, - }) - - deposit := NewHardDepositBuilder(claim.Owner). - WithSourceShares("depositdenom", 1e9). - Build() - - suite.keeper.SynchronizeHardSupplyReward(suite.ctx, deposit) - - // new reward is (new index - old index) * deposit amount - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal( - cs(c("rewarddenom", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeHardSupplyRewardTests) TestRewardIsIncrementedWhenNewRewardAdded() { - // When a new reward is added (via gov) for a hard deposit denom the user has already deposited, and the claim is synced - // Then the user earns rewards for the time since the reward was added - - originalReward := arbitraryCoins() - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - SupplyRewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: "rewarded", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeHardClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: "rewarded", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - }, - }, - { - CollateralType: "newlyrewarded", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalSupplyIndexes(globalIndexes) - - deposit := NewHardDepositBuilder(claim.Owner). - WithSourceShares("rewarded", 1e9). - WithSourceShares("newlyrewarded", 1e9). - Build() - - suite.keeper.SynchronizeHardSupplyReward(suite.ctx, deposit) - - // new reward is (new index - old index) * deposit amount for each deposited denom - // The old index for `newlyrewarded` isn't in the claim, so it's added starting at 0 for calculating the reward. - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal( - cs(c("otherreward", 1_000_001_000_000), c("reward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeHardSupplyRewardTests) TestRewardIsIncrementedWhenNewRewardDenomAdded() { - // When a new reward coin is added (via gov) to an already rewarded deposit denom (that the user has already deposited), and the claim is synced; - // Then the user earns rewards for the time since the reward was added - - originalReward := arbitraryCoins() - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - SupplyRewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: "deposited", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeHardClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: "deposited", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalSupplyIndexes(globalIndexes) - - deposit := NewHardDepositBuilder(claim.Owner). - WithSourceShares("deposited", 1e9). - Build() - - suite.keeper.SynchronizeHardSupplyReward(suite.ctx, deposit) - - // new reward is (new index - old index) * deposit amount for each deposited denom - // The old index for `otherreward` isn't in the claim, so it's added starting at 0 for calculating the reward. - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal( - cs(c("reward", 1_000_001_000_000), c("otherreward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -// HardDepositBuilder is a tool for creating a hard deposit in tests. -// The builder inherits from hard.Deposit, so fields can be accessed directly if a helper method doesn't exist. -type HardDepositBuilder struct { - hardtypes.Deposit -} - -// NewHardDepositBuilder creates a HardDepositBuilder containing an empty deposit. -func NewHardDepositBuilder(depositor sdk.AccAddress) HardDepositBuilder { - return HardDepositBuilder{ - Deposit: hardtypes.Deposit{ - Depositor: depositor, - }, - } -} - -// Build assembles and returns the final deposit. -func (builder HardDepositBuilder) Build() hardtypes.Deposit { return builder.Deposit } - -// WithSourceShares adds a deposit amount and factor such that the source shares for this deposit is equal to specified. -// With a factor of 1, the deposit amount is the source shares. This picks an arbitrary factor to ensure factors are accounted for in production code. -func (builder HardDepositBuilder) WithSourceShares(denom string, shares int64) HardDepositBuilder { - if !builder.Amount.AmountOf(denom).Equal(sdk.ZeroInt()) { - panic("adding to amount with existing denom not implemented") - } - if _, f := builder.Index.GetInterestFactor(denom); f { - panic("adding to indexes with existing denom not implemented") - } - - // pick arbitrary factor - factor := sdk.MustNewDecFromStr("2") - - // Calculate deposit amount that would equal the requested source shares given the above factor. - amt := sdkmath.NewInt(shares).Mul(factor.RoundInt()) - - builder.Amount = builder.Amount.Add(sdk.NewCoin(denom, amt)) - builder.Index = builder.Index.SetInterestFactor(denom, factor) - return builder -} - -// WithArbitrarySourceShares adds arbitrary deposit amounts and indexes for each specified denom. -func (builder HardDepositBuilder) WithArbitrarySourceShares(denoms ...string) HardDepositBuilder { - const arbitraryShares = 1e9 - for _, denom := range denoms { - builder = builder.WithSourceShares(denom, arbitraryShares) - } - return builder -} diff --git a/x/incentive/keeper/rewards_supply_test.go b/x/incentive/keeper/rewards_supply_test.go deleted file mode 100644 index 46242ff3..00000000 --- a/x/incentive/keeper/rewards_supply_test.go +++ /dev/null @@ -1,1030 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - proposaltypes "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/committee" - committeekeeper "github.com/0glabs/0g-chain/x/committee/keeper" - committeetypes "github.com/0glabs/0g-chain/x/committee/types" - "github.com/0glabs/0g-chain/x/hard" - hardkeeper "github.com/0glabs/0g-chain/x/hard/keeper" - "github.com/0glabs/0g-chain/x/incentive/keeper" - "github.com/0glabs/0g-chain/x/incentive/testutil" - "github.com/0glabs/0g-chain/x/incentive/types" - kavadisttypes "github.com/0glabs/0g-chain/x/kavadist/types" -) - -type SupplyIntegrationTests struct { - testutil.IntegrationTester - - genesisTime time.Time - addrs []sdk.AccAddress -} - -func TestSupplyIntegration(t *testing.T) { - suite.Run(t, new(SupplyIntegrationTests)) -} - -// SetupTest is run automatically before each suite test -func (suite *SupplyIntegrationTests) SetupTest() { - _, suite.addrs = app.GeneratePrivKeyAddressPairs(5) - - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *SupplyIntegrationTests) TestSingleUserAccumulatesRewardsAfterSyncing() { - userA := suite.addrs[0] - - authBulder := app.NewAuthBankGenesisBuilder(). - WithSimpleModuleAccount(kavadisttypes.ModuleName, cs(c("hard", 1e18))). // Fill kavadist with enough coins to pay out any reward - WithSimpleAccount(userA, cs(c("bnb", 1e12))) // give the user some coins - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithMultipliers(types.MultipliersPerDenoms{{ - Denom: "hard", - Multipliers: types.Multipliers{types.NewMultiplier("large", 12, d("1.0"))}, // keep payout at 1.0 to make maths easier - }}). - WithSimpleSupplyRewardPeriod("bnb", cs(c("hard", 1e6))) // only borrow rewards - - suite.SetApp() - - suite.WithGenesisTime(suite.genesisTime) - suite.StartChain( - NewPricefeedGenStateMultiFromTime(suite.App.AppCodec(), suite.genesisTime), - NewHardGenStateMulti(suite.genesisTime).BuildMarshalled(suite.App.AppCodec()), - authBulder.BuildMarshalled(suite.App.AppCodec()), - incentBuilder.BuildMarshalled(suite.App.AppCodec()), - ) - - // Create a deposit - suite.NoError(suite.DeliverHardMsgDeposit(userA, cs(c("bnb", 1e11)))) - // Also create a borrow so interest accumulates on the deposit - suite.NoError(suite.DeliverHardMsgBorrow(userA, cs(c("bnb", 1e10)))) - - // Let time pass to accumulate interest on the deposit - // Use one long block instead of many to reduce any rounding errors, and speed up tests. - suite.NextBlockAfter(1e6 * time.Second) // about 12 days - - // User withdraw and redeposits just to sync their deposit. - suite.NoError(suite.DeliverHardMsgWithdraw(userA, cs(c("bnb", 1)))) - suite.NoError(suite.DeliverHardMsgDeposit(userA, cs(c("bnb", 1)))) - - // Accumulate more rewards. - // The user still has the same percentage of all deposits (100%) so their rewards should be the same as in the previous block. - suite.NextBlockAfter(1e6 * time.Second) // about 12 days - - msg := types.NewMsgClaimHardReward( - userA.String(), - types.Selections{ - types.NewSelection("hard", "large"), - }) - - // User claims all their rewards - suite.Require().NoError(suite.DeliverIncentiveMsg(&msg)) - - // The users has always had 100% of deposits, so they should receive all rewards for the previous two blocks. - // Total rewards for each block is block duration * rewards per second - accuracy := 1e-10 // using a very high accuracy to flag future small calculation changes - suite.BalanceInEpsilon(userA, cs(c("bnb", 1e12-1e11+1e10), c("hard", 2*1e6*1e6)), accuracy) -} - -// Test suite used for all keeper tests -type SupplyRewardsTestSuite struct { - suite.Suite - - keeper keeper.Keeper - hardKeeper hardkeeper.Keeper - committeeKeeper committeekeeper.Keeper - - app app.TestApp - ctx sdk.Context - - genesisTime time.Time - addrs []sdk.AccAddress -} - -// SetupTest is run automatically before each suite test -func (suite *SupplyRewardsTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - _, suite.addrs = app.GeneratePrivKeyAddressPairs(5) - - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *SupplyRewardsTestSuite) SetupApp() { - suite.app = app.NewTestApp() - - suite.keeper = suite.app.GetIncentiveKeeper() - suite.hardKeeper = suite.app.GetHardKeeper() - suite.committeeKeeper = suite.app.GetCommitteeKeeper() - - suite.ctx = suite.app.NewContext(true, tmproto.Header{Height: 1, Time: suite.genesisTime}) -} - -func (suite *SupplyRewardsTestSuite) SetupWithGenState(authBuilder *app.AuthBankGenesisBuilder, incentBuilder testutil.IncentiveGenesisBuilder, hardBuilder testutil.HardGenesisBuilder) { - suite.SetupApp() - - suite.app.InitializeFromGenesisStatesWithTime( - suite.genesisTime, - authBuilder.BuildMarshalled(suite.app.AppCodec()), - NewPricefeedGenStateMultiFromTime(suite.app.AppCodec(), suite.genesisTime), - hardBuilder.BuildMarshalled(suite.app.AppCodec()), - NewCommitteeGenesisState(suite.app.AppCodec(), 1, suite.addrs[:2]...), - incentBuilder.BuildMarshalled(suite.app.AppCodec()), - ) -} - -func (suite *SupplyRewardsTestSuite) TestAccumulateHardSupplyRewards() { - type args struct { - deposit sdk.Coin - rewardsPerSecond sdk.Coins - timeElapsed int - expectedRewardIndexes types.RewardIndexes - } - type test struct { - name string - args args - } - testCases := []test{ - { - "single reward denom: 7 seconds", - args{ - deposit: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 7, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.000000856478000000"))}, - }, - }, - { - "single reward denom: 1 day", - args{ - deposit: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 86400, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.010571385600000000"))}, - }, - }, - { - "single reward denom: 0 seconds", - args{ - deposit: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354)), - timeElapsed: 0, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.0"))}, - }, - }, - { - "multiple reward denoms: 7 seconds", - args{ - deposit: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - timeElapsed: 7, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.000000856478000000")), - types.NewRewardIndex("ukava", d("0.000000856478000000")), - }, - }, - }, - { - "multiple reward denoms: 1 day", - args{ - deposit: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - timeElapsed: 86400, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.010571385600000000")), - types.NewRewardIndex("ukava", d("0.010571385600000000")), - }, - }, - }, - { - "multiple reward denoms: 0 seconds", - args{ - deposit: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - timeElapsed: 0, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - types.NewRewardIndex("ukava", d("0.0")), - }, - }, - }, - { - "multiple reward denoms with different rewards per second: 1 day", - args{ - deposit: c("bnb", 1000000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 555555)), - timeElapsed: 86400, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.010571385600000000")), - types.NewRewardIndex("ukava", d("0.047999952000000000")), - }, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder().WithSimpleAccount( - userAddr, - cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15)), - ) - // suite.SetupWithGenState(authBuilder) - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime) - if tc.args.rewardsPerSecond != nil { - incentBuilder = incentBuilder.WithSimpleSupplyRewardPeriod(tc.args.deposit.Denom, tc.args.rewardsPerSecond) - } - - suite.SetupWithGenState(authBuilder, incentBuilder, NewHardGenStateMulti(suite.genesisTime)) - - // User deposits to increase total supplied amount - err := suite.hardKeeper.Deposit(suite.ctx, userAddr, sdk.NewCoins(tc.args.deposit)) - suite.Require().NoError(err) - - // Set up chain context at future time - runAtTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed)) - runCtx := suite.ctx.WithBlockTime(runAtTime) - - // Run Hard begin blocker in order to update the denom's index factor - hard.BeginBlocker(runCtx, suite.hardKeeper) - - // Accumulate hard supply rewards for the deposit denom - multiRewardPeriod, found := suite.keeper.GetHardSupplyRewardPeriods(runCtx, tc.args.deposit.Denom) - suite.Require().True(found) - suite.keeper.AccumulateHardSupplyRewards(runCtx, multiRewardPeriod) - - // Check that each expected reward index matches the current stored reward index for the denom - globalRewardIndexes, found := suite.keeper.GetHardSupplyRewardIndexes(runCtx, tc.args.deposit.Denom) - if len(tc.args.rewardsPerSecond) > 0 { - suite.Require().True(found) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - globalRewardIndex, found := globalRewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, globalRewardIndex) - } - } else { - suite.Require().False(found) - } - }) - } -} - -func (suite *SupplyRewardsTestSuite) TestInitializeHardSupplyRewards() { - type args struct { - moneyMarketRewardDenoms map[string]sdk.Coins - deposit sdk.Coins - expectedClaimSupplyRewardIndexes types.MultiRewardIndexes - } - type test struct { - name string - args args - } - - standardMoneyMarketRewardDenoms := map[string]sdk.Coins{ - "bnb": cs(c("hard", 1)), - "btcb": cs(c("hard", 1), c("ukava", 1)), - } - - testCases := []test{ - { - "single deposit denom, single reward denom", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("bnb", 1000000000000)), - expectedClaimSupplyRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "bnb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - }, - ), - }, - }, - }, - { - "single deposit denom, multiple reward denoms", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("btcb", 1000000000000)), - expectedClaimSupplyRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "btcb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - types.NewRewardIndex("ukava", d("0.0")), - }, - ), - }, - }, - }, - { - "single deposit denom, no reward denoms", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("xrp", 1000000000000)), - expectedClaimSupplyRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "xrp", - nil, - ), - }, - }, - }, - { - "multiple deposit denoms, multiple overlapping reward denoms", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("bnb", 1000000000000), c("btcb", 1000000000000)), - expectedClaimSupplyRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "bnb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - }, - ), - types.NewMultiRewardIndex( - "btcb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - types.NewRewardIndex("ukava", d("0.0")), - }, - ), - }, - }, - }, - { - "multiple deposit denoms, correct discrete reward denoms", - args{ - moneyMarketRewardDenoms: standardMoneyMarketRewardDenoms, - deposit: cs(c("bnb", 1000000000000), c("xrp", 1000000000000)), - expectedClaimSupplyRewardIndexes: types.MultiRewardIndexes{ - types.NewMultiRewardIndex( - "bnb", - types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.0")), - }, - ), - types.NewMultiRewardIndex( - "xrp", - nil, - ), - }, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder().WithSimpleAccount( - userAddr, - cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15)), - ) - - incentBuilder := testutil.NewIncentiveGenesisBuilder().WithGenesisTime(suite.genesisTime) - for moneyMarketDenom, rewardsPerSecond := range tc.args.moneyMarketRewardDenoms { - incentBuilder = incentBuilder.WithSimpleSupplyRewardPeriod(moneyMarketDenom, rewardsPerSecond) - } - suite.SetupWithGenState(authBuilder, incentBuilder, NewHardGenStateMulti(suite.genesisTime)) - - // User deposits - err := suite.hardKeeper.Deposit(suite.ctx, userAddr, tc.args.deposit) - suite.Require().NoError(err) - - claim, foundClaim := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(foundClaim) - suite.Require().Equal(tc.args.expectedClaimSupplyRewardIndexes, claim.SupplyRewardIndexes) - }) - } -} - -func (suite *SupplyRewardsTestSuite) TestSynchronizeHardSupplyReward() { - type args struct { - incentiveSupplyRewardDenom string - deposit sdk.Coin - rewardsPerSecond sdk.Coins - blockTimes []int - expectedRewardIndexes types.RewardIndexes - expectedRewards sdk.Coins - updateRewardsViaCommmittee bool - updatedBaseDenom string - updatedRewardsPerSecond sdk.Coins - updatedExpectedRewardIndexes types.RewardIndexes - updatedExpectedRewards sdk.Coins - updatedTimeDuration int - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "single reward denom: 10 blocks", - args{ - incentiveSupplyRewardDenom: "bnb", - deposit: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.001223540000000000"))}, - expectedRewards: cs(c("hard", 12235400)), - updateRewardsViaCommmittee: false, - }, - }, - { - "single reward denom: 10 blocks - long block time", - args{ - incentiveSupplyRewardDenom: "bnb", - deposit: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("10.571385600000000000"))}, - expectedRewards: cs(c("hard", 105713856000)), - updateRewardsViaCommmittee: false, - }, - }, - { - "single reward denom: user reward index updated when reward is zero", - args{ - incentiveSupplyRewardDenom: "ukava", - deposit: c("ukava", 1), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.122353998776460010"))}, - expectedRewards: cs(), - updateRewardsViaCommmittee: false, - }, - }, - { - "multiple reward denoms: 10 blocks", - args{ - incentiveSupplyRewardDenom: "bnb", - deposit: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.001223540000000000")), - types.NewRewardIndex("ukava", d("0.001223540000000000")), - }, - expectedRewards: cs(c("hard", 12235400), c("ukava", 12235400)), - updateRewardsViaCommmittee: false, - }, - }, - { - "multiple reward denoms: 10 blocks - long block time", - args{ - incentiveSupplyRewardDenom: "bnb", - deposit: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("10.571385600000000000")), - types.NewRewardIndex("ukava", d("10.571385600000000000")), - }, - expectedRewards: cs(c("hard", 105713856000), c("ukava", 105713856000)), - updateRewardsViaCommmittee: false, - }, - }, - { - "multiple reward denoms with different rewards per second: 10 blocks", - args{ - incentiveSupplyRewardDenom: "bnb", - deposit: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 555555)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.001223540000000000")), - types.NewRewardIndex("ukava", d("0.005555550000000000")), - }, - expectedRewards: cs(c("hard", 12235400), c("ukava", 55555500)), - updateRewardsViaCommmittee: false, - }, - }, - { - "denom is in incentive's hard supply reward params and has rewards; add new reward type", - args{ - incentiveSupplyRewardDenom: "bnb", - deposit: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{86400}, - expectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("1.057138560000000000")), - }, - expectedRewards: cs(c("hard", 10571385600)), - updateRewardsViaCommmittee: true, - updatedBaseDenom: "bnb", - updatedRewardsPerSecond: cs(c("hard", 122354), c("ukava", 100000)), - updatedExpectedRewards: cs(c("hard", 21142771200), c("ukava", 8640000000)), - updatedExpectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("2.114277120000000000")), - types.NewRewardIndex("ukava", d("0.864000000000000000")), - }, - updatedTimeDuration: 86400, - }, - }, - { - "denom is in hard's money market params but not in incentive's hard supply reward params; add reward", - args{ - incentiveSupplyRewardDenom: "bnb", - deposit: c("zzz", 10000000000), - rewardsPerSecond: nil, - blockTimes: []int{100}, - expectedRewardIndexes: types.RewardIndexes{}, - expectedRewards: sdk.Coins{}, - updateRewardsViaCommmittee: true, - updatedBaseDenom: "zzz", - updatedRewardsPerSecond: cs(c("hard", 100000)), - updatedExpectedRewards: cs(c("hard", 8640000000)), - updatedExpectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.864")), - }, - updatedTimeDuration: 86400, - }, - }, - { - "denom is in hard's money market params but not in incentive's hard supply reward params; add multiple reward types", - args{ - incentiveSupplyRewardDenom: "bnb", - deposit: c("zzz", 10000000000), - rewardsPerSecond: nil, - blockTimes: []int{100}, - expectedRewardIndexes: types.RewardIndexes{}, - expectedRewards: sdk.Coins{}, - updateRewardsViaCommmittee: true, - updatedBaseDenom: "zzz", - updatedRewardsPerSecond: cs(c("hard", 100000), c("ukava", 100500), c("swap", 500)), - updatedExpectedRewards: cs(c("hard", 8640000000), c("ukava", 8683200000), c("swap", 43200000)), - updatedExpectedRewardIndexes: types.RewardIndexes{ - types.NewRewardIndex("hard", d("0.864")), - types.NewRewardIndex("ukava", d("0.86832")), - types.NewRewardIndex("swap", d("0.00432")), - }, - updatedTimeDuration: 86400, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleAccount(suite.addrs[2], cs(c("ukava", 1e9))). - WithSimpleAccount(userAddr, cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15))) - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime) - if tc.args.rewardsPerSecond != nil { - incentBuilder = incentBuilder.WithSimpleSupplyRewardPeriod(tc.args.incentiveSupplyRewardDenom, tc.args.rewardsPerSecond) - } - suite.SetupWithGenState(authBuilder, incentBuilder, NewHardGenStateMulti(suite.genesisTime)) - - // Deposit a fixed amount from another user to dilute primary user's rewards per second. - suite.Require().NoError( - suite.hardKeeper.Deposit(suite.ctx, suite.addrs[2], cs(c("ukava", 100_000_000))), - ) - - // User deposits and borrows to increase total borrowed amount - err := suite.hardKeeper.Deposit(suite.ctx, userAddr, sdk.NewCoins(tc.args.deposit)) - suite.Require().NoError(err) - - // Check that Hard hooks initialized a HardLiquidityProviderClaim with 0 reward indexes - claim, found := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - multiRewardIndex, _ := claim.SupplyRewardIndexes.GetRewardIndex(tc.args.deposit.Denom) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - currRewardIndex, found := multiRewardIndex.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(sdk.ZeroDec(), currRewardIndex.RewardFactor) - } - - // Run accumulator at several intervals - var timeElapsed int - previousBlockTime := suite.ctx.BlockTime() - for _, t := range tc.args.blockTimes { - timeElapsed += t - updatedBlockTime := previousBlockTime.Add(time.Duration(int(time.Second) * t)) - previousBlockTime = updatedBlockTime - blockCtx := suite.ctx.WithBlockTime(updatedBlockTime) - - // Run Hard begin blocker for each block ctx to update denom's interest factor - hard.BeginBlocker(blockCtx, suite.hardKeeper) - - // Accumulate hard supply-side rewards - multiRewardPeriod, found := suite.keeper.GetHardSupplyRewardPeriods(blockCtx, tc.args.deposit.Denom) - if found { - suite.keeper.AccumulateHardSupplyRewards(blockCtx, multiRewardPeriod) - } - } - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - - // After we've accumulated, run synchronize - deposit, found := suite.hardKeeper.GetDeposit(suite.ctx, userAddr) - suite.Require().True(found) - suite.Require().NotPanics(func() { - suite.keeper.SynchronizeHardSupplyReward(suite.ctx, deposit) - }) - - // Check that the global reward index's reward factor and user's claim have been updated as expected - claim, found = suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - globalRewardIndexes, foundGlobalRewardIndexes := suite.keeper.GetHardSupplyRewardIndexes(suite.ctx, tc.args.deposit.Denom) - if len(tc.args.rewardsPerSecond) > 0 { - suite.Require().True(foundGlobalRewardIndexes) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - // Check that global reward index has been updated as expected - globalRewardIndex, found := globalRewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, globalRewardIndex) - - // Check that the user's claim's reward index matches the corresponding global reward index - multiRewardIndex, found := claim.SupplyRewardIndexes.GetRewardIndex(tc.args.deposit.Denom) - suite.Require().True(found) - rewardIndex, found := multiRewardIndex.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, rewardIndex) - - // Check that the user's claim holds the expected amount of reward coins - suite.Require().Equal( - tc.args.expectedRewards.AmountOf(expectedRewardIndex.CollateralType), - claim.Reward.AmountOf(expectedRewardIndex.CollateralType), - ) - } - } - - // Only test cases with reward param updates continue past this point - if !tc.args.updateRewardsViaCommmittee { - return - } - - // If are no initial rewards per second, add new rewards through a committee param change - // 1. Construct incentive's new HardSupplyRewardPeriods param - currIncentiveHardSupplyRewardPeriods := suite.keeper.GetParams(suite.ctx).HardSupplyRewardPeriods - multiRewardPeriod, found := currIncentiveHardSupplyRewardPeriods.GetMultiRewardPeriod(tc.args.deposit.Denom) - if found { - // Deposit denom's reward period exists, but it doesn't have any rewards per second - index, found := currIncentiveHardSupplyRewardPeriods.GetMultiRewardPeriodIndex(tc.args.deposit.Denom) - suite.Require().True(found) - multiRewardPeriod.RewardsPerSecond = tc.args.updatedRewardsPerSecond - currIncentiveHardSupplyRewardPeriods[index] = multiRewardPeriod - } else { - // Deposit denom's reward period does not exist - _, found := currIncentiveHardSupplyRewardPeriods.GetMultiRewardPeriodIndex(tc.args.deposit.Denom) - suite.Require().False(found) - newMultiRewardPeriod := types.NewMultiRewardPeriod(true, tc.args.deposit.Denom, suite.genesisTime, suite.genesisTime.Add(time.Hour*24*365*4), tc.args.updatedRewardsPerSecond) - currIncentiveHardSupplyRewardPeriods = append(currIncentiveHardSupplyRewardPeriods, newMultiRewardPeriod) - } - - // 2. Construct the parameter change proposal to update HardSupplyRewardPeriods param - pubProposal := proposaltypes.NewParameterChangeProposal( - "Update hard supply rewards", "Adds a new reward coin to the incentive module's hard supply rewards.", - []proposaltypes.ParamChange{ - { - Subspace: types.ModuleName, // target incentive module - Key: string(types.KeyHardSupplyRewardPeriods), // target hard supply rewards key - Value: string(suite.app.LegacyAmino().MustMarshalJSON(&currIncentiveHardSupplyRewardPeriods)), - }, - }, - ) - - // 3. Ensure proposal is properly formed - err = suite.committeeKeeper.ValidatePubProposal(suite.ctx, pubProposal) - suite.Require().NoError(err) - - // 4. Committee creates proposal - committeeMemberOne := suite.addrs[0] - committeeMemberTwo := suite.addrs[1] - proposalID, err := suite.committeeKeeper.SubmitProposal(suite.ctx, committeeMemberOne, 1, pubProposal) - suite.Require().NoError(err) - - // 5. Committee votes and passes proposal - err = suite.committeeKeeper.AddVote(suite.ctx, proposalID, committeeMemberOne, committeetypes.VOTE_TYPE_YES) - suite.Require().NoError(err) - err = suite.committeeKeeper.AddVote(suite.ctx, proposalID, committeeMemberTwo, committeetypes.VOTE_TYPE_YES) - suite.Require().NoError(err) - - // 6. Check proposal passed - com, found := suite.committeeKeeper.GetCommittee(suite.ctx, 1) - suite.Require().True(found) - proposalPasses := suite.committeeKeeper.GetProposalResult(suite.ctx, proposalID, com) - suite.Require().True(proposalPasses) - - // 7. Run committee module's begin blocker to enact proposal - suite.NotPanics(func() { - committee.BeginBlocker(suite.ctx, abci.RequestBeginBlock{}, suite.committeeKeeper) - }) - - // We need to accumulate hard supply-side rewards again - multiRewardPeriod, found = suite.keeper.GetHardSupplyRewardPeriods(suite.ctx, tc.args.deposit.Denom) - suite.Require().True(found) - - // But new deposit denoms don't have their PreviousHardSupplyRewardAccrualTime set yet, - // so we need to call the accumulation method once to set the initial reward accrual time - if tc.args.deposit.Denom != tc.args.incentiveSupplyRewardDenom { - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, multiRewardPeriod) - } - - // Now we can jump forward in time and accumulate rewards - updatedBlockTime = previousBlockTime.Add(time.Duration(int(time.Second) * tc.args.updatedTimeDuration)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - suite.keeper.AccumulateHardSupplyRewards(suite.ctx, multiRewardPeriod) - - // After we've accumulated, run synchronize - deposit, found = suite.hardKeeper.GetDeposit(suite.ctx, userAddr) - suite.Require().True(found) - suite.Require().NotPanics(func() { - suite.keeper.SynchronizeHardSupplyReward(suite.ctx, deposit) - }) - - // Check that the global reward index's reward factor and user's claim have been updated as expected - globalRewardIndexes, found = suite.keeper.GetHardSupplyRewardIndexes(suite.ctx, tc.args.deposit.Denom) - suite.Require().True(found) - claim, found = suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - for _, expectedRewardIndex := range tc.args.updatedExpectedRewardIndexes { - // Check that global reward index has been updated as expected - globalRewardIndex, found := globalRewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, globalRewardIndex) - - // Check that the user's claim's reward index matches the corresponding global reward index - multiRewardIndex, found := claim.SupplyRewardIndexes.GetRewardIndex(tc.args.deposit.Denom) - suite.Require().True(found) - rewardIndex, found := multiRewardIndex.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, rewardIndex) - - // Check that the user's claim holds the expected amount of reward coins - suite.Require().Equal( - tc.args.updatedExpectedRewards.AmountOf(expectedRewardIndex.CollateralType), - claim.Reward.AmountOf(expectedRewardIndex.CollateralType), - ) - } - }) - } -} - -func (suite *SupplyRewardsTestSuite) TestUpdateHardSupplyIndexDenoms() { - type depositModification struct { - coins sdk.Coins - withdraw bool - } - - type args struct { - firstDeposit sdk.Coins - modification depositModification - rewardsPerSecond sdk.Coins - expectedSupplyIndexDenoms []string - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "single reward denom: update adds one supply reward index", - args{ - firstDeposit: cs(c("bnb", 10000000000)), - modification: depositModification{coins: cs(c("ukava", 10000000000))}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedSupplyIndexDenoms: []string{"bnb", "ukava"}, - }, - }, - { - "single reward denom: update adds multiple supply reward indexes", - args{ - firstDeposit: cs(c("bnb", 10000000000)), - modification: depositModification{coins: cs(c("ukava", 10000000000), c("btcb", 10000000000), c("xrp", 10000000000))}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedSupplyIndexDenoms: []string{"bnb", "ukava", "btcb", "xrp"}, - }, - }, - { - "single reward denom: update doesn't add duplicate supply reward index for same denom", - args{ - firstDeposit: cs(c("bnb", 10000000000)), - modification: depositModification{coins: cs(c("bnb", 5000000000))}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedSupplyIndexDenoms: []string{"bnb"}, - }, - }, - { - "multiple reward denoms: update adds one supply reward index", - args{ - firstDeposit: cs(c("bnb", 10000000000)), - modification: depositModification{coins: cs(c("ukava", 10000000000))}, - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - expectedSupplyIndexDenoms: []string{"bnb", "ukava"}, - }, - }, - { - "multiple reward denoms: update adds multiple supply reward indexes", - args{ - firstDeposit: cs(c("bnb", 10000000000)), - modification: depositModification{coins: cs(c("ukava", 10000000000), c("btcb", 10000000000), c("xrp", 10000000000))}, - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - expectedSupplyIndexDenoms: []string{"bnb", "ukava", "btcb", "xrp"}, - }, - }, - { - "multiple reward denoms: update doesn't add duplicate supply reward index for same denom", - args{ - firstDeposit: cs(c("bnb", 10000000000)), - modification: depositModification{coins: cs(c("bnb", 5000000000))}, - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - expectedSupplyIndexDenoms: []string{"bnb"}, - }, - }, - { - "single reward denom: fully withdrawing a denom deletes the denom's supply reward index", - args{ - firstDeposit: cs(c("bnb", 1000000000)), - modification: depositModification{coins: cs(c("bnb", 1100000000)), withdraw: true}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedSupplyIndexDenoms: []string{}, - }, - }, - { - "single reward denom: fully withdrawing a denom deletes only the denom's supply reward index", - args{ - firstDeposit: cs(c("bnb", 1000000000), c("ukava", 100000000)), - modification: depositModification{coins: cs(c("bnb", 1100000000)), withdraw: true}, - rewardsPerSecond: cs(c("hard", 122354)), - expectedSupplyIndexDenoms: []string{"ukava"}, - }, - }, - { - "multiple reward denoms: fully repaying a denom deletes the denom's supply reward index", - args{ - firstDeposit: cs(c("bnb", 1000000000)), - modification: depositModification{coins: cs(c("bnb", 1100000000)), withdraw: true}, - rewardsPerSecond: cs(c("hard", 122354), c("ukava", 122354)), - expectedSupplyIndexDenoms: []string{}, - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder().WithSimpleAccount( - userAddr, - cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15)), - ) - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleSupplyRewardPeriod("bnb", tc.args.rewardsPerSecond). - WithSimpleSupplyRewardPeriod("ukava", tc.args.rewardsPerSecond). - WithSimpleSupplyRewardPeriod("btcb", tc.args.rewardsPerSecond). - WithSimpleSupplyRewardPeriod("xrp", tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder, NewHardGenStateMulti(suite.genesisTime)) - - // User deposits (first time) - err := suite.hardKeeper.Deposit(suite.ctx, userAddr, tc.args.firstDeposit) - suite.Require().NoError(err) - - // Confirm that a claim was created and populated with the correct supply indexes - claimAfterFirstDeposit, found := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - for _, coin := range tc.args.firstDeposit { - _, hasIndex := claimAfterFirstDeposit.HasSupplyRewardIndex(coin.Denom) - suite.Require().True(hasIndex) - } - suite.Require().True(len(claimAfterFirstDeposit.SupplyRewardIndexes) == len(tc.args.firstDeposit)) - - // User modifies their Deposit by withdrawing or depositing more - if tc.args.modification.withdraw { - err = suite.hardKeeper.Withdraw(suite.ctx, userAddr, tc.args.modification.coins) - } else { - err = suite.hardKeeper.Deposit(suite.ctx, userAddr, tc.args.modification.coins) - } - suite.Require().NoError(err) - - // Confirm that the claim contains all expected supply indexes - claimAfterModification, found := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(found) - for _, denom := range tc.args.expectedSupplyIndexDenoms { - _, hasIndex := claimAfterModification.HasSupplyRewardIndex(denom) - suite.Require().True(hasIndex) - } - suite.Require().True(len(claimAfterModification.SupplyRewardIndexes) == len(tc.args.expectedSupplyIndexDenoms)) - }) - } -} - -func (suite *SupplyRewardsTestSuite) TestSimulateHardSupplyRewardSynchronization() { - type args struct { - deposit sdk.Coin - rewardsPerSecond sdk.Coins - blockTimes []int - expectedRewardIndexes types.RewardIndexes - expectedRewards sdk.Coins - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "10 blocks", - args{ - deposit: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("0.001223540000000000"))}, - expectedRewards: cs(c("hard", 12235400)), - }, - }, - { - "10 blocks - long block time", - args{ - deposit: c("bnb", 10000000000), - rewardsPerSecond: cs(c("hard", 122354)), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardIndexes: types.RewardIndexes{types.NewRewardIndex("hard", d("10.571385600000000000"))}, - expectedRewards: cs(c("hard", 105713856000)), - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - userAddr := suite.addrs[3] - authBuilder := app.NewAuthBankGenesisBuilder().WithSimpleAccount( - userAddr, - cs(c("bnb", 1e15), c("ukava", 1e15), c("btcb", 1e15), c("xrp", 1e15), c("zzz", 1e15)), - ) - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithSimpleSupplyRewardPeriod(tc.args.deposit.Denom, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder, NewHardGenStateMulti(suite.genesisTime)) - - // User deposits and borrows to increase total borrowed amount - err := suite.hardKeeper.Deposit(suite.ctx, userAddr, sdk.NewCoins(tc.args.deposit)) - suite.Require().NoError(err) - - // Run accumulator at several intervals - var timeElapsed int - previousBlockTime := suite.ctx.BlockTime() - for _, t := range tc.args.blockTimes { - timeElapsed += t - updatedBlockTime := previousBlockTime.Add(time.Duration(int(time.Second) * t)) - previousBlockTime = updatedBlockTime - blockCtx := suite.ctx.WithBlockTime(updatedBlockTime) - - // Run Hard begin blocker for each block ctx to update denom's interest factor - hard.BeginBlocker(blockCtx, suite.hardKeeper) - - // Accumulate hard supply-side rewards - multiRewardPeriod, found := suite.keeper.GetHardSupplyRewardPeriods(blockCtx, tc.args.deposit.Denom) - suite.Require().True(found) - suite.keeper.AccumulateHardSupplyRewards(blockCtx, multiRewardPeriod) - } - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - - // Confirm that the user's claim hasn't been synced - claimPre, foundPre := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, userAddr) - suite.Require().True(foundPre) - multiRewardIndexPre, _ := claimPre.SupplyRewardIndexes.GetRewardIndex(tc.args.deposit.Denom) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - currRewardIndex, found := multiRewardIndexPre.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(sdk.ZeroDec(), currRewardIndex.RewardFactor) - } - - // Check that the synced claim held in memory has properly simulated syncing - syncedClaim := suite.keeper.SimulateHardSynchronization(suite.ctx, claimPre) - for _, expectedRewardIndex := range tc.args.expectedRewardIndexes { - // Check that the user's claim's reward index matches the expected reward index - multiRewardIndex, found := syncedClaim.SupplyRewardIndexes.GetRewardIndex(tc.args.deposit.Denom) - suite.Require().True(found) - rewardIndex, found := multiRewardIndex.RewardIndexes.GetRewardIndex(expectedRewardIndex.CollateralType) - suite.Require().True(found) - suite.Require().Equal(expectedRewardIndex, rewardIndex) - - // Check that the user's claim holds the expected amount of reward coins - suite.Require().Equal( - tc.args.expectedRewards.AmountOf(expectedRewardIndex.CollateralType), - syncedClaim.Reward.AmountOf(expectedRewardIndex.CollateralType), - ) - } - }) - } -} - -func TestSupplyRewardsTestSuite(t *testing.T) { - suite.Run(t, new(SupplyRewardsTestSuite)) -} diff --git a/x/incentive/keeper/rewards_supply_update_test.go b/x/incentive/keeper/rewards_supply_update_test.go deleted file mode 100644 index ee9f645c..00000000 --- a/x/incentive/keeper/rewards_supply_update_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// UpdateHardSupplyIndexDenomsTests runs unit tests for the keeper.UpdateHardSupplyIndexDenoms method -type UpdateHardSupplyIndexDenomsTests struct { - unitTester -} - -func TestUpdateHardSupplyIndexDenoms(t *testing.T) { - suite.Run(t, new(UpdateHardSupplyIndexDenomsTests)) -} - -func (suite *UpdateHardSupplyIndexDenomsTests) TestClaimIndexesAreRemovedForDenomsNoLongerSupplied() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - SupplyRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - suite.storeGlobalSupplyIndexes(claim.SupplyRewardIndexes) - - // remove one denom from the indexes already in the deposit - expectedIndexes := claim.SupplyRewardIndexes[1:] - deposit := NewHardDepositBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(expectedIndexes)...). - Build() - - suite.keeper.UpdateHardSupplyIndexDenoms(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(expectedIndexes, syncedClaim.SupplyRewardIndexes) -} - -func (suite *UpdateHardSupplyIndexDenomsTests) TestClaimIndexesAreAddedForNewlySuppliedDenoms() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - SupplyRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - globalIndexes := appendUniqueMultiRewardIndex(claim.SupplyRewardIndexes) - suite.storeGlobalSupplyIndexes(globalIndexes) - - deposit := NewHardDepositBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(globalIndexes)...). - Build() - - suite.keeper.UpdateHardSupplyIndexDenoms(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(globalIndexes, syncedClaim.SupplyRewardIndexes) -} - -func (suite *UpdateHardSupplyIndexDenomsTests) TestClaimIndexesAreUnchangedWhenSuppliedDenomsUnchanged() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - SupplyRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - // Set global indexes with same denoms but different values. - // UpdateHardSupplyIndexDenoms should ignore the new values. - suite.storeGlobalSupplyIndexes(increaseAllRewardFactors(claim.SupplyRewardIndexes)) - - deposit := NewHardDepositBuilder(claim.Owner). - WithArbitrarySourceShares(extractCollateralTypes(claim.SupplyRewardIndexes)...). - Build() - - suite.keeper.UpdateHardSupplyIndexDenoms(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(claim.SupplyRewardIndexes, syncedClaim.SupplyRewardIndexes) -} - -func (suite *UpdateHardSupplyIndexDenomsTests) TestEmptyClaimIndexesAreAddedForNewlySuppliedButNotRewardedDenoms() { - claim := types.HardLiquidityProviderClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - }, - SupplyRewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeHardClaim(claim) - suite.storeGlobalSupplyIndexes(claim.SupplyRewardIndexes) - - // add a denom to the deposited amount that is not in the global or claim's indexes - expectedIndexes := appendUniqueEmptyMultiRewardIndex(claim.SupplyRewardIndexes) - depositedDenoms := extractCollateralTypes(expectedIndexes) - deposit := NewHardDepositBuilder(claim.Owner). - WithArbitrarySourceShares(depositedDenoms...). - Build() - - suite.keeper.UpdateHardSupplyIndexDenoms(suite.ctx, deposit) - - syncedClaim, _ := suite.keeper.GetHardLiquidityProviderClaim(suite.ctx, claim.Owner) - suite.Equal(expectedIndexes, syncedClaim.SupplyRewardIndexes) -} diff --git a/x/incentive/keeper/rewards_swap.go b/x/incentive/keeper/rewards_swap.go deleted file mode 100644 index 4d26e462..00000000 --- a/x/incentive/keeper/rewards_swap.go +++ /dev/null @@ -1,130 +0,0 @@ -package keeper - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// AccumulateSwapRewards calculates new rewards to distribute this block and updates the global indexes to reflect this. -// The provided rewardPeriod must be valid to avoid panics in calculating time durations. -func (k Keeper) AccumulateSwapRewards(ctx sdk.Context, rewardPeriod types.MultiRewardPeriod) { - previousAccrualTime, found := k.GetSwapRewardAccrualTime(ctx, rewardPeriod.CollateralType) - if !found { - previousAccrualTime = ctx.BlockTime() - } - - indexes, found := k.GetSwapRewardIndexes(ctx, rewardPeriod.CollateralType) - if !found { - indexes = types.RewardIndexes{} - } - - acc := types.NewAccumulator(previousAccrualTime, indexes) - - totalSource := k.getSwapTotalSourceShares(ctx, rewardPeriod.CollateralType) - - acc.Accumulate(rewardPeriod, totalSource, ctx.BlockTime()) - - k.SetSwapRewardAccrualTime(ctx, rewardPeriod.CollateralType, acc.PreviousAccumulationTime) - if len(acc.Indexes) > 0 { - // the store panics when setting empty or nil indexes - k.SetSwapRewardIndexes(ctx, rewardPeriod.CollateralType, acc.Indexes) - } -} - -// getSwapTotalSourceShares fetches the sum of all source shares for a swap reward. -// In the case of swap, these are the total (swap module) shares in a particular pool. -func (k Keeper) getSwapTotalSourceShares(ctx sdk.Context, poolID string) sdk.Dec { - totalShares, found := k.swapKeeper.GetPoolShares(ctx, poolID) - if !found { - totalShares = sdk.ZeroInt() - } - return sdk.NewDecFromInt(totalShares) -} - -// InitializeSwapReward creates a new claim with zero rewards and indexes matching the global indexes. -// If the claim already exists it just updates the indexes. -func (k Keeper) InitializeSwapReward(ctx sdk.Context, poolID string, owner sdk.AccAddress) { - claim, found := k.GetSwapClaim(ctx, owner) - if !found { - claim = types.NewSwapClaim(owner, sdk.Coins{}, nil) - } - - globalRewardIndexes, found := k.GetSwapRewardIndexes(ctx, poolID) - if !found { - globalRewardIndexes = types.RewardIndexes{} - } - claim.RewardIndexes = claim.RewardIndexes.With(poolID, globalRewardIndexes) - - k.SetSwapClaim(ctx, claim) -} - -// SynchronizeSwapReward updates the claim object by adding any accumulated rewards -// and updating the reward index value. -func (k Keeper) SynchronizeSwapReward(ctx sdk.Context, poolID string, owner sdk.AccAddress, shares sdkmath.Int) { - claim, found := k.GetSwapClaim(ctx, owner) - if !found { - return - } - claim = k.synchronizeSwapReward(ctx, claim, poolID, owner, shares) - - k.SetSwapClaim(ctx, claim) -} - -// synchronizeSwapReward updates the reward and indexes in a swap claim for one pool. -func (k *Keeper) synchronizeSwapReward(ctx sdk.Context, claim types.SwapClaim, poolID string, owner sdk.AccAddress, shares sdkmath.Int) types.SwapClaim { - globalRewardIndexes, found := k.GetSwapRewardIndexes(ctx, poolID) - if !found { - // The global factor is only not found if - // - the pool has not started accumulating rewards yet (either there is no reward specified in params, or the reward start time hasn't been hit) - // - OR it was wrongly deleted from state (factors should never be removed while unsynced claims exist) - // If not found we could either skip this sync, or assume the global factor is zero. - // Skipping will avoid storing unnecessary factors in the claim for non rewarded pools. - // And in the event a global factor is wrongly deleted, it will avoid this function panicking when calculating rewards. - return claim - } - - userRewardIndexes, found := claim.RewardIndexes.Get(poolID) - if !found { - // Normally the reward indexes should always be found. - // But if a pool was not rewarded then becomes rewarded (ie a reward period is added to params), then the indexes will be missing from claims for that pool. - // So given the reward period was just added, assume the starting value for any global reward indexes, which is an empty slice. - userRewardIndexes = types.RewardIndexes{} - } - - newRewards, err := k.CalculateRewards(userRewardIndexes, globalRewardIndexes, sdk.NewDecFromInt(shares)) - if err != nil { - // Global reward factors should never decrease, as it would lead to a negative update to claim.Rewards. - // This panics if a global reward factor decreases or disappears between the old and new indexes. - panic(fmt.Sprintf("corrupted global reward indexes found: %v", err)) - } - - claim.Reward = claim.Reward.Add(newRewards...) - claim.RewardIndexes = claim.RewardIndexes.With(poolID, globalRewardIndexes) - - return claim -} - -// GetSynchronizedSwapClaim fetches a swap claim from the store and syncs rewards for all rewarded pools. -func (k Keeper) GetSynchronizedSwapClaim(ctx sdk.Context, owner sdk.AccAddress) (types.SwapClaim, bool) { - claim, found := k.GetSwapClaim(ctx, owner) - if !found { - return types.SwapClaim{}, false - } - - k.IterateSwapRewardIndexes(ctx, func(poolID string, _ types.RewardIndexes) bool { - shares, found := k.swapKeeper.GetDepositorSharesAmount(ctx, owner, poolID) - if !found { - shares = sdk.ZeroInt() - } - - claim = k.synchronizeSwapReward(ctx, claim, poolID, owner, shares) - - return false - }) - - return claim, true -} diff --git a/x/incentive/keeper/rewards_swap_accum_test.go b/x/incentive/keeper/rewards_swap_accum_test.go deleted file mode 100644 index aa0c688a..00000000 --- a/x/incentive/keeper/rewards_swap_accum_test.go +++ /dev/null @@ -1,320 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -type AccumulateSwapRewardsTests struct { - unitTester -} - -func (suite *AccumulateSwapRewardsTests) storedTimeEquals(poolID string, expected time.Time) { - storedTime, found := suite.keeper.GetSwapRewardAccrualTime(suite.ctx, poolID) - suite.True(found) - suite.Equal(expected, storedTime) -} - -func (suite *AccumulateSwapRewardsTests) storedIndexesEqual(poolID string, expected types.RewardIndexes) { - storedIndexes, found := suite.keeper.GetSwapRewardIndexes(suite.ctx, poolID) - suite.Equal(found, expected != nil) - if found { - suite.Equal(expected, storedIndexes) - } else { - suite.Empty(storedIndexes) - } -} - -func TestAccumulateSwapRewards(t *testing.T) { - suite.Run(t, new(AccumulateSwapRewardsTests)) -} - -func (suite *AccumulateSwapRewardsTests) TestStateUpdatedWhenBlockTimeHasIncreased() { - pool := "btc:usdx" - - swapKeeper := newFakeSwapKeeper().addPool(pool, i(1e6)) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, swapKeeper, nil, nil, nil) - - suite.storeGlobalSwapIndexes(types.MultiRewardIndexes{ - { - CollateralType: pool, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "swap", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - }) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetSwapRewardAccrualTime(suite.ctx, pool, previousAccrualTime) - - newAccrualTime := previousAccrualTime.Add(1 * time.Hour) - suite.ctx = suite.ctx.WithBlockTime(newAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - pool, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("swap", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateSwapRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(pool, newAccrualTime) - suite.storedIndexesEqual(pool, types.RewardIndexes{ - { - CollateralType: "swap", - RewardFactor: d("7.22"), - }, - { - CollateralType: "ukava", - RewardFactor: d("3.64"), - }, - }) -} - -func (suite *AccumulateSwapRewardsTests) TestStateUnchangedWhenBlockTimeHasNotIncreased() { - pool := "btc:usdx" - - swapKeeper := newFakeSwapKeeper().addPool(pool, i(1e6)) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, swapKeeper, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: pool, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "swap", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetSwapRewardAccrualTime(suite.ctx, pool, previousAccrualTime) - - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - pool, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("swap", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateSwapRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(pool, previousAccrualTime) - expected, f := previousIndexes.Get(pool) - suite.True(f) - suite.storedIndexesEqual(pool, expected) -} - -func (suite *AccumulateSwapRewardsTests) TestNoAccumulationWhenSourceSharesAreZero() { - pool := "btc:usdx" - - swapKeeper := newFakeSwapKeeper() // no pools, so no source shares - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, swapKeeper, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: pool, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "swap", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetSwapRewardAccrualTime(suite.ctx, pool, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(7 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - period := types.NewMultiRewardPeriod( - true, - pool, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("swap", 2000), c("ukava", 1000)), // same denoms as in global indexes - ) - - suite.keeper.AccumulateSwapRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(pool, firstAccrualTime) - expected, f := previousIndexes.Get(pool) - suite.True(f) - suite.storedIndexesEqual(pool, expected) -} - -func (suite *AccumulateSwapRewardsTests) TestStateAddedWhenStateDoesNotExist() { - pool := "btc:usdx" - - swapKeeper := newFakeSwapKeeper().addPool(pool, i(1e6)) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, swapKeeper, nil, nil, nil) - - period := types.NewMultiRewardPeriod( - true, - pool, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(c("swap", 2000), c("ukava", 1000)), - ) - - firstAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateSwapRewards(suite.ctx, period) - - // After the first accumulation only the current block time should be stored. - // The indexes will be empty as no time has passed since the previous block because it didn't exist. - suite.storedTimeEquals(pool, firstAccrualTime) - suite.storedIndexesEqual(pool, nil) - - secondAccrualTime := firstAccrualTime.Add(10 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(secondAccrualTime) - - suite.keeper.AccumulateSwapRewards(suite.ctx, period) - - // After the second accumulation both current block time and indexes should be stored. - suite.storedTimeEquals(pool, secondAccrualTime) - suite.storedIndexesEqual(pool, types.RewardIndexes{ - { - CollateralType: "swap", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.01"), - }, - }) -} - -func (suite *AccumulateSwapRewardsTests) TestNoPanicWhenStateDoesNotExist() { - pool := "btc:usdx" - - swapKeeper := newFakeSwapKeeper() - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, swapKeeper, nil, nil, nil) - - period := types.NewMultiRewardPeriod( - true, - pool, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - cs(), - ) - - accrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(accrualTime) - - // Accumulate with no swap shares and no rewards per second will result in no increment to the indexes. - // No increment and no previous indexes stored, results in an updated of nil. Setting this in the state panics. - // Check there is no panic. - suite.NotPanics(func() { - suite.keeper.AccumulateSwapRewards(suite.ctx, period) - }) - - suite.storedTimeEquals(pool, accrualTime) - suite.storedIndexesEqual(pool, nil) -} - -func (suite *AccumulateSwapRewardsTests) TestNoAccumulationWhenBeforeStartTime() { - pool := "btc:usdx" - - swapKeeper := newFakeSwapKeeper().addPool(pool, i(1e6)) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, swapKeeper, nil, nil, nil) - - previousIndexes := types.MultiRewardIndexes{ - { - CollateralType: pool, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "swap", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetSwapRewardAccrualTime(suite.ctx, pool, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(10 * time.Second) - - period := types.NewMultiRewardPeriod( - true, - pool, - firstAccrualTime.Add(time.Nanosecond), // start time after accrual time - distantFuture, - cs(c("swap", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateSwapRewards(suite.ctx, period) - - // The accrual time should be updated, but the indexes unchanged - suite.storedTimeEquals(pool, firstAccrualTime) - expectedIndexes, f := previousIndexes.Get(pool) - suite.True(f) - suite.storedIndexesEqual(pool, expectedIndexes) -} - -func (suite *AccumulateSwapRewardsTests) TestPanicWhenCurrentTimeLessThanPrevious() { - pool := "btc:usdx" - - swapKeeper := newFakeSwapKeeper().addPool(pool, i(1e6)) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, swapKeeper, nil, nil, nil) - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetSwapRewardAccrualTime(suite.ctx, pool, previousAccrualTime) - - firstAccrualTime := time.Time{} - - period := types.NewMultiRewardPeriod( - true, - pool, - time.Time{}, // start time after accrual time - distantFuture, - cs(c("swap", 2000), c("ukava", 1000)), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.Panics(func() { - suite.keeper.AccumulateSwapRewards(suite.ctx, period) - }) -} diff --git a/x/incentive/keeper/rewards_swap_init_test.go b/x/incentive/keeper/rewards_swap_init_test.go deleted file mode 100644 index 8fd9fb51..00000000 --- a/x/incentive/keeper/rewards_swap_init_test.go +++ /dev/null @@ -1,195 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// InitializeSwapRewardTests runs unit tests for the keeper.InitializeSwapReward method -// -// inputs -// - claim in store if it exists -// - global indexes in store -// -// outputs -// - sets or creates a claim -type InitializeSwapRewardTests struct { - unitTester -} - -func TestInitializeSwapReward(t *testing.T) { - suite.Run(t, new(InitializeSwapRewardTests)) -} - -func (suite *InitializeSwapRewardTests) TestClaimAddedWhenClaimDoesNotExistAndNoRewards() { - // When a claim doesn't exist, and a user deposits to a non-rewarded pool; - // then a claim is added with no rewards and no indexes - - poolID := "base:quote" - - // no global indexes stored as this pool is not rewarded - - owner := arbitraryAddress() - - suite.keeper.InitializeSwapReward(suite.ctx, poolID, owner) - - syncedClaim, found := suite.keeper.GetSwapClaim(suite.ctx, owner) - suite.True(found) - // A new claim should have empty indexes. It doesn't strictly need the poolID either. - expectedIndexes := types.MultiRewardIndexes{{ - CollateralType: poolID, - RewardIndexes: nil, - }} - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // a new claim should start with 0 rewards - suite.Equal(sdk.Coins(nil), syncedClaim.Reward) -} - -func (suite *InitializeSwapRewardTests) TestClaimAddedWhenClaimDoesNotExistAndRewardsExist() { - // When a claim doesn't exist, and a user deposits to a rewarded pool; - // then a claim is added with no rewards and indexes matching the global indexes - - poolID := "base:quote" - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: poolID, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(globalIndexes) - - owner := arbitraryAddress() - - suite.keeper.InitializeSwapReward(suite.ctx, poolID, owner) - - syncedClaim, found := suite.keeper.GetSwapClaim(suite.ctx, owner) - suite.True(found) - // a new claim should start with the current global indexes - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // a new claim should start with 0 rewards - suite.Equal(sdk.Coins(nil), syncedClaim.Reward) -} - -func (suite *InitializeSwapRewardTests) TestClaimUpdatedWhenClaimExistsAndNoRewards() { - // When a claim exists, and a user deposits to a new non-rewarded pool; - // then the claim's rewards don't change - - preexistingPoolID := "preexisting" - preexistingIndexes := types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - } - - newPoolID := "btcb:usdx" - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: preexistingPoolID, - RewardIndexes: preexistingIndexes, - }, - }, - } - suite.storeSwapClaim(claim) - - // no global indexes stored as the new pool is not rewarded - - suite.keeper.InitializeSwapReward(suite.ctx, newPoolID, claim.Owner) - - syncedClaim, _ := suite.keeper.GetSwapClaim(suite.ctx, claim.Owner) - // The preexisting indexes shouldn't be changed. It doesn't strictly need the new poolID either. - expectedIndexes := types.MultiRewardIndexes{ - { - CollateralType: preexistingPoolID, - RewardIndexes: preexistingIndexes, - }, - { - CollateralType: newPoolID, - RewardIndexes: nil, - }, - } - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // init should never alter the rewards - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *InitializeSwapRewardTests) TestClaimUpdatedWhenClaimExistsAndRewardsExist() { - // When a claim exists, and a user deposits to a new rewarded pool; - // then the claim's rewards don't change and the indexes are updated to match the global indexes - - preexistingPoolID := "preexisting" - preexistingIndexes := types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - } - - newPoolID := "btcb:usdx" - newIndexes := types.RewardIndexes{ - { - CollateralType: "otherrewarddenom", - RewardFactor: d("1000.001"), - }, - } - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: preexistingPoolID, - RewardIndexes: preexistingIndexes, - }, - }, - } - suite.storeSwapClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: preexistingPoolID, - RewardIndexes: increaseRewardFactors(preexistingIndexes), - }, - { - CollateralType: newPoolID, - RewardIndexes: newIndexes, - }, - } - suite.storeGlobalSwapIndexes(globalIndexes) - - suite.keeper.InitializeSwapReward(suite.ctx, newPoolID, claim.Owner) - - syncedClaim, _ := suite.keeper.GetSwapClaim(suite.ctx, claim.Owner) - // only the indexes for the new pool should be updated - expectedIndexes := types.MultiRewardIndexes{ - { - CollateralType: preexistingPoolID, - RewardIndexes: preexistingIndexes, - }, - { - CollateralType: newPoolID, - RewardIndexes: newIndexes, - }, - } - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // init should never alter the rewards - suite.Equal(claim.Reward, syncedClaim.Reward) -} diff --git a/x/incentive/keeper/rewards_swap_sync_test.go b/x/incentive/keeper/rewards_swap_sync_test.go deleted file mode 100644 index deb78e1c..00000000 --- a/x/incentive/keeper/rewards_swap_sync_test.go +++ /dev/null @@ -1,470 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// SynchronizeSwapRewardTests runs unit tests for the keeper.SynchronizeSwapReward method -// -// inputs -// - claim in store (only claim.RewardIndexes, claim.Reward) -// - global indexes in store -// - shares function arg -// -// outputs -// - sets a claim -type SynchronizeSwapRewardTests struct { - unitTester -} - -func TestSynchronizeSwapReward(t *testing.T) { - suite.Run(t, new(SynchronizeSwapRewardTests)) -} - -func (suite *SynchronizeSwapRewardTests) TestClaimUpdatedWhenGlobalIndexesHaveIncreased() { - // This is the normal case - // Given some time has passed (meaning the global indexes have increased) - // When the claim is synced - // The user earns rewards for the time passed, and the claim indexes are updated - - originalReward := arbitraryCoins() - poolID := "base:quote" - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: poolID, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeSwapClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: poolID, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("2000.002"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(globalIndexes) - - userShares := i(1e9) - - suite.keeper.SynchronizeSwapReward(suite.ctx, poolID, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetSwapClaim(suite.ctx, claim.Owner) - // indexes updated from global - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // new reward is (new index - old index) * user shares - suite.Equal( - cs(c("rewarddenom", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeSwapRewardTests) TestClaimUnchangedWhenGlobalIndexesUnchanged() { - // It should be safe to call SynchronizeSwapReward multiple times - - poolID := "base:quote" - unchangingIndexes := types.MultiRewardIndexes{ - { - CollateralType: poolID, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - } - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: unchangingIndexes, - } - suite.storeSwapClaim(claim) - - suite.storeGlobalSwapIndexes(unchangingIndexes) - - userShares := i(1e9) - - suite.keeper.SynchronizeSwapReward(suite.ctx, poolID, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetSwapClaim(suite.ctx, claim.Owner) - // claim should have the same rewards and indexes as before - suite.Equal(claim, syncedClaim) -} - -func (suite *SynchronizeSwapRewardTests) TestClaimUpdatedWhenNewRewardAdded() { - // When a new reward is added (via gov) for a pool the user has already deposited to, and the claim is synced; - // Then the user earns rewards for the time since the reward was added, and the indexes are added to the claim. - - originalReward := arbitraryCoins() - newlyRewardPoolID := "newlyRewardedPool" - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: "currentlyRewardedPool", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeSwapClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: "currentlyRewardedPool", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - }, - }, - { - CollateralType: newlyRewardPoolID, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(globalIndexes) - - userShares := i(1e9) - - suite.keeper.SynchronizeSwapReward(suite.ctx, newlyRewardPoolID, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetSwapClaim(suite.ctx, claim.Owner) - // the new indexes should be added to the claim, but the old ones should be unchanged - newlyRewrdedIndexes, _ := globalIndexes.Get(newlyRewardPoolID) - expectedIndexes := claim.RewardIndexes.With(newlyRewardPoolID, newlyRewrdedIndexes) - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) - // new reward is (new index - old index) * shares for the synced pool - // The old index for `newlyrewarded` isn't in the claim, so it's added starting at 0 for calculating the reward. - suite.Equal( - cs(c("otherreward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeSwapRewardTests) TestClaimUnchangedWhenNoReward() { - // When a pool is not rewarded but the user has deposited to that pool, and the claim is synced; - // Then the claim should be the same. - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: nonEmptyMultiRewardIndexes, - } - suite.storeSwapClaim(claim) - - poolID := "nonRewardPool" - // No global indexes stored as this pool is not rewarded - - userShares := i(1e9) - - suite.keeper.SynchronizeSwapReward(suite.ctx, poolID, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetSwapClaim(suite.ctx, claim.Owner) - suite.Equal(claim, syncedClaim) -} - -func (suite *SynchronizeSwapRewardTests) TestClaimUpdatedWhenNewRewardDenomAdded() { - // When a new reward coin is added (via gov) to an already rewarded pool (that the user has already deposited to), and the claim is synced; - // Then the user earns rewards for the time since the reward was added, and the new indexes are added. - - originalReward := arbitraryCoins() - poolID := "base:quote" - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: originalReward, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: poolID, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeSwapClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: poolID, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: d("2000.002"), - }, - { - CollateralType: "otherreward", - // Indexes start at 0 when the reward is added by gov, - // so this represents the syncing happening some time later. - RewardFactor: d("1000.001"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(globalIndexes) - - userShares := i(1e9) - - suite.keeper.SynchronizeSwapReward(suite.ctx, poolID, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetSwapClaim(suite.ctx, claim.Owner) - // indexes should have the new reward denom added - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // new reward is (new index - old index) * shares - // The old index for `otherreward` isn't in the claim, so it's added starting at 0 for calculating the reward. - suite.Equal( - cs(c("reward", 1_000_001_000_000), c("otherreward", 1_000_001_000_000)).Add(originalReward...), - syncedClaim.Reward, - ) -} - -func (suite *SynchronizeSwapRewardTests) TestClaimUpdatedWhenGlobalIndexesIncreasedAndSourceIsZero() { - // Given some time has passed (meaning the global indexes have increased) - // When the claim is synced, but the user has no shares - // The user earns no rewards for the time passed, but the claim indexes are updated - - poolID := "base:quote" - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: arbitraryAddress(), - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: poolID, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeSwapClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: poolID, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom", - RewardFactor: d("2000.002"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(globalIndexes) - - userShares := i(0) - - suite.keeper.SynchronizeSwapReward(suite.ctx, poolID, claim.Owner, userShares) - - syncedClaim, _ := suite.keeper.GetSwapClaim(suite.ctx, claim.Owner) - // indexes updated from global - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // reward is unchanged - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *SynchronizeSwapRewardTests) TestGetSyncedClaim_ClaimUnchangedWhenNoGlobalIndexes() { - poolID_1 := "btcb:usdx" - owner := arbitraryAddress() - - swapKeeper := newFakeSwapKeeper(). - addDeposit(poolID_1, owner, i(1e9)) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, swapKeeper, nil, nil, nil) - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: owner, - Reward: nil, - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: poolID_1, - RewardIndexes: nil, // this state only happens because Init stores empty indexes - }, - }, - } - suite.storeSwapClaim(claim) - - // no global indexes for any pool - - syncedClaim, f := suite.keeper.GetSynchronizedSwapClaim(suite.ctx, claim.Owner) - suite.True(f) - - // indexes are unchanged - suite.Equal(claim.RewardIndexes, syncedClaim.RewardIndexes) - // reward is unchanged - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *SynchronizeSwapRewardTests) TestGetSyncedClaim_ClaimUpdatedWhenMissingIndexAndHasNoSourceShares() { - poolID_1 := "btcb:usdx" - poolID_2 := "ukava:usdx" - owner := arbitraryAddress() - - // owner has no shares in any pool - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, newFakeSwapKeeper(), nil, nil, nil) - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: owner, - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: poolID_1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom1", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeSwapClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: poolID_1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom1", - RewardFactor: d("2000.002"), - }, - }, - }, - { - CollateralType: poolID_2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom2", - RewardFactor: d("2000.002"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(globalIndexes) - - syncedClaim, f := suite.keeper.GetSynchronizedSwapClaim(suite.ctx, claim.Owner) - suite.True(f) - - // indexes updated from global - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // reward is unchanged - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *SynchronizeSwapRewardTests) TestGetSyncedClaim_ClaimUpdatedWhenMissingIndexButHasSourceShares() { - poolID_1 := "btcb:usdx" - poolID_2 := "ukava:usdx" - owner := arbitraryAddress() - - swapKeeper := newFakeSwapKeeper(). - addDeposit(poolID_1, owner, i(1e9)). - addDeposit(poolID_2, owner, i(1e9)) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, swapKeeper, nil, nil, nil) - - claim := types.SwapClaim{ - BaseMultiClaim: types.BaseMultiClaim{ - Owner: owner, - Reward: arbitraryCoins(), - }, - RewardIndexes: types.MultiRewardIndexes{ - { - CollateralType: poolID_1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom1", - RewardFactor: d("1000.001"), - }, - }, - }, - }, - } - suite.storeSwapClaim(claim) - - globalIndexes := types.MultiRewardIndexes{ - { - CollateralType: poolID_1, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom1", - RewardFactor: d("2000.002"), - }, - }, - }, - { - CollateralType: poolID_2, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "rewarddenom2", - RewardFactor: d("2000.002"), - }, - }, - }, - } - suite.storeGlobalSwapIndexes(globalIndexes) - - syncedClaim, f := suite.keeper.GetSynchronizedSwapClaim(suite.ctx, claim.Owner) - suite.True(f) - - // indexes updated from global - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) - // reward is incremented - expectedReward := cs(c("rewarddenom1", 1_000_001_000_000), c("rewarddenom2", 2_000_002_000_000)) - suite.Equal(claim.Reward.Add(expectedReward...), syncedClaim.Reward) -} diff --git a/x/incentive/keeper/rewards_usdx.go b/x/incentive/keeper/rewards_usdx.go deleted file mode 100644 index bee935b1..00000000 --- a/x/incentive/keeper/rewards_usdx.go +++ /dev/null @@ -1,198 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - cdptypes "github.com/0glabs/0g-chain/x/cdp/types" - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// AccumulateUSDXMintingRewards calculates new rewards to distribute this block and updates the global indexes to reflect this. -// The provided rewardPeriod must be valid to avoid panics in calculating time durations. -func (k Keeper) AccumulateUSDXMintingRewards(ctx sdk.Context, rewardPeriod types.RewardPeriod) { - previousAccrualTime, found := k.GetPreviousUSDXMintingAccrualTime(ctx, rewardPeriod.CollateralType) - if !found { - previousAccrualTime = ctx.BlockTime() - } - - factor, found := k.GetUSDXMintingRewardFactor(ctx, rewardPeriod.CollateralType) - if !found { - factor = sdk.ZeroDec() - } - // wrap in RewardIndexes for compatibility with Accumulator - indexes := types.RewardIndexes{}.With(types.USDXMintingRewardDenom, factor) - - acc := types.NewAccumulator(previousAccrualTime, indexes) - - totalSource := k.getUSDXTotalSourceShares(ctx, rewardPeriod.CollateralType) - - acc.Accumulate(types.NewMultiRewardPeriodFromRewardPeriod(rewardPeriod), totalSource, ctx.BlockTime()) - - k.SetPreviousUSDXMintingAccrualTime(ctx, rewardPeriod.CollateralType, acc.PreviousAccumulationTime) - - factor, found = acc.Indexes.Get(types.USDXMintingRewardDenom) - if !found { - panic("could not find factor that should never be missing when accumulating usdx rewards") - } - k.SetUSDXMintingRewardFactor(ctx, rewardPeriod.CollateralType, factor) -} - -// getUSDXTotalSourceShares fetches the sum of all source shares for a usdx minting reward. -// In the case of usdx minting, this is the total debt from all cdps of a particular type, divided by the cdp interest factor. -// This gives the "pre interest" value of the total debt. -func (k Keeper) getUSDXTotalSourceShares(ctx sdk.Context, collateralType string) sdk.Dec { - totalPrincipal := k.cdpKeeper.GetTotalPrincipal(ctx, collateralType, cdptypes.DefaultStableDenom) - - cdpFactor, found := k.cdpKeeper.GetInterestFactor(ctx, collateralType) - if !found { - // assume nothing has been borrowed so the factor starts at it's default value - cdpFactor = sdk.OneDec() - } - // return debt/factor to get the "pre interest" value of the current total debt - return sdk.NewDecFromInt(totalPrincipal).Quo(cdpFactor) -} - -// InitializeUSDXMintingClaim creates or updates a claim such that no new rewards are accrued, but any existing rewards are not lost. -// this function should be called after a cdp is created. If a user previously had a cdp, then closed it, they shouldn't -// accrue rewards during the period the cdp was closed. By setting the reward factor to the current global reward factor, -// any unclaimed rewards are preserved, but no new rewards are added. -func (k Keeper) InitializeUSDXMintingClaim(ctx sdk.Context, cdp cdptypes.CDP) { - claim, found := k.GetUSDXMintingClaim(ctx, cdp.Owner) - if !found { // this is the owner's first usdx minting reward claim - claim = types.NewUSDXMintingClaim(cdp.Owner, sdk.NewCoin(types.USDXMintingRewardDenom, sdk.ZeroInt()), types.RewardIndexes{}) - } - - globalRewardFactor, found := k.GetUSDXMintingRewardFactor(ctx, cdp.Type) - if !found { - globalRewardFactor = sdk.ZeroDec() - } - claim.RewardIndexes = claim.RewardIndexes.With(cdp.Type, globalRewardFactor) - - k.SetUSDXMintingClaim(ctx, claim) -} - -// SynchronizeUSDXMintingReward updates the claim object by adding any accumulated rewards and updating the reward index value. -// this should be called before a cdp is modified. -func (k Keeper) SynchronizeUSDXMintingReward(ctx sdk.Context, cdp cdptypes.CDP) { - claim, found := k.GetUSDXMintingClaim(ctx, cdp.Owner) - if !found { - return - } - - sourceShares, err := cdp.GetNormalizedPrincipal() - if err != nil { - panic(fmt.Sprintf("during usdx reward sync, could not get normalized principal for %s: %s", cdp.Owner, err.Error())) - } - - claim = k.synchronizeSingleUSDXMintingReward(ctx, claim, cdp.Type, sourceShares) - - k.SetUSDXMintingClaim(ctx, claim) -} - -// synchronizeSingleUSDXMintingReward synchronizes a single rewarded cdp collateral type in a usdx minting claim. -// It returns the claim without setting in the store. -// The public methods for accessing and modifying claims are preferred over this one. Direct modification of claims is easy to get wrong. -func (k Keeper) synchronizeSingleUSDXMintingReward(ctx sdk.Context, claim types.USDXMintingClaim, ctype string, sourceShares sdk.Dec) types.USDXMintingClaim { - globalRewardFactor, found := k.GetUSDXMintingRewardFactor(ctx, ctype) - if !found { - // The global factor is only not found if - // - the cdp collateral type has not started accumulating rewards yet (either there is no reward specified in params, or the reward start time hasn't been hit) - // - OR it was wrongly deleted from state (factors should never be removed while unsynced claims exist) - // If not found we could either skip this sync, or assume the global factor is zero. - // Skipping will avoid storing unnecessary factors in the claim for non rewarded denoms. - // And in the event a global factor is wrongly deleted, it will avoid this function panicking when calculating rewards. - return claim - } - - userRewardFactor, found := claim.RewardIndexes.Get(ctype) - if !found { - // Normally the factor should always be found, as it is added when the cdp is created in InitializeUSDXMintingClaim. - // However if a cdp type is not rewarded then becomes rewarded (ie a reward period is added to params), existing cdps will not have the factor in their claims. - // So assume the factor is the starting value for any global factor: 0. - userRewardFactor = sdk.ZeroDec() - } - - newRewardsAmount, err := k.CalculateSingleReward(userRewardFactor, globalRewardFactor, sourceShares) - if err != nil { - // Global reward factors should never decrease, as it would lead to a negative update to claim.Rewards. - // This panics if a global reward factor decreases or disappears between the old and new indexes. - panic(fmt.Sprintf("corrupted global reward indexes found: %v", err)) - } - newRewardsCoin := sdk.NewCoin(types.USDXMintingRewardDenom, newRewardsAmount) - - claim.Reward = claim.Reward.Add(newRewardsCoin) - claim.RewardIndexes = claim.RewardIndexes.With(ctype, globalRewardFactor) - - return claim -} - -// SimulateUSDXMintingSynchronization calculates a user's outstanding USDX minting rewards by simulating reward synchronization -func (k Keeper) SimulateUSDXMintingSynchronization(ctx sdk.Context, claim types.USDXMintingClaim) types.USDXMintingClaim { - for _, ri := range claim.RewardIndexes { - _, found := k.GetUSDXMintingRewardPeriod(ctx, ri.CollateralType) - if !found { - continue - } - - globalRewardFactor, found := k.GetUSDXMintingRewardFactor(ctx, ri.CollateralType) - if !found { - globalRewardFactor = sdk.ZeroDec() - } - - // the owner has an existing usdx minting reward claim - index, hasRewardIndex := claim.HasRewardIndex(ri.CollateralType) - if !hasRewardIndex { // this is the owner's first usdx minting reward for this collateral type - claim.RewardIndexes = append(claim.RewardIndexes, types.NewRewardIndex(ri.CollateralType, globalRewardFactor)) - } - userRewardFactor := claim.RewardIndexes[index].RewardFactor - rewardsAccumulatedFactor := globalRewardFactor.Sub(userRewardFactor) - if rewardsAccumulatedFactor.IsZero() { - continue - } - - claim.RewardIndexes[index].RewardFactor = globalRewardFactor - - cdp, found := k.cdpKeeper.GetCdpByOwnerAndCollateralType(ctx, claim.GetOwner(), ri.CollateralType) - if !found { - continue - } - newRewardsAmount := rewardsAccumulatedFactor.Mul(sdk.NewDecFromInt(cdp.GetTotalPrincipal().Amount)).RoundInt() - if newRewardsAmount.IsZero() { - continue - } - newRewardsCoin := sdk.NewCoin(types.USDXMintingRewardDenom, newRewardsAmount) - claim.Reward = claim.Reward.Add(newRewardsCoin) - } - - return claim -} - -// SynchronizeUSDXMintingClaim updates the claim object by adding any rewards that have accumulated. -// Returns the updated claim object -func (k Keeper) SynchronizeUSDXMintingClaim(ctx sdk.Context, claim types.USDXMintingClaim) (types.USDXMintingClaim, error) { - for _, ri := range claim.RewardIndexes { - cdp, found := k.cdpKeeper.GetCdpByOwnerAndCollateralType(ctx, claim.Owner, ri.CollateralType) - if !found { - // if the cdp for this collateral type has been closed, no updates are needed - continue - } - claim = k.synchronizeRewardAndReturnClaim(ctx, cdp) - } - return claim, nil -} - -// this function assumes a claim already exists, so don't call it if that's not the case -func (k Keeper) synchronizeRewardAndReturnClaim(ctx sdk.Context, cdp cdptypes.CDP) types.USDXMintingClaim { - k.SynchronizeUSDXMintingReward(ctx, cdp) - claim, _ := k.GetUSDXMintingClaim(ctx, cdp.Owner) - return claim -} - -// ZeroUSDXMintingClaim zeroes out the claim object's rewards and returns the updated claim object -func (k Keeper) ZeroUSDXMintingClaim(ctx sdk.Context, claim types.USDXMintingClaim) types.USDXMintingClaim { - claim.Reward = sdk.NewCoin(claim.Reward.Denom, sdk.ZeroInt()) - k.SetUSDXMintingClaim(ctx, claim) - return claim -} diff --git a/x/incentive/keeper/rewards_usdx_accum_test.go b/x/incentive/keeper/rewards_usdx_accum_test.go deleted file mode 100644 index 21c52ff6..00000000 --- a/x/incentive/keeper/rewards_usdx_accum_test.go +++ /dev/null @@ -1,234 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -type AccumulateUSDXRewardsTests struct { - usdxRewardsUnitTester -} - -func (suite *AccumulateUSDXRewardsTests) storedTimeEquals(cType string, expected time.Time) { - storedTime, found := suite.keeper.GetPreviousUSDXMintingAccrualTime(suite.ctx, cType) - suite.True(found) - suite.Equal(expected, storedTime) -} - -func (suite *AccumulateUSDXRewardsTests) storedIndexesEqual(cType string, expected sdk.Dec) { - storedIndexes, found := suite.keeper.GetUSDXMintingRewardFactor(suite.ctx, cType) - suite.True(found) - suite.Equal(expected, storedIndexes) -} - -func TestAccumulateUSDXRewards(t *testing.T) { - suite.Run(t, new(AccumulateUSDXRewardsTests)) -} - -func (suite *AccumulateUSDXRewardsTests) TestStateUpdatedWhenBlockTimeHasIncreased() { - cType := "bnb-a" - - cdpKeeper := newFakeCDPKeeper().addTotalPrincipal(i(1e6)).addInterestFactor(d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, cdpKeeper, nil, nil, nil, nil, nil, nil, nil) - - suite.storeGlobalUSDXIndexes(types.RewardIndexes{ - { - CollateralType: cType, - RewardFactor: d("0.04"), - }, - }) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousUSDXMintingAccrualTime(suite.ctx, cType, previousAccrualTime) - - newAccrualTime := previousAccrualTime.Add(1 * time.Hour) - suite.ctx = suite.ctx.WithBlockTime(newAccrualTime) - - period := types.NewRewardPeriod( - true, - cType, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - c("ukava", 1000), - ) - - suite.keeper.AccumulateUSDXMintingRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(cType, newAccrualTime) - suite.storedIndexesEqual(cType, d("3.64")) -} - -func (suite *AccumulateUSDXRewardsTests) TestStateUnchangedWhenBlockTimeHasNotIncreased() { - cType := "bnb-a" - - cdpKeeper := newFakeCDPKeeper().addTotalPrincipal(i(1e6)).addInterestFactor(d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, cdpKeeper, nil, nil, nil, nil, nil, nil, nil) - - previousIndexes := types.RewardIndexes{ - { - CollateralType: cType, - RewardFactor: d("0.04"), - }, - } - suite.storeGlobalUSDXIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousUSDXMintingAccrualTime(suite.ctx, cType, previousAccrualTime) - - suite.ctx = suite.ctx.WithBlockTime(previousAccrualTime) - - period := types.NewRewardPeriod( - true, - cType, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - c("ukava", 2000), - ) - - suite.keeper.AccumulateUSDXMintingRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(cType, previousAccrualTime) - expected, f := previousIndexes.Get(cType) - suite.True(f) - suite.storedIndexesEqual(cType, expected) -} - -func (suite *AccumulateUSDXRewardsTests) TestNoAccumulationWhenSourceSharesAreZero() { - cType := "bnb-a" - - cdpKeeper := newFakeCDPKeeper() // zero total borrows - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, cdpKeeper, nil, nil, nil, nil, nil, nil, nil) - - previousIndexes := types.RewardIndexes{ - { - CollateralType: cType, - RewardFactor: d("0.04"), - }, - } - suite.storeGlobalUSDXIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousUSDXMintingAccrualTime(suite.ctx, cType, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(7 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - period := types.NewRewardPeriod( - true, - cType, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - c("ukava", 1000), - ) - - suite.keeper.AccumulateUSDXMintingRewards(suite.ctx, period) - - // check time and factors - - suite.storedTimeEquals(cType, firstAccrualTime) - expected, f := previousIndexes.Get(cType) - suite.True(f) - suite.storedIndexesEqual(cType, expected) -} - -func (suite *AccumulateUSDXRewardsTests) TestStateAddedWhenStateDoesNotExist() { - cType := "bnb-a" - - cdpKeeper := newFakeCDPKeeper().addTotalPrincipal(i(1e6)).addInterestFactor(d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, cdpKeeper, nil, nil, nil, nil, nil, nil, nil) - - period := types.NewRewardPeriod( - true, - cType, - time.Unix(0, 0), // ensure the test is within start and end times - distantFuture, - c("ukava", 1000), - ) - - firstAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateUSDXMintingRewards(suite.ctx, period) - - // After the first accumulation the current block time should be stored and the factor will be zero. - suite.storedTimeEquals(cType, firstAccrualTime) - suite.storedIndexesEqual(cType, sdk.ZeroDec()) - - secondAccrualTime := firstAccrualTime.Add(10 * time.Second) - suite.ctx = suite.ctx.WithBlockTime(secondAccrualTime) - - suite.keeper.AccumulateUSDXMintingRewards(suite.ctx, period) - - // After the second accumulation both current block time and indexes should be stored. - suite.storedTimeEquals(cType, secondAccrualTime) - suite.storedIndexesEqual(cType, d("0.01")) -} - -func (suite *AccumulateUSDXRewardsTests) TestNoAccumulationWhenBeforeStartTime() { - cType := "bnb-a" - - cdpKeeper := newFakeCDPKeeper().addTotalPrincipal(i(1e6)).addInterestFactor(d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, cdpKeeper, nil, nil, nil, nil, nil, nil, nil) - - previousIndexes := types.RewardIndexes{ - { - CollateralType: cType, - RewardFactor: d("0.04"), - }, - } - suite.storeGlobalUSDXIndexes(previousIndexes) - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousUSDXMintingAccrualTime(suite.ctx, cType, previousAccrualTime) - - firstAccrualTime := previousAccrualTime.Add(10 * time.Second) - - period := types.NewRewardPeriod( - true, - cType, - firstAccrualTime.Add(time.Nanosecond), // start time after accrual time - distantFuture, - c("ukava", 1000), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.keeper.AccumulateUSDXMintingRewards(suite.ctx, period) - - // The accrual time should be updated, but the indexes unchanged - suite.storedTimeEquals(cType, firstAccrualTime) - expected, f := previousIndexes.Get(cType) - suite.True(f) - suite.storedIndexesEqual(cType, expected) -} - -func (suite *AccumulateUSDXRewardsTests) TestPanicWhenCurrentTimeLessThanPrevious() { - cType := "bnb-a" - - cdpKeeper := newFakeCDPKeeper().addTotalPrincipal(i(1e6)).addInterestFactor(d("1")) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, cdpKeeper, nil, nil, nil, nil, nil, nil, nil) - - previousAccrualTime := time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC) - suite.keeper.SetPreviousUSDXMintingAccrualTime(suite.ctx, cType, previousAccrualTime) - - firstAccrualTime := time.Time{} - - period := types.NewRewardPeriod( - true, - cType, - time.Time{}, // start time after accrual time - distantFuture, - c("ukava", 1000), - ) - - suite.ctx = suite.ctx.WithBlockTime(firstAccrualTime) - - suite.Panics(func() { - suite.keeper.AccumulateUSDXMintingRewards(suite.ctx, period) - }) -} diff --git a/x/incentive/keeper/rewards_usdx_test.go b/x/incentive/keeper/rewards_usdx_test.go deleted file mode 100644 index c67fc747..00000000 --- a/x/incentive/keeper/rewards_usdx_test.go +++ /dev/null @@ -1,510 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - proposaltypes "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/app" - cdpkeeper "github.com/0glabs/0g-chain/x/cdp/keeper" - cdptypes "github.com/0glabs/0g-chain/x/cdp/types" - "github.com/0glabs/0g-chain/x/incentive/keeper" - "github.com/0glabs/0g-chain/x/incentive/testutil" - "github.com/0glabs/0g-chain/x/incentive/types" - kavadisttypes "github.com/0glabs/0g-chain/x/kavadist/types" -) - -type USDXIntegrationTests struct { - testutil.IntegrationTester - - genesisTime time.Time - addrs []sdk.AccAddress -} - -func TestUSDXIntegration(t *testing.T) { - suite.Run(t, new(USDXIntegrationTests)) -} - -// SetupTest is run automatically before each suite test -func (suite *USDXIntegrationTests) SetupTest() { - _, suite.addrs = app.GeneratePrivKeyAddressPairs(5) - - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *USDXIntegrationTests) ProposeAndVoteOnNewRewardPeriods(committeeID uint64, voter sdk.AccAddress, newPeriods types.RewardPeriods) { - suite.ProposeAndVoteOnNewParams( - voter, - committeeID, - []proposaltypes.ParamChange{{ - Subspace: types.ModuleName, - Key: string(types.KeyUSDXMintingRewardPeriods), - Value: string(types.ModuleCdc.LegacyAmino.MustMarshalJSON(newPeriods)), - }}) -} - -func (suite *USDXIntegrationTests) TestSingleUserAccumulatesRewardsAfterSyncing() { - userA := suite.addrs[0] - - authBulder := app.NewAuthBankGenesisBuilder(). - WithSimpleModuleAccount(kavadisttypes.ModuleName, cs(c(types.USDXMintingRewardDenom, 1e18))). // Fill kavadist with enough coins to pay out any reward - WithSimpleAccount(userA, cs(c("bnb", 1e12))) // give the user some coins - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithMultipliers(types.MultipliersPerDenoms{{ - Denom: types.USDXMintingRewardDenom, - Multipliers: types.Multipliers{types.NewMultiplier("large", 12, d("1.0"))}, // keep payout at 1.0 to make maths easier - }}). - WithSimpleUSDXRewardPeriod("bnb-a", c(types.USDXMintingRewardDenom, 1e6)) - - suite.SetApp() - suite.WithGenesisTime(suite.genesisTime) - suite.StartChain( - NewPricefeedGenStateMultiFromTime(suite.App.AppCodec(), suite.genesisTime), - NewCDPGenStateMulti(suite.App.AppCodec()), - authBulder.BuildMarshalled(suite.App.AppCodec()), - incentBuilder.BuildMarshalled(suite.App.AppCodec()), - ) - - // User creates a CDP to begin earning rewards. - suite.NoError( - suite.DeliverMsgCreateCDP(userA, c("bnb", 1e10), c(cdptypes.DefaultStableDenom, 1e9), "bnb-a"), - ) - - // Let time pass to accumulate interest on the deposit - // Use one long block instead of many to reduce any rounding errors, and speed up tests. - suite.NextBlockAfter(1e6 * time.Second) // about 12 days - - // User repays and borrows just to sync their CDP - suite.NoError( - suite.DeliverCDPMsgRepay(userA, "bnb-a", c(cdptypes.DefaultStableDenom, 1)), - ) - suite.NoError( - suite.DeliverCDPMsgBorrow(userA, "bnb-a", c(cdptypes.DefaultStableDenom, 1)), - ) - - // Accumulate more rewards. - // The user still has the same percentage of all CDP debt (100%) so their rewards should be the same as in the previous block. - suite.NextBlockAfter(1e6 * time.Second) // about 12 days - - // User claims all their rewards - msg := types.NewMsgClaimUSDXMintingReward(userA.String(), "large") - suite.Require().NoError(suite.DeliverIncentiveMsg(&msg)) - - // The users has always had 100% of cdp debt, so they should receive all rewards for the previous two blocks. - // Total rewards for each block is block duration * rewards per second - accuracy := 1e-18 // using a very high accuracy to flag future small calculation changes - suite.BalanceInEpsilon(userA, cs(c("bnb", 1e12-1e10), c(cdptypes.DefaultStableDenom, 1e9), c(types.USDXMintingRewardDenom, 2*1e6*1e6)), accuracy) -} - -func (suite *USDXIntegrationTests) TestSingleUserAccumulatesRewardsWithoutSyncing() { - user := suite.addrs[0] - initialCollateral := c("bnb", 1e9) - - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleModuleAccount(kavadisttypes.ModuleName, cs(c(types.USDXMintingRewardDenom, 1e18))). // Fill kavadist with enough coins to pay out any reward - WithSimpleAccount(user, cs(initialCollateral)) - - collateralType := "bnb-a" - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithMultipliers(types.MultipliersPerDenoms{{ - Denom: types.USDXMintingRewardDenom, - Multipliers: types.Multipliers{types.NewMultiplier("large", 12, d("1.0"))}, // keep payout at 1.0 to make maths easier - }}). - WithSimpleUSDXRewardPeriod(collateralType, c(types.USDXMintingRewardDenom, 1e6)) - - suite.SetApp() - suite.WithGenesisTime(suite.genesisTime) - suite.StartChain( - authBuilder.BuildMarshalled(suite.App.AppCodec()), - NewPricefeedGenStateMultiFromTime(suite.App.AppCodec(), suite.genesisTime), - NewCDPGenStateMulti(suite.App.AppCodec()), - incentBuilder.BuildMarshalled(suite.App.AppCodec()), - ) - - // Setup cdp state containing one CDP - suite.NoError( - suite.DeliverMsgCreateCDP(user, initialCollateral, c("usdx", 1e8), collateralType), - ) - - // Skip ahead a few blocks blocks to accumulate both interest and usdx reward for the cdp - // Don't sync the CDP between the blocks - suite.NextBlockAfter(1e6 * time.Second) // about 12 days - suite.NextBlockAfter(1e6 * time.Second) - suite.NextBlockAfter(1e6 * time.Second) - - msg := types.NewMsgClaimUSDXMintingReward(user.String(), "large") - suite.Require().NoError(suite.DeliverIncentiveMsg(&msg)) - - // The users has always had 100% of cdp debt, so they should receive all rewards for the previous two blocks. - // Total rewards for each block is block duration * rewards per second - accuracy := 1e-18 // using a very high accuracy to flag future small calculation changes - suite.BalanceInEpsilon(user, cs(c(cdptypes.DefaultStableDenom, 1e8), c(types.USDXMintingRewardDenom, 3*1e6*1e6)), accuracy) -} - -func (suite *USDXIntegrationTests) TestReinstatingRewardParamsDoesNotTriggerOverPayments() { - userA := suite.addrs[0] - userB := suite.addrs[1] - - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleModuleAccount(kavadisttypes.ModuleName, cs(c(types.USDXMintingRewardDenom, 1e18))). // Fill kavadist with enough coins to pay out any reward - WithSimpleAccount(userA, cs(c("bnb", 1e10))). - WithSimpleAccount(userB, cs(c("bnb", 1e10))) - - incentBuilder := testutil.NewIncentiveGenesisBuilder(). - WithGenesisTime(suite.genesisTime). - WithMultipliers(types.MultipliersPerDenoms{{ - Denom: types.USDXMintingRewardDenom, - Multipliers: types.Multipliers{types.NewMultiplier("large", 12, d("1.0"))}, // keep payout at 1.0 to make maths easier - }}). - WithSimpleUSDXRewardPeriod("bnb-a", c(types.USDXMintingRewardDenom, 1e6)) - - suite.SetApp() - suite.WithGenesisTime(suite.genesisTime) - suite.StartChain( - authBuilder.BuildMarshalled(suite.App.AppCodec()), - NewPricefeedGenStateMultiFromTime(suite.App.AppCodec(), suite.genesisTime), - NewCDPGenStateMulti(suite.App.AppCodec()), - incentBuilder.BuildMarshalled(suite.App.AppCodec()), - NewCommitteeGenesisState(suite.App.AppCodec(), 0, userA), // create a committtee to change params - ) - - // Accumulate some CDP rewards, requires creating a cdp so the total borrowed isn't 0. - suite.NoError( - suite.DeliverMsgCreateCDP(userA, c("bnb", 1e10), c("usdx", 1e9), "bnb-a"), - ) - suite.NextBlockAfter(1e6 * time.Second) - - // Remove the USDX reward period - suite.ProposeAndVoteOnNewRewardPeriods(0, userA, types.RewardPeriods{}) - // next block so proposal is enacted - suite.NextBlockAfter(1 * time.Second) - - // Create a CDP when there is no reward periods. In a previous version the claim object would not be created, leading to the bug. - // Withdraw the same amount of usdx as the first cdp currently has. This make the reward maths easier, as rewards will be split 50:50 between each cdp. - firstCDP, f := suite.App.GetCDPKeeper().GetCdpByOwnerAndCollateralType(suite.Ctx, userA, "bnb-a") - suite.True(f) - firstCDPTotalPrincipal := firstCDP.GetTotalPrincipal() - suite.NoError( - suite.DeliverMsgCreateCDP(userB, c("bnb", 1e10), firstCDPTotalPrincipal, "bnb-a"), - ) - - // Add back the reward period - suite.ProposeAndVoteOnNewRewardPeriods(0, userA, - types.RewardPeriods{types.NewRewardPeriod( - true, - "bnb-a", - suite.Ctx.BlockTime(), // start accumulating again from this block - suite.genesisTime.Add(365*24*time.Hour), - c(types.USDXMintingRewardDenom, 1e6), - )}, - ) - // next block so proposal is enacted - suite.NextBlockAfter(1 * time.Second) - - // Sync the cdp and claim by borrowing a bit - // In a previous version this would create the cdp with incorrect indexes, leading to overpayment. - suite.NoError( - suite.DeliverCDPMsgBorrow(userB, "bnb-a", c(cdptypes.DefaultStableDenom, 1)), - ) - - // Claim rewards - msg := types.NewMsgClaimUSDXMintingReward(userB.String(), "large") - suite.Require().NoError(suite.DeliverIncentiveMsg(&msg)) - - // The cdp had half the total borrows for a 1s block. So should earn half the rewards for that block - suite.BalanceInEpsilon( - userB, - cs(firstCDPTotalPrincipal.Add(c(cdptypes.DefaultStableDenom, 1)), c(types.USDXMintingRewardDenom, 0.5*1e6)), - 1e-18, // using very high accuracy to catch small changes to the calculations - ) -} - -// Test suite used for all keeper tests -type USDXRewardsTestSuite struct { - suite.Suite - - keeper keeper.Keeper - cdpKeeper cdpkeeper.Keeper - - app app.TestApp - ctx sdk.Context - - genesisTime time.Time - addrs []sdk.AccAddress -} - -// SetupTest is run automatically before each suite test -func (suite *USDXRewardsTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - _, suite.addrs = app.GeneratePrivKeyAddressPairs(5) - - suite.genesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *USDXRewardsTestSuite) SetupApp() { - suite.app = app.NewTestApp() - - suite.keeper = suite.app.GetIncentiveKeeper() - suite.cdpKeeper = suite.app.GetCDPKeeper() - - suite.ctx = suite.app.NewContext(true, tmproto.Header{Height: 1, Time: suite.genesisTime}) -} - -func (suite *USDXRewardsTestSuite) SetupWithGenState(authBuilder *app.AuthBankGenesisBuilder, incentBuilder testutil.IncentiveGenesisBuilder) { - suite.SetupApp() - - suite.app.InitializeFromGenesisStatesWithTime( - suite.genesisTime, - authBuilder.BuildMarshalled(suite.app.AppCodec()), - NewPricefeedGenStateMultiFromTime(suite.app.AppCodec(), suite.genesisTime), - NewCDPGenStateMulti(suite.app.AppCodec()), - incentBuilder.BuildMarshalled(suite.app.AppCodec()), - ) -} - -func (suite *USDXRewardsTestSuite) TestAccumulateUSDXMintingRewards() { - type args struct { - ctype string - rewardsPerSecond sdk.Coin - initialTotalPrincipal sdk.Coin - timeElapsed int - expectedRewardFactor sdk.Dec - } - type test struct { - name string - args args - } - testCases := []test{ - { - "7 seconds", - args{ - ctype: "bnb-a", - rewardsPerSecond: c("ukava", 122354), - initialTotalPrincipal: c("usdx", 1000000000000), - timeElapsed: 7, - expectedRewardFactor: d("0.000000856478000000"), - }, - }, - { - "1 day", - args{ - ctype: "bnb-a", - rewardsPerSecond: c("ukava", 122354), - initialTotalPrincipal: c("usdx", 1000000000000), - timeElapsed: 86400, - expectedRewardFactor: d("0.0105713856"), - }, - }, - { - "0 seconds", - args{ - ctype: "bnb-a", - rewardsPerSecond: c("ukava", 122354), - initialTotalPrincipal: c("usdx", 1000000000000), - timeElapsed: 0, - expectedRewardFactor: d("0.0"), - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - incentBuilder := testutil.NewIncentiveGenesisBuilder().WithGenesisTime(suite.genesisTime).WithSimpleUSDXRewardPeriod(tc.args.ctype, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(app.NewAuthBankGenesisBuilder(), incentBuilder) - - // setup cdp state - suite.cdpKeeper.SetTotalPrincipal(suite.ctx, tc.args.ctype, cdptypes.DefaultStableDenom, tc.args.initialTotalPrincipal.Amount) - - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * tc.args.timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - rewardPeriod, found := suite.keeper.GetUSDXMintingRewardPeriod(suite.ctx, tc.args.ctype) - suite.Require().True(found) - suite.keeper.AccumulateUSDXMintingRewards(suite.ctx, rewardPeriod) - - rewardFactor, _ := suite.keeper.GetUSDXMintingRewardFactor(suite.ctx, tc.args.ctype) - suite.Require().Equal(tc.args.expectedRewardFactor, rewardFactor) - }) - } -} - -func (suite *USDXRewardsTestSuite) TestSynchronizeUSDXMintingReward() { - type args struct { - ctype string - rewardsPerSecond sdk.Coin - initialCollateral sdk.Coin - initialPrincipal sdk.Coin - blockTimes []int - expectedRewardFactor sdk.Dec - expectedRewards sdk.Coin - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "10 blocks", - args{ - ctype: "bnb-a", - rewardsPerSecond: c("ukava", 122354), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 10000000000), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardFactor: d("0.001223540000000000"), - expectedRewards: c("ukava", 12235400), - }, - }, - { - "10 blocks - long block time", - args{ - ctype: "bnb-a", - rewardsPerSecond: c("ukava", 122354), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 10000000000), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardFactor: d("10.57138560000000000"), - expectedRewards: c("ukava", 105713856000), - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - authBuilder := app.NewAuthBankGenesisBuilder().WithSimpleAccount(suite.addrs[0], cs(tc.args.initialCollateral)) - incentBuilder := testutil.NewIncentiveGenesisBuilder().WithGenesisTime(suite.genesisTime).WithSimpleUSDXRewardPeriod(tc.args.ctype, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder) - - // setup cdp state - err := suite.cdpKeeper.AddCdp(suite.ctx, suite.addrs[0], tc.args.initialCollateral, tc.args.initialPrincipal, tc.args.ctype) - suite.Require().NoError(err) - - claim, found := suite.keeper.GetUSDXMintingClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - suite.Require().Equal(sdk.ZeroDec(), claim.RewardIndexes[0].RewardFactor) - - var timeElapsed int - previousBlockTime := suite.ctx.BlockTime() - for _, t := range tc.args.blockTimes { - timeElapsed += t - updatedBlockTime := previousBlockTime.Add(time.Duration(int(time.Second) * t)) - previousBlockTime = updatedBlockTime - blockCtx := suite.ctx.WithBlockTime(updatedBlockTime) - rewardPeriod, found := suite.keeper.GetUSDXMintingRewardPeriod(blockCtx, tc.args.ctype) - suite.Require().True(found) - suite.keeper.AccumulateUSDXMintingRewards(blockCtx, rewardPeriod) - } - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - cdp, found := suite.cdpKeeper.GetCdpByOwnerAndCollateralType(suite.ctx, suite.addrs[0], tc.args.ctype) - suite.Require().True(found) - suite.Require().NotPanics(func() { - suite.keeper.SynchronizeUSDXMintingReward(suite.ctx, cdp) - }) - - rewardFactor, _ := suite.keeper.GetUSDXMintingRewardFactor(suite.ctx, tc.args.ctype) - suite.Require().Equal(tc.args.expectedRewardFactor, rewardFactor) - - claim, found = suite.keeper.GetUSDXMintingClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - suite.Require().Equal(tc.args.expectedRewardFactor, claim.RewardIndexes[0].RewardFactor) - suite.Require().Equal(tc.args.expectedRewards, claim.Reward) - }) - } -} - -func (suite *USDXRewardsTestSuite) TestSimulateUSDXMintingRewardSynchronization() { - type args struct { - ctype string - rewardsPerSecond sdk.Coin - initialCollateral sdk.Coin - initialPrincipal sdk.Coin - blockTimes []int - expectedRewardFactor sdk.Dec - expectedRewards sdk.Coin - } - type test struct { - name string - args args - } - - testCases := []test{ - { - "10 blocks", - args{ - ctype: "bnb-a", - rewardsPerSecond: c("ukava", 122354), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 10000000000), - blockTimes: []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, - expectedRewardFactor: d("0.001223540000000000"), - expectedRewards: c("ukava", 12235400), - }, - }, - { - "10 blocks - long block time", - args{ - ctype: "bnb-a", - rewardsPerSecond: c("ukava", 122354), - initialCollateral: c("bnb", 1000000000000), - initialPrincipal: c("usdx", 10000000000), - blockTimes: []int{86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400, 86400}, - expectedRewardFactor: d("10.57138560000000000"), - expectedRewards: c("ukava", 105713856000), - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - authBuilder := app.NewAuthBankGenesisBuilder().WithSimpleAccount(suite.addrs[0], cs(tc.args.initialCollateral)) - incentBuilder := testutil.NewIncentiveGenesisBuilder().WithGenesisTime(suite.genesisTime).WithSimpleUSDXRewardPeriod(tc.args.ctype, tc.args.rewardsPerSecond) - - suite.SetupWithGenState(authBuilder, incentBuilder) - - // setup cdp state - err := suite.cdpKeeper.AddCdp(suite.ctx, suite.addrs[0], tc.args.initialCollateral, tc.args.initialPrincipal, tc.args.ctype) - suite.Require().NoError(err) - - claim, found := suite.keeper.GetUSDXMintingClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - suite.Require().Equal(sdk.ZeroDec(), claim.RewardIndexes[0].RewardFactor) - - var timeElapsed int - previousBlockTime := suite.ctx.BlockTime() - for _, t := range tc.args.blockTimes { - timeElapsed += t - updatedBlockTime := previousBlockTime.Add(time.Duration(int(time.Second) * t)) - previousBlockTime = updatedBlockTime - blockCtx := suite.ctx.WithBlockTime(updatedBlockTime) - rewardPeriod, found := suite.keeper.GetUSDXMintingRewardPeriod(blockCtx, tc.args.ctype) - suite.Require().True(found) - suite.keeper.AccumulateUSDXMintingRewards(blockCtx, rewardPeriod) - } - updatedBlockTime := suite.ctx.BlockTime().Add(time.Duration(int(time.Second) * timeElapsed)) - suite.ctx = suite.ctx.WithBlockTime(updatedBlockTime) - - claim, found = suite.keeper.GetUSDXMintingClaim(suite.ctx, suite.addrs[0]) - suite.Require().True(found) - suite.Require().Equal(claim.RewardIndexes[0].RewardFactor, sdk.ZeroDec()) - suite.Require().Equal(claim.Reward, sdk.NewCoin("ukava", sdk.ZeroInt())) - - updatedClaim := suite.keeper.SimulateUSDXMintingSynchronization(suite.ctx, claim) - suite.Require().Equal(tc.args.expectedRewardFactor, updatedClaim.RewardIndexes[0].RewardFactor) - suite.Require().Equal(tc.args.expectedRewards, updatedClaim.Reward) - }) - } -} - -func TestUSDXRewardsTestSuite(t *testing.T) { - suite.Run(t, new(USDXRewardsTestSuite)) -} diff --git a/x/incentive/keeper/rewards_usdx_unit_test.go b/x/incentive/keeper/rewards_usdx_unit_test.go deleted file mode 100644 index 3425c3d3..00000000 --- a/x/incentive/keeper/rewards_usdx_unit_test.go +++ /dev/null @@ -1,302 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - cdptypes "github.com/0glabs/0g-chain/x/cdp/types" - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// usdxRewardsUnitTester contains common methods for running unit tests for keeper methods related to the USDX minting rewards -type usdxRewardsUnitTester struct { - unitTester -} - -func (suite *usdxRewardsUnitTester) storeGlobalUSDXIndexes(indexes types.RewardIndexes) { - for _, ri := range indexes { - suite.keeper.SetUSDXMintingRewardFactor(suite.ctx, ri.CollateralType, ri.RewardFactor) - } -} - -func (suite *usdxRewardsUnitTester) storeClaim(claim types.USDXMintingClaim) { - suite.keeper.SetUSDXMintingClaim(suite.ctx, claim) -} - -type InitializeUSDXMintingClaimTests struct { - usdxRewardsUnitTester -} - -func TestInitializeUSDXMintingClaims(t *testing.T) { - suite.Run(t, new(InitializeUSDXMintingClaimTests)) -} - -func (suite *InitializeUSDXMintingClaimTests) TestClaimIndexIsSetWhenClaimDoesNotExist() { - collateralType := "bnb-a" - - cdp := NewCDPBuilder(arbitraryAddress(), collateralType).Build() - - globalIndexes := types.RewardIndexes{{ - CollateralType: collateralType, - RewardFactor: d("0.2"), - }} - suite.storeGlobalUSDXIndexes(globalIndexes) - - suite.keeper.InitializeUSDXMintingClaim(suite.ctx, cdp) - - syncedClaim, f := suite.keeper.GetUSDXMintingClaim(suite.ctx, cdp.Owner) - suite.True(f) - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) -} - -func (suite *InitializeUSDXMintingClaimTests) TestClaimIndexIsSetWhenClaimExists() { - collateralType := "bnb-a" - - claim := types.USDXMintingClaim{ - BaseClaim: types.BaseClaim{ - Owner: arbitraryAddress(), - }, - RewardIndexes: types.RewardIndexes{{ - CollateralType: collateralType, - RewardFactor: d("0.1"), - }}, - } - suite.storeClaim(claim) - - globalIndexes := types.RewardIndexes{{ - CollateralType: collateralType, - RewardFactor: d("0.2"), - }} - suite.storeGlobalUSDXIndexes(globalIndexes) - - cdp := NewCDPBuilder(claim.Owner, collateralType).Build() - - suite.keeper.InitializeUSDXMintingClaim(suite.ctx, cdp) - - syncedClaim, _ := suite.keeper.GetUSDXMintingClaim(suite.ctx, cdp.Owner) - suite.Equal(globalIndexes, syncedClaim.RewardIndexes) -} - -type SynchronizeUSDXMintingRewardTests struct { - usdxRewardsUnitTester -} - -func TestSynchronizeUSDXMintingReward(t *testing.T) { - suite.Run(t, new(SynchronizeUSDXMintingRewardTests)) -} - -func (suite *SynchronizeUSDXMintingRewardTests) TestRewardUnchangedWhenGlobalIndexesUnchanged() { - unchangingRewardIndexes := nonEmptyRewardIndexes - collateralType := extractFirstCollateralType(unchangingRewardIndexes) - - claim := types.USDXMintingClaim{ - BaseClaim: types.BaseClaim{ - Owner: arbitraryAddress(), - Reward: c(types.USDXMintingRewardDenom, 0), - }, - RewardIndexes: unchangingRewardIndexes, - } - suite.storeClaim(claim) - - suite.storeGlobalUSDXIndexes(unchangingRewardIndexes) - - cdp := NewCDPBuilder(claim.Owner, collateralType).WithSourceShares(1e12).Build() - - suite.keeper.SynchronizeUSDXMintingReward(suite.ctx, cdp) - - syncedClaim, _ := suite.keeper.GetUSDXMintingClaim(suite.ctx, claim.Owner) - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -func (suite *SynchronizeUSDXMintingRewardTests) TestRewardIsIncrementedWhenGlobalIndexIncreased() { - collateralType := "bnb-a" - - claim := types.USDXMintingClaim{ - BaseClaim: types.BaseClaim{ - Owner: arbitraryAddress(), - Reward: c(types.USDXMintingRewardDenom, 0), - }, - RewardIndexes: types.RewardIndexes{ - { - CollateralType: collateralType, - RewardFactor: d("0.1"), - }, - }, - } - suite.storeClaim(claim) - - globalIndexes := types.RewardIndexes{ - { - CollateralType: collateralType, - RewardFactor: d("0.2"), - }, - } - suite.storeGlobalUSDXIndexes(globalIndexes) - - cdp := NewCDPBuilder(claim.Owner, collateralType).WithSourceShares(1e12).Build() - - suite.keeper.SynchronizeUSDXMintingReward(suite.ctx, cdp) - - syncedClaim, _ := suite.keeper.GetUSDXMintingClaim(suite.ctx, claim.Owner) - // reward is ( new index - old index ) * cdp.TotalPrincipal - suite.Equal(c(types.USDXMintingRewardDenom, 1e11), syncedClaim.Reward) -} - -func (suite *SynchronizeUSDXMintingRewardTests) TestClaimIndexIsUpdatedWhenGlobalIndexIncreased() { - claimsRewardIndexes := nonEmptyRewardIndexes - collateralType := extractFirstCollateralType(claimsRewardIndexes) - - claim := types.USDXMintingClaim{ - BaseClaim: types.BaseClaim{ - Owner: arbitraryAddress(), - Reward: c(types.USDXMintingRewardDenom, 0), - }, - RewardIndexes: claimsRewardIndexes, - } - suite.storeClaim(claim) - - globalIndexes := increaseRewardFactors(claimsRewardIndexes) - suite.storeGlobalUSDXIndexes(globalIndexes) - - cdp := NewCDPBuilder(claim.Owner, collateralType).Build() - - suite.keeper.SynchronizeUSDXMintingReward(suite.ctx, cdp) - - syncedClaim, _ := suite.keeper.GetUSDXMintingClaim(suite.ctx, claim.Owner) - - // Only the claim's index for `collateralType` should have been changed - i, _ := globalIndexes.Get(collateralType) - expectedIndexes := claimsRewardIndexes.With(collateralType, i) - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) -} - -func (suite *SynchronizeUSDXMintingRewardTests) TestClaimIndexIsUpdatedWhenNewRewardAddedAndClaimAlreadyExists() { - claimsRewardIndexes := types.RewardIndexes{ - { - CollateralType: "bnb-a", - RewardFactor: d("0.1"), - }, - { - CollateralType: "busd-b", - RewardFactor: d("0.4"), - }, - } - newRewardIndex := types.NewRewardIndex("xrp-a", d("0.0001")) - - claim := types.USDXMintingClaim{ - BaseClaim: types.BaseClaim{ - Owner: arbitraryAddress(), - Reward: c(types.USDXMintingRewardDenom, 0), - }, - RewardIndexes: claimsRewardIndexes, - } - suite.storeClaim(claim) - - globalIndexes := increaseRewardFactors(claimsRewardIndexes) - globalIndexes = append(globalIndexes, newRewardIndex) - suite.storeGlobalUSDXIndexes(globalIndexes) - - cdp := NewCDPBuilder(claim.Owner, newRewardIndex.CollateralType).Build() - - suite.keeper.SynchronizeUSDXMintingReward(suite.ctx, cdp) - - syncedClaim, _ := suite.keeper.GetUSDXMintingClaim(suite.ctx, claim.Owner) - - // Only the claim's index for `collateralType` should have been changed - expectedIndexes := claimsRewardIndexes.With(newRewardIndex.CollateralType, newRewardIndex.RewardFactor) - suite.Equal(expectedIndexes, syncedClaim.RewardIndexes) -} - -func (suite *SynchronizeUSDXMintingRewardTests) TestClaimIsUnchangedWhenGlobalFactorMissing() { - claimsRewardIndexes := nonEmptyRewardIndexes - claim := types.USDXMintingClaim{ - BaseClaim: types.BaseClaim{ - Owner: arbitraryAddress(), - Reward: c(types.USDXMintingRewardDenom, 0), - }, - RewardIndexes: claimsRewardIndexes, - } - suite.storeClaim(claim) - // don't store any reward indexes - - // create a cdp with collateral type that doesn't exist in the claim's indexes, and does not have a corresponding global factor - cdp := NewCDPBuilder(claim.Owner, "unrewardedcollateral").WithSourceShares(1e12).Build() - - suite.keeper.SynchronizeUSDXMintingReward(suite.ctx, cdp) - - syncedClaim, _ := suite.keeper.GetUSDXMintingClaim(suite.ctx, claim.Owner) - suite.Equal(claim.RewardIndexes, syncedClaim.RewardIndexes) - suite.Equal(claim.Reward, syncedClaim.Reward) -} - -// CDPBuilder is a tool for creating a CDP in tests. -// The builder inherits from cdp.CDP, so fields can be accessed directly if a helper method doesn't exist. -type CDPBuilder struct { - cdptypes.CDP -} - -// NewCDPBuilder creates a CdpBuilder containing a CDP with owner and collateral type set. -func NewCDPBuilder(owner sdk.AccAddress, collateralType string) CDPBuilder { - return CDPBuilder{ - CDP: cdptypes.CDP{ - Owner: owner, - Type: collateralType, - // The zero value of Principal and AccumulatedFees (type sdk.Coin) is invalid as the denom is "" - // Set them to the default denom, but with 0 amount. - Principal: c(cdptypes.DefaultStableDenom, 0), - AccumulatedFees: c(cdptypes.DefaultStableDenom, 0), - // zero value of sdk.Dec causes nil pointer panics - InterestFactor: sdk.OneDec(), - }, - } -} - -// Build assembles and returns the final deposit. -func (builder CDPBuilder) Build() cdptypes.CDP { return builder.CDP } - -// WithSourceShares adds a principal amount and interest factor such that the source shares for this CDP is equal to specified. -// With a factor of 1, the total principal is the source shares. This picks an arbitrary factor to ensure factors are accounted for in production code. -func (builder CDPBuilder) WithSourceShares(shares int64) CDPBuilder { - if !builder.GetTotalPrincipal().Amount.Equal(sdk.ZeroInt()) { - panic("setting source shares on cdp with existing principal or fees not implemented") - } - if !(builder.InterestFactor.IsNil() || builder.InterestFactor.Equal(sdk.OneDec())) { - panic("setting source shares on cdp with existing interest factor not implemented") - } - // pick arbitrary interest factor - factor := sdkmath.NewInt(2) - - // Calculate deposit amount that would equal the requested source shares given the above factor. - principal := sdkmath.NewInt(shares).Mul(factor) - - builder.Principal = sdk.NewCoin(cdptypes.DefaultStableDenom, principal) - builder.InterestFactor = sdk.NewDecFromInt(factor) - - return builder -} - -func (builder CDPBuilder) WithPrincipal(principal sdkmath.Int) CDPBuilder { - builder.Principal = sdk.NewCoin(cdptypes.DefaultStableDenom, principal) - return builder -} - -var nonEmptyRewardIndexes = types.RewardIndexes{ - { - CollateralType: "bnb-a", - RewardFactor: d("0.1"), - }, - { - CollateralType: "busd-b", - RewardFactor: d("0.4"), - }, -} - -func extractFirstCollateralType(indexes types.RewardIndexes) string { - if len(indexes) == 0 { - panic("cannot extract a collateral type from 0 length RewardIndexes") - } - return indexes[0].CollateralType -} diff --git a/x/incentive/keeper/unit_test.go b/x/incentive/keeper/unit_test.go deleted file mode 100644 index ee1008f8..00000000 --- a/x/incentive/keeper/unit_test.go +++ /dev/null @@ -1,877 +0,0 @@ -package keeper_test - -import ( - "fmt" - "strings" - "time" - - sdkmath "cosmossdk.io/math" - pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" - db "github.com/cometbft/cometbft-db" - "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/app" - cdptypes "github.com/0glabs/0g-chain/x/cdp/types" - earntypes "github.com/0glabs/0g-chain/x/earn/types" - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - - hardtypes "github.com/0glabs/0g-chain/x/hard/types" - "github.com/0glabs/0g-chain/x/incentive/keeper" - "github.com/0glabs/0g-chain/x/incentive/types" -) - -// NewTestContext sets up a basic context with an in-memory db -func NewTestContext(requiredStoreKeys ...storetypes.StoreKey) sdk.Context { - memDB := db.NewMemDB() - cms := store.NewCommitMultiStore(memDB) - - for _, key := range requiredStoreKeys { - cms.MountStoreWithDB(key, storetypes.StoreTypeIAVL, nil) - } - - if err := cms.LoadLatestVersion(); err != nil { - panic(err) - } - - return sdk.NewContext(cms, tmprototypes.Header{}, false, log.NewNopLogger()) -} - -// unitTester is a wrapper around suite.Suite, with common functionality for keeper unit tests. -// It can be embedded in structs the same way as suite.Suite. -type unitTester struct { - suite.Suite - keeper keeper.Keeper - ctx sdk.Context - - cdc codec.Codec - incentiveStoreKey storetypes.StoreKey -} - -func (suite *unitTester) SetupSuite() { - tApp := app.NewTestApp() - suite.cdc = tApp.AppCodec() - - suite.incentiveStoreKey = sdk.NewKVStoreKey(types.StoreKey) -} - -func (suite *unitTester) SetupTest() { - suite.ctx = NewTestContext(suite.incentiveStoreKey) - suite.keeper = suite.NewKeeper(&fakeParamSubspace{}, nil, nil, nil, nil, nil, nil, nil, nil, nil) -} - -func (suite *unitTester) TearDownTest() { - suite.keeper = keeper.Keeper{} - suite.ctx = sdk.Context{} -} - -func (suite *unitTester) NewKeeper( - paramSubspace types.ParamSubspace, - bk types.BankKeeper, cdpk types.CdpKeeper, hk types.HardKeeper, - ak types.AccountKeeper, stk types.StakingKeeper, swk types.SwapKeeper, - svk types.SavingsKeeper, lqk types.LiquidKeeper, ek types.EarnKeeper, -) keeper.Keeper { - return keeper.NewKeeper( - suite.cdc, suite.incentiveStoreKey, paramSubspace, - bk, cdpk, hk, ak, stk, swk, svk, lqk, ek, - nil, nil, nil, - ) -} - -func (suite *unitTester) storeGlobalBorrowIndexes(indexes types.MultiRewardIndexes) { - for _, i := range indexes { - suite.keeper.SetHardBorrowRewardIndexes(suite.ctx, i.CollateralType, i.RewardIndexes) - } -} - -func (suite *unitTester) storeGlobalSupplyIndexes(indexes types.MultiRewardIndexes) { - for _, i := range indexes { - suite.keeper.SetHardSupplyRewardIndexes(suite.ctx, i.CollateralType, i.RewardIndexes) - } -} - -func (suite *unitTester) storeGlobalDelegatorIndexes(multiRewardIndexes types.MultiRewardIndexes) { - // Hardcoded to use bond denom - multiRewardIndex, _ := multiRewardIndexes.GetRewardIndex(types.BondDenom) - suite.keeper.SetDelegatorRewardIndexes(suite.ctx, types.BondDenom, multiRewardIndex.RewardIndexes) -} - -func (suite *unitTester) storeGlobalSwapIndexes(indexes types.MultiRewardIndexes) { - for _, i := range indexes { - suite.keeper.SetSwapRewardIndexes(suite.ctx, i.CollateralType, i.RewardIndexes) - } -} - -func (suite *unitTester) storeGlobalSavingsIndexes(indexes types.MultiRewardIndexes) { - for _, i := range indexes { - suite.keeper.SetSavingsRewardIndexes(suite.ctx, i.CollateralType, i.RewardIndexes) - } -} - -func (suite *unitTester) storeGlobalEarnIndexes(indexes types.MultiRewardIndexes) { - for _, i := range indexes { - suite.keeper.SetEarnRewardIndexes(suite.ctx, i.CollateralType, i.RewardIndexes) - } -} - -func (suite *unitTester) storeHardClaim(claim types.HardLiquidityProviderClaim) { - suite.keeper.SetHardLiquidityProviderClaim(suite.ctx, claim) -} - -func (suite *unitTester) storeDelegatorClaim(claim types.DelegatorClaim) { - suite.keeper.SetDelegatorClaim(suite.ctx, claim) -} - -func (suite *unitTester) storeSwapClaim(claim types.SwapClaim) { - suite.keeper.SetSwapClaim(suite.ctx, claim) -} - -func (suite *unitTester) storeSavingsClaim(claim types.SavingsClaim) { - suite.keeper.SetSavingsClaim(suite.ctx, claim) -} - -func (suite *unitTester) storeEarnClaim(claim types.EarnClaim) { - suite.keeper.SetEarnClaim(suite.ctx, claim) -} - -type TestKeeperBuilder struct { - cdc codec.Codec - key storetypes.StoreKey - paramSubspace types.ParamSubspace - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - cdpKeeper types.CdpKeeper - hardKeeper types.HardKeeper - stakingKeeper types.StakingKeeper - swapKeeper types.SwapKeeper - savingsKeeper types.SavingsKeeper - liquidKeeper types.LiquidKeeper - earnKeeper types.EarnKeeper - - // Keepers used for APY queries - mintKeeper types.MintKeeper - distrKeeper types.DistrKeeper - pricefeedKeeper types.PricefeedKeeper -} - -func (suite *unitTester) NewTestKeeper( - paramSubspace types.ParamSubspace, -) *TestKeeperBuilder { - if !paramSubspace.HasKeyTable() { - paramSubspace = paramSubspace.WithKeyTable(types.ParamKeyTable()) - } - - return &TestKeeperBuilder{ - cdc: suite.cdc, - key: suite.incentiveStoreKey, - paramSubspace: paramSubspace, - accountKeeper: nil, - bankKeeper: nil, - cdpKeeper: nil, - hardKeeper: nil, - stakingKeeper: nil, - swapKeeper: nil, - savingsKeeper: nil, - liquidKeeper: nil, - earnKeeper: nil, - mintKeeper: nil, - distrKeeper: nil, - pricefeedKeeper: nil, - } -} - -func (tk *TestKeeperBuilder) WithPricefeedKeeper(k types.PricefeedKeeper) *TestKeeperBuilder { - tk.pricefeedKeeper = k - return tk -} - -func (tk *TestKeeperBuilder) WithDistrKeeper(k types.DistrKeeper) *TestKeeperBuilder { - tk.distrKeeper = k - return tk -} - -func (tk *TestKeeperBuilder) WithBankKeeper(k types.BankKeeper) *TestKeeperBuilder { - tk.bankKeeper = k - return tk -} - -func (tk *TestKeeperBuilder) WithStakingKeeper(k types.StakingKeeper) *TestKeeperBuilder { - tk.stakingKeeper = k - return tk -} - -func (tk *TestKeeperBuilder) WithMintKeeper(k types.MintKeeper) *TestKeeperBuilder { - tk.mintKeeper = k - return tk -} - -func (tk *TestKeeperBuilder) WithEarnKeeper(k types.EarnKeeper) *TestKeeperBuilder { - tk.earnKeeper = k - return tk -} - -func (tk *TestKeeperBuilder) WithLiquidKeeper(k types.LiquidKeeper) *TestKeeperBuilder { - tk.liquidKeeper = k - return tk -} - -func (tk *TestKeeperBuilder) Build() keeper.Keeper { - return keeper.NewKeeper( - tk.cdc, tk.key, tk.paramSubspace, - tk.bankKeeper, tk.cdpKeeper, tk.hardKeeper, tk.accountKeeper, - tk.stakingKeeper, tk.swapKeeper, tk.savingsKeeper, tk.liquidKeeper, - tk.earnKeeper, tk.mintKeeper, tk.distrKeeper, tk.pricefeedKeeper, - ) -} - -// fakeParamSubspace is a stub paramSpace to simplify keeper unit test setup. -type fakeParamSubspace struct { - params types.Params -} - -func (subspace *fakeParamSubspace) GetParamSet(_ sdk.Context, ps paramtypes.ParamSet) { - *(ps.(*types.Params)) = subspace.params -} - -func (subspace *fakeParamSubspace) SetParamSet(_ sdk.Context, ps paramtypes.ParamSet) { - subspace.params = *(ps.(*types.Params)) -} - -func (subspace *fakeParamSubspace) HasKeyTable() bool { - // return true so the keeper does not try to call WithKeyTable, which does nothing - return true -} - -func (subspace *fakeParamSubspace) WithKeyTable(paramtypes.KeyTable) paramtypes.Subspace { - // return an non-functional subspace to satisfy the interface - return paramtypes.Subspace{} -} - -// fakeSwapKeeper is a stub swap keeper. -// It can be used to return values to the incentive keeper without having to initialize a full swap keeper. -type fakeSwapKeeper struct { - poolShares map[string]sdkmath.Int - depositShares map[string](map[string]sdkmath.Int) -} - -var _ types.SwapKeeper = newFakeSwapKeeper() - -func newFakeSwapKeeper() *fakeSwapKeeper { - return &fakeSwapKeeper{ - poolShares: map[string]sdkmath.Int{}, - depositShares: map[string](map[string]sdkmath.Int){}, - } -} - -func (k *fakeSwapKeeper) addPool(id string, shares sdkmath.Int) *fakeSwapKeeper { - k.poolShares[id] = shares - return k -} - -func (k *fakeSwapKeeper) addDeposit(poolID string, depositor sdk.AccAddress, shares sdkmath.Int) *fakeSwapKeeper { - if k.depositShares[poolID] == nil { - k.depositShares[poolID] = map[string]sdkmath.Int{} - } - k.depositShares[poolID][depositor.String()] = shares - return k -} - -func (k *fakeSwapKeeper) GetPoolShares(_ sdk.Context, poolID string) (sdkmath.Int, bool) { - shares, ok := k.poolShares[poolID] - return shares, ok -} - -func (k *fakeSwapKeeper) GetDepositorSharesAmount(_ sdk.Context, depositor sdk.AccAddress, poolID string) (sdkmath.Int, bool) { - shares, found := k.depositShares[poolID][depositor.String()] - return shares, found -} - -// fakeHardKeeper is a stub hard keeper. -// It can be used to return values to the incentive keeper without having to initialize a full hard keeper. -type fakeHardKeeper struct { - borrows fakeHardState - deposits fakeHardState -} - -type fakeHardState struct { - total sdk.Coins - interestFactors map[string]sdk.Dec -} - -func newFakeHardState() fakeHardState { - return fakeHardState{ - total: nil, - interestFactors: map[string]sdk.Dec{}, // initialize map to avoid panics on read - } -} - -var _ types.HardKeeper = newFakeHardKeeper() - -func newFakeHardKeeper() *fakeHardKeeper { - return &fakeHardKeeper{ - borrows: newFakeHardState(), - deposits: newFakeHardState(), - } -} - -func (k *fakeHardKeeper) addTotalBorrow(coin sdk.Coin, factor sdk.Dec) *fakeHardKeeper { - k.borrows.total = k.borrows.total.Add(coin) - k.borrows.interestFactors[coin.Denom] = factor - return k -} - -func (k *fakeHardKeeper) addTotalSupply(coin sdk.Coin, factor sdk.Dec) *fakeHardKeeper { - k.deposits.total = k.deposits.total.Add(coin) - k.deposits.interestFactors[coin.Denom] = factor - return k -} - -func (k *fakeHardKeeper) GetBorrowedCoins(_ sdk.Context) (sdk.Coins, bool) { - if k.borrows.total == nil { - return nil, false - } - return k.borrows.total, true -} - -func (k *fakeHardKeeper) GetSuppliedCoins(_ sdk.Context) (sdk.Coins, bool) { - if k.deposits.total == nil { - return nil, false - } - return k.deposits.total, true -} - -func (k *fakeHardKeeper) GetBorrowInterestFactor(_ sdk.Context, denom string) (sdk.Dec, bool) { - f, ok := k.borrows.interestFactors[denom] - return f, ok -} - -func (k *fakeHardKeeper) GetSupplyInterestFactor(_ sdk.Context, denom string) (sdk.Dec, bool) { - f, ok := k.deposits.interestFactors[denom] - return f, ok -} - -func (k *fakeHardKeeper) GetBorrow(_ sdk.Context, _ sdk.AccAddress) (hardtypes.Borrow, bool) { - panic("unimplemented") -} - -func (k *fakeHardKeeper) GetDeposit(_ sdk.Context, _ sdk.AccAddress) (hardtypes.Deposit, bool) { - panic("unimplemented") -} - -// fakeStakingKeeper is a stub staking keeper. -// It can be used to return values to the incentive keeper without having to initialize a full staking keeper. -type fakeStakingKeeper struct { - delegations stakingtypes.Delegations - validators stakingtypes.Validators -} - -var _ types.StakingKeeper = newFakeStakingKeeper() - -func newFakeStakingKeeper() *fakeStakingKeeper { return &fakeStakingKeeper{} } - -func (k *fakeStakingKeeper) addBondedTokens(amount int64) *fakeStakingKeeper { - if len(k.validators) != 0 { - panic("cannot set total bonded if keeper already has validators set") - } - // add a validator with all the tokens - k.validators = append(k.validators, stakingtypes.Validator{ - Status: stakingtypes.Bonded, - Tokens: sdkmath.NewInt(amount), - }) - return k -} - -func (k *fakeStakingKeeper) TotalBondedTokens(_ sdk.Context) sdkmath.Int { - total := sdk.ZeroInt() - for _, val := range k.validators { - if val.GetStatus() == stakingtypes.Bonded { - total = total.Add(val.GetBondedTokens()) - } - } - return total -} - -func (k *fakeStakingKeeper) GetDelegatorDelegations(_ sdk.Context, delegator sdk.AccAddress, maxRetrieve uint16) []stakingtypes.Delegation { - return k.delegations -} - -func (k *fakeStakingKeeper) GetValidator(_ sdk.Context, addr sdk.ValAddress) (stakingtypes.Validator, bool) { - for _, val := range k.validators { - if val.GetOperator().Equals(addr) { - return val, true - } - } - return stakingtypes.Validator{}, false -} - -func (k *fakeStakingKeeper) GetValidatorDelegations(_ sdk.Context, valAddr sdk.ValAddress) []stakingtypes.Delegation { - var delegations stakingtypes.Delegations - for _, d := range k.delegations { - if d.GetValidatorAddr().Equals(valAddr) { - delegations = append(delegations, d) - } - } - return delegations -} - -// fakeCDPKeeper is a stub cdp keeper. -// It can be used to return values to the incentive keeper without having to initialize a full cdp keeper. -type fakeCDPKeeper struct { - interestFactor *sdk.Dec - totalPrincipal sdkmath.Int -} - -var _ types.CdpKeeper = newFakeCDPKeeper() - -func newFakeCDPKeeper() *fakeCDPKeeper { - return &fakeCDPKeeper{ - interestFactor: nil, - totalPrincipal: sdk.ZeroInt(), - } -} - -func (k *fakeCDPKeeper) addInterestFactor(f sdk.Dec) *fakeCDPKeeper { - k.interestFactor = &f - return k -} - -func (k *fakeCDPKeeper) addTotalPrincipal(p sdkmath.Int) *fakeCDPKeeper { - k.totalPrincipal = p - return k -} - -func (k *fakeCDPKeeper) GetInterestFactor(_ sdk.Context, collateralType string) (sdk.Dec, bool) { - if k.interestFactor != nil { - return *k.interestFactor, true - } - return sdk.Dec{}, false -} - -func (k *fakeCDPKeeper) GetTotalPrincipal(_ sdk.Context, collateralType string, principalDenom string) sdkmath.Int { - return k.totalPrincipal -} - -func (k *fakeCDPKeeper) GetCdpByOwnerAndCollateralType(_ sdk.Context, owner sdk.AccAddress, collateralType string) (cdptypes.CDP, bool) { - return cdptypes.CDP{}, false -} - -func (k *fakeCDPKeeper) GetCollateral(_ sdk.Context, collateralType string) (cdptypes.CollateralParam, bool) { - return cdptypes.CollateralParam{}, false -} - -// fakeEarnKeeper is a stub earn keeper. -// It can be used to return values to the incentive keeper without having to initialize a full earn keeper. -type fakeEarnKeeper struct { - vaultShares map[string]earntypes.VaultShare - depositShares map[string]earntypes.VaultShares -} - -var _ types.EarnKeeper = newFakeEarnKeeper() - -func newFakeEarnKeeper() *fakeEarnKeeper { - return &fakeEarnKeeper{ - vaultShares: map[string]earntypes.VaultShare{}, - depositShares: map[string]earntypes.VaultShares{}, - } -} - -func (k *fakeEarnKeeper) addVault(vaultDenom string, shares earntypes.VaultShare) *fakeEarnKeeper { - k.vaultShares[vaultDenom] = shares - return k -} - -func (k *fakeEarnKeeper) addDeposit( - depositor sdk.AccAddress, - shares earntypes.VaultShare, -) *fakeEarnKeeper { - if k.depositShares[depositor.String()] == nil { - k.depositShares[depositor.String()] = earntypes.NewVaultShares() - } - - k.depositShares[depositor.String()] = k.depositShares[depositor.String()].Add(shares) - - return k -} - -func (k *fakeEarnKeeper) GetVaultTotalShares( - ctx sdk.Context, - denom string, -) (shares earntypes.VaultShare, found bool) { - vaultShares, found := k.vaultShares[denom] - return vaultShares, found -} - -func (k *fakeEarnKeeper) GetVaultTotalValue(ctx sdk.Context, denom string) (sdk.Coin, error) { - vaultShares, found := k.vaultShares[denom] - if !found { - return sdk.NewCoin(denom, sdk.ZeroInt()), nil - } - - return sdk.NewCoin(denom, vaultShares.Amount.RoundInt()), nil -} - -func (k *fakeEarnKeeper) GetVaultAccountShares( - ctx sdk.Context, - acc sdk.AccAddress, -) (shares earntypes.VaultShares, found bool) { - accShares, found := k.depositShares[acc.String()] - return accShares, found -} - -func (k *fakeEarnKeeper) IterateVaultRecords( - ctx sdk.Context, - cb func(record earntypes.VaultRecord) (stop bool), -) { - for _, vaultShares := range k.vaultShares { - cb(earntypes.VaultRecord{ - TotalShares: vaultShares, - }) - } -} - -// fakeLiquidKeeper is a stub liquid keeper. -// It can be used to return values to the incentive keeper without having to initialize a full liquid keeper. -type fakeLiquidKeeper struct { - derivatives map[string]sdkmath.Int - lastRewardClaim map[string]time.Time -} - -var _ types.LiquidKeeper = newFakeLiquidKeeper() - -func newFakeLiquidKeeper() *fakeLiquidKeeper { - return &fakeLiquidKeeper{ - derivatives: map[string]sdkmath.Int{}, - lastRewardClaim: map[string]time.Time{}, - } -} - -func (k *fakeLiquidKeeper) addDerivative( - ctx sdk.Context, - denom string, - supply sdkmath.Int, -) *fakeLiquidKeeper { - k.derivatives[denom] = supply - k.lastRewardClaim[denom] = ctx.BlockTime() - return k -} - -func (k *fakeLiquidKeeper) IsDerivativeDenom(ctx sdk.Context, denom string) bool { - return strings.HasPrefix(denom, "bkava-") -} - -func (k *fakeLiquidKeeper) GetAllDerivativeDenoms(ctx sdk.Context) (denoms []string) { - for denom := range k.derivatives { - denoms = append(denoms, denom) - } - - return denoms -} - -func (k *fakeLiquidKeeper) GetTotalDerivativeValue(ctx sdk.Context) (sdk.Coin, error) { - totalSupply := sdk.ZeroInt() - for _, supply := range k.derivatives { - totalSupply = totalSupply.Add(supply) - } - - return sdk.NewCoin("ukava", totalSupply), nil -} - -func (k *fakeLiquidKeeper) GetDerivativeValue(ctx sdk.Context, denom string) (sdk.Coin, error) { - supply, found := k.derivatives[denom] - if !found { - return sdk.NewCoin("ukava", sdk.ZeroInt()), nil - } - - return sdk.NewCoin("ukava", supply), nil -} - -func (k *fakeLiquidKeeper) CollectStakingRewardsByDenom( - ctx sdk.Context, - derivativeDenom string, - destinationModAccount string, -) (sdk.Coins, error) { - amt := k.getRewardAmount(ctx, derivativeDenom) - - return sdk.NewCoins(sdk.NewCoin("ukava", amt)), nil -} - -func (k *fakeLiquidKeeper) getRewardAmount( - ctx sdk.Context, - derivativeDenom string, -) sdkmath.Int { - amt, found := k.derivatives[derivativeDenom] - if !found { - // No error - return sdk.ZeroInt() - } - - lastRewardClaim, found := k.lastRewardClaim[derivativeDenom] - if !found { - panic("last reward claim not found") - } - - duration := int64(ctx.BlockTime().Sub(lastRewardClaim).Seconds()) - if duration <= 0 { - return sdk.ZeroInt() - } - - // Reward amount just set to 10% of the derivative supply per second - return amt.QuoRaw(10).MulRaw(duration) -} - -type fakeDistrKeeper struct { - communityTax sdk.Dec -} - -var _ types.DistrKeeper = newFakeDistrKeeper() - -func newFakeDistrKeeper() *fakeDistrKeeper { - return &fakeDistrKeeper{} -} - -func (k *fakeDistrKeeper) setCommunityTax(percent sdk.Dec) *fakeDistrKeeper { - k.communityTax = percent - return k -} - -func (k *fakeDistrKeeper) GetCommunityTax(ctx sdk.Context) (percent sdk.Dec) { - return k.communityTax -} - -type fakeMintKeeper struct { - minter minttypes.Minter -} - -var _ types.MintKeeper = newFakeMintKeeper() - -func newFakeMintKeeper() *fakeMintKeeper { - return &fakeMintKeeper{} -} - -func (k *fakeMintKeeper) setMinter(minter minttypes.Minter) *fakeMintKeeper { - k.minter = minter - return k -} - -func (k *fakeMintKeeper) GetMinter(ctx sdk.Context) (minter minttypes.Minter) { - return k.minter -} - -type fakePricefeedKeeper struct { - prices map[string]pricefeedtypes.CurrentPrice -} - -var _ types.PricefeedKeeper = newFakePricefeedKeeper() - -func newFakePricefeedKeeper() *fakePricefeedKeeper { - return &fakePricefeedKeeper{ - prices: map[string]pricefeedtypes.CurrentPrice{}, - } -} - -func (k *fakePricefeedKeeper) setPrice(price pricefeedtypes.CurrentPrice) *fakePricefeedKeeper { - k.prices[price.MarketID] = price - return k -} - -func (k *fakePricefeedKeeper) GetCurrentPrice(ctx sdk.Context, marketID string) (pricefeedtypes.CurrentPrice, error) { - price, found := k.prices[marketID] - if !found { - return pricefeedtypes.CurrentPrice{}, fmt.Errorf("price not found for market %s", marketID) - } - - return price, nil -} - -type fakeBankKeeper struct { - supply map[string]sdkmath.Int -} - -var _ types.BankKeeper = newFakeBankKeeper() - -func newFakeBankKeeper() *fakeBankKeeper { - return &fakeBankKeeper{ - supply: map[string]sdkmath.Int{}, - } -} - -func (k *fakeBankKeeper) setSupply(coins ...sdk.Coin) *fakeBankKeeper { - for _, coin := range coins { - k.supply[coin.Denom] = coin.Amount - } - - return k -} - -func (k *fakeBankKeeper) SendCoinsFromModuleToAccount( - ctx sdk.Context, - senderModule string, - recipientAddr sdk.AccAddress, - amt sdk.Coins, -) error { - panic("not implemented") -} - -func (k *fakeBankKeeper) GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins { - panic("not implemented") -} - -func (k *fakeBankKeeper) GetSupply(ctx sdk.Context, denom string) sdk.Coin { - supply, found := k.supply[denom] - if !found { - return sdk.NewCoin(denom, sdk.ZeroInt()) - } - - return sdk.NewCoin(denom, supply) -} - -// Assorted Testing Data - -// note: amino panics when encoding times ≥ the start of year 10000. -var distantFuture = time.Date(9000, 1, 1, 0, 0, 0, 0, time.UTC) - -func arbitraryCoins() sdk.Coins { - return cs(c("btcb", 1)) -} - -func arbitraryAddress() sdk.AccAddress { - _, addresses := app.GeneratePrivKeyAddressPairs(1) - return addresses[0] -} - -func arbitraryValidatorAddress() sdk.ValAddress { - return generateValidatorAddresses(1)[0] -} - -func generateValidatorAddresses(n int) []sdk.ValAddress { - _, addresses := app.GeneratePrivKeyAddressPairs(n) - var valAddresses []sdk.ValAddress - for _, a := range addresses { - valAddresses = append(valAddresses, sdk.ValAddress(a)) - } - return valAddresses -} - -var nonEmptyMultiRewardIndexes = types.MultiRewardIndexes{ - { - CollateralType: "bnb", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - }, - { - CollateralType: "btcb", - RewardIndexes: types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.2"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.4"), - }, - }, - }, -} - -func extractCollateralTypes(indexes types.MultiRewardIndexes) []string { - var denoms []string - for _, ri := range indexes { - denoms = append(denoms, ri.CollateralType) - } - return denoms -} - -func increaseAllRewardFactors(indexes types.MultiRewardIndexes) types.MultiRewardIndexes { - increasedIndexes := make(types.MultiRewardIndexes, len(indexes)) - copy(increasedIndexes, indexes) - - for i := range increasedIndexes { - increasedIndexes[i].RewardIndexes = increaseRewardFactors(increasedIndexes[i].RewardIndexes) - } - return increasedIndexes -} - -func increaseRewardFactors(indexes types.RewardIndexes) types.RewardIndexes { - increasedIndexes := make(types.RewardIndexes, len(indexes)) - copy(increasedIndexes, indexes) - - for i := range increasedIndexes { - increasedIndexes[i].RewardFactor = increasedIndexes[i].RewardFactor.MulInt64(2) - } - return increasedIndexes -} - -func appendUniqueMultiRewardIndex(indexes types.MultiRewardIndexes) types.MultiRewardIndexes { - const uniqueDenom = "uniquedenom" - - for _, mri := range indexes { - if mri.CollateralType == uniqueDenom { - panic(fmt.Sprintf("tried to add unique multi reward index with denom '%s', but denom already existed", uniqueDenom)) - } - } - - return append(indexes, types.NewMultiRewardIndex( - uniqueDenom, - types.RewardIndexes{ - { - CollateralType: "hard", - RewardFactor: d("0.02"), - }, - { - CollateralType: "ukava", - RewardFactor: d("0.04"), - }, - }, - ), - ) -} - -func appendUniqueEmptyMultiRewardIndex(indexes types.MultiRewardIndexes) types.MultiRewardIndexes { - const uniqueDenom = "uniquedenom" - - for _, mri := range indexes { - if mri.CollateralType == uniqueDenom { - panic(fmt.Sprintf("tried to add unique multi reward index with denom '%s', but denom already existed", uniqueDenom)) - } - } - - return append(indexes, types.NewMultiRewardIndex(uniqueDenom, nil)) -} - -func appendUniqueRewardIndexToFirstItem(indexes types.MultiRewardIndexes) types.MultiRewardIndexes { - newIndexes := make(types.MultiRewardIndexes, len(indexes)) - copy(newIndexes, indexes) - - newIndexes[0].RewardIndexes = appendUniqueRewardIndex(newIndexes[0].RewardIndexes) - return newIndexes -} - -func appendUniqueRewardIndex(indexes types.RewardIndexes) types.RewardIndexes { - const uniqueDenom = "uniquereward" - - for _, mri := range indexes { - if mri.CollateralType == uniqueDenom { - panic(fmt.Sprintf("tried to add unique reward index with denom '%s', but denom already existed", uniqueDenom)) - } - } - - return append( - indexes, - types.NewRewardIndex(uniqueDenom, d("0.02")), - ) -} diff --git a/x/incentive/legacy/go.mod b/x/incentive/legacy/go.mod deleted file mode 100644 index e69de29b..00000000 diff --git a/x/incentive/legacy/v0_15/types.go b/x/incentive/legacy/v0_15/types.go deleted file mode 100644 index 58f6f912..00000000 --- a/x/incentive/legacy/v0_15/types.go +++ /dev/null @@ -1,171 +0,0 @@ -package v0_15 - -import ( - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // ModuleName The name that will be used throughout the module - ModuleName = "incentive" -) - -// GenesisState is the state that must be provided at genesis. -type GenesisState struct { - Params Params `json:"params" yaml:"params"` - - USDXRewardState GenesisRewardState `json:"usdx_reward_state" yaml:"usdx_reward_state"` - HardSupplyRewardState GenesisRewardState `json:"hard_supply_reward_state" yaml:"hard_supply_reward_state"` - HardBorrowRewardState GenesisRewardState `json:"hard_borrow_reward_state" yaml:"hard_borrow_reward_state"` - DelegatorRewardState GenesisRewardState `json:"delegator_reward_state" yaml:"delegator_reward_state"` - SwapRewardState GenesisRewardState `json:"swap_reward_state" yaml:"swap_reward_state"` - - USDXMintingClaims USDXMintingClaims `json:"usdx_minting_claims" yaml:"usdx_minting_claims"` - HardLiquidityProviderClaims HardLiquidityProviderClaims `json:"hard_liquidity_provider_claims" yaml:"hard_liquidity_provider_claims"` - DelegatorClaims DelegatorClaims `json:"delegator_claims" yaml:"delegator_claims"` - SwapClaims SwapClaims `json:"swap_claims" yaml:"swap_claims"` -} - -// Params governance parameters for the incentive module -type Params struct { - USDXMintingRewardPeriods RewardPeriods `json:"usdx_minting_reward_periods" yaml:"usdx_minting_reward_periods"` - HardSupplyRewardPeriods MultiRewardPeriods `json:"hard_supply_reward_periods" yaml:"hard_supply_reward_periods"` - HardBorrowRewardPeriods MultiRewardPeriods `json:"hard_borrow_reward_periods" yaml:"hard_borrow_reward_periods"` - DelegatorRewardPeriods MultiRewardPeriods `json:"delegator_reward_periods" yaml:"delegator_reward_periods"` - SwapRewardPeriods MultiRewardPeriods `json:"swap_reward_periods" yaml:"swap_reward_periods"` - ClaimMultipliers MultipliersPerDenom `json:"claim_multipliers" yaml:"claim_multipliers"` - ClaimEnd time.Time `json:"claim_end" yaml:"claim_end"` -} - -// RewardPeriods array of RewardPeriod -type RewardPeriods []RewardPeriod - -// RewardPeriod stores the state of an ongoing reward -type RewardPeriod struct { - Active bool `json:"active" yaml:"active"` - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - Start time.Time `json:"start" yaml:"start"` - End time.Time `json:"end" yaml:"end"` - RewardsPerSecond sdk.Coin `json:"rewards_per_second" yaml:"rewards_per_second"` // per second reward payouts -} - -// GenesisRewardState groups together the global state for a particular reward so it can be exported in genesis. -type GenesisRewardState struct { - AccumulationTimes AccumulationTimes `json:"accumulation_times" yaml:"accumulation_times"` - MultiRewardIndexes MultiRewardIndexes `json:"multi_reward_indexes" yaml:"multi_reward_indexes"` -} - -// AccumulationTimes slice of GenesisAccumulationTime -type AccumulationTimes []AccumulationTime - -// AccumulationTime stores the previous reward distribution time and its corresponding collateral type -type AccumulationTime struct { - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - PreviousAccumulationTime time.Time `json:"previous_accumulation_time" yaml:"previous_accumulation_time"` -} - -// MultiRewardIndexes slice of MultiRewardIndex -type MultiRewardIndexes []MultiRewardIndex - -// MultiRewardIndex stores reward accumulation information on multiple reward types -type MultiRewardIndex struct { - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - RewardIndexes RewardIndexes `json:"reward_indexes" yaml:"reward_indexes"` -} - -// RewardIndexes slice of RewardIndex -type RewardIndexes []RewardIndex - -// RewardIndex stores reward accumulation information -type RewardIndex struct { - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - RewardFactor sdk.Dec `json:"reward_factor" yaml:"reward_factor"` -} - -// USDXMintingClaims slice of USDXMintingClaim -type USDXMintingClaims []USDXMintingClaim - -// USDXMintingClaim is for USDX minting rewards -type USDXMintingClaim struct { - BaseClaim `json:"base_claim" yaml:"base_claim"` - RewardIndexes RewardIndexes `json:"reward_indexes" yaml:"reward_indexes"` -} - -// BaseClaim is a common type shared by all Claims -type BaseClaim struct { - Owner sdk.AccAddress `json:"owner" yaml:"owner"` - Reward sdk.Coin `json:"reward" yaml:"reward"` -} - -// HardLiquidityProviderClaims slice of HardLiquidityProviderClaim -type HardLiquidityProviderClaims []HardLiquidityProviderClaim - -// HardLiquidityProviderClaim stores the hard liquidity provider rewards that can be claimed by owner -type HardLiquidityProviderClaim struct { - BaseMultiClaim `json:"base_claim" yaml:"base_claim"` - SupplyRewardIndexes MultiRewardIndexes `json:"supply_reward_indexes" yaml:"supply_reward_indexes"` - BorrowRewardIndexes MultiRewardIndexes `json:"borrow_reward_indexes" yaml:"borrow_reward_indexes"` -} - -// BaseMultiClaim is a common type shared by all Claims with multiple reward denoms -type BaseMultiClaim struct { - Owner sdk.AccAddress `json:"owner" yaml:"owner"` - Reward sdk.Coins `json:"reward" yaml:"reward"` -} - -// DelegatorClaim slice of DelegatorClaim -type DelegatorClaims []DelegatorClaim - -// DelegatorClaim stores delegation rewards that can be claimed by owner -type DelegatorClaim struct { - BaseMultiClaim `json:"base_claim" yaml:"base_claim"` - RewardIndexes MultiRewardIndexes `json:"reward_indexes" yaml:"reward_indexes"` -} - -// SwapClaims slice of SwapClaim -type SwapClaims []SwapClaim - -// SwapClaim stores the swap rewards that can be claimed by owner -type SwapClaim struct { - BaseMultiClaim `json:"base_claim" yaml:"base_claim"` - RewardIndexes MultiRewardIndexes `json:"reward_indexes" yaml:"reward_indexes"` -} - -// MultiRewardPeriods array of MultiRewardPeriod -type MultiRewardPeriods []MultiRewardPeriod - -// MultiRewardPeriod supports multiple reward types -type MultiRewardPeriod struct { - Active bool `json:"active" yaml:"active"` - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - Start time.Time `json:"start" yaml:"start"` - End time.Time `json:"end" yaml:"end"` - RewardsPerSecond sdk.Coins `json:"rewards_per_second" yaml:"rewards_per_second"` // per second reward payouts -} - -// MultipliersPerDenom is a map of denoms to a set of multipliers -type MultipliersPerDenom []struct { - Denom string `json:"denom" yaml:"denom"` - Multipliers Multipliers `json:"multipliers" yaml:"multipliers"` -} - -// Multipliers is a slice of Multiplier -type Multipliers []Multiplier - -// Multiplier amount the claim rewards get increased by, along with how long the claim rewards are locked -type Multiplier struct { - Name MultiplierName `json:"name" yaml:"name"` - MonthsLockup int64 `json:"months_lockup" yaml:"months_lockup"` - Factor sdk.Dec `json:"factor" yaml:"factor"` -} - -// MultiplierName is the user facing ID for a multiplier. There is a restricted set of possible values. -type MultiplierName string - -// Available reward multipliers names -const ( - Small MultiplierName = "small" - Medium MultiplierName = "medium" - Large MultiplierName = "large" -) diff --git a/x/incentive/legacy/v0_16/migrate.go b/x/incentive/legacy/v0_16/migrate.go deleted file mode 100644 index 5a2534d5..00000000 --- a/x/incentive/legacy/v0_16/migrate.go +++ /dev/null @@ -1,174 +0,0 @@ -package v0_16 - -import ( - v015incentive "github.com/0glabs/0g-chain/x/incentive/legacy/v0_15" - v016incentive "github.com/0glabs/0g-chain/x/incentive/types" -) - -func migrateMultiRewardPerids(oldPeriods v015incentive.MultiRewardPeriods) v016incentive.MultiRewardPeriods { - newPeriods := make(v016incentive.MultiRewardPeriods, len(oldPeriods)) - for i, oldPeriod := range oldPeriods { - newPeriods[i] = v016incentive.MultiRewardPeriod{ - Active: oldPeriod.Active, - CollateralType: oldPeriod.CollateralType, - Start: oldPeriod.Start, - End: oldPeriod.End, - RewardsPerSecond: oldPeriod.RewardsPerSecond, - } - } - return newPeriods -} - -func migrateRewardPeriods(oldPeriods v015incentive.RewardPeriods) v016incentive.RewardPeriods { - newPeriods := make(v016incentive.RewardPeriods, len(oldPeriods)) - for i, oldPeriod := range oldPeriods { - newPeriods[i] = v016incentive.RewardPeriod{ - Active: oldPeriod.Active, - CollateralType: oldPeriod.CollateralType, - Start: oldPeriod.Start, - End: oldPeriod.End, - RewardsPerSecond: oldPeriod.RewardsPerSecond, - } - } - return newPeriods -} - -func migrateMultipliersPerDenom(oldMpds v015incentive.MultipliersPerDenom) []v016incentive.MultipliersPerDenom { - mpds := make([]v016incentive.MultipliersPerDenom, len(oldMpds)) - for i, oldMpd := range oldMpds { - multipliers := make(v016incentive.Multipliers, len(oldMpd.Multipliers)) - for i, multiplier := range oldMpd.Multipliers { - multipliers[i] = v016incentive.Multiplier{ - Name: string(multiplier.Name), - MonthsLockup: multiplier.MonthsLockup, - Factor: multiplier.Factor, - } - } - mpds[i] = v016incentive.MultipliersPerDenom{ - Denom: oldMpd.Denom, - Multipliers: multipliers, - } - } - return mpds -} - -func migrateParams(params v015incentive.Params) v016incentive.Params { - return v016incentive.Params{ - USDXMintingRewardPeriods: migrateRewardPeriods(params.USDXMintingRewardPeriods), - HardSupplyRewardPeriods: migrateMultiRewardPerids(params.HardSupplyRewardPeriods), - HardBorrowRewardPeriods: migrateMultiRewardPerids(params.HardBorrowRewardPeriods), - DelegatorRewardPeriods: migrateMultiRewardPerids(params.DelegatorRewardPeriods), - SwapRewardPeriods: migrateMultiRewardPerids(params.SwapRewardPeriods), - ClaimMultipliers: migrateMultipliersPerDenom(params.ClaimMultipliers), - ClaimEnd: params.ClaimEnd, - } -} - -func migrateRewardState(oldRewardState v015incentive.GenesisRewardState) v016incentive.GenesisRewardState { - allTimes := make(v016incentive.AccumulationTimes, len(oldRewardState.AccumulationTimes)) - for i, at := range oldRewardState.AccumulationTimes { - allTimes[i] = v016incentive.AccumulationTime{ - CollateralType: at.CollateralType, - PreviousAccumulationTime: at.PreviousAccumulationTime, - } - } - return v016incentive.GenesisRewardState{ - AccumulationTimes: allTimes, - MultiRewardIndexes: migrateMultiRewardIndexes(oldRewardState.MultiRewardIndexes), - } -} - -func migrateMultiRewardIndexes(oldMultiRewardIndexes v015incentive.MultiRewardIndexes) v016incentive.MultiRewardIndexes { - multiRewardIndexes := make(v016incentive.MultiRewardIndexes, len(oldMultiRewardIndexes)) - for i, multiRewardIndex := range oldMultiRewardIndexes { - multiRewardIndexes[i] = v016incentive.MultiRewardIndex{ - CollateralType: multiRewardIndex.CollateralType, - RewardIndexes: migrateRewadIndexes(multiRewardIndex.RewardIndexes), - } - } - return multiRewardIndexes -} - -func migrateRewadIndexes(oldRewardIndexes v015incentive.RewardIndexes) v016incentive.RewardIndexes { - rewardIndexes := make(v016incentive.RewardIndexes, len(oldRewardIndexes)) - for j, rewardIndex := range oldRewardIndexes { - rewardIndexes[j] = v016incentive.RewardIndex{ - CollateralType: rewardIndex.CollateralType, - RewardFactor: rewardIndex.RewardFactor, - } - } - return rewardIndexes -} - -func migrateUSDXMintingClaims(oldClaims v015incentive.USDXMintingClaims) v016incentive.USDXMintingClaims { - claims := make(v016incentive.USDXMintingClaims, len(oldClaims)) - for i, oldClaim := range oldClaims { - claims[i] = v016incentive.USDXMintingClaim{ - BaseClaim: v016incentive.BaseClaim{ - Owner: oldClaim.BaseClaim.Owner, - Reward: oldClaim.BaseClaim.Reward, - }, - RewardIndexes: migrateRewadIndexes(oldClaim.RewardIndexes), - } - } - return claims -} - -func migrateHardLiquidityProviderClaims(oldClaims v015incentive.HardLiquidityProviderClaims) v016incentive.HardLiquidityProviderClaims { - claims := make(v016incentive.HardLiquidityProviderClaims, len(oldClaims)) - for i, oldClaim := range oldClaims { - claims[i] = v016incentive.HardLiquidityProviderClaim{ - BaseMultiClaim: v016incentive.BaseMultiClaim{ - Owner: oldClaim.BaseMultiClaim.Owner, - Reward: oldClaim.BaseMultiClaim.Reward, - }, - SupplyRewardIndexes: migrateMultiRewardIndexes(oldClaim.SupplyRewardIndexes), - BorrowRewardIndexes: migrateMultiRewardIndexes(oldClaim.BorrowRewardIndexes), - } - } - return claims -} - -func migrateDelegatorClaims(oldClaims v015incentive.DelegatorClaims) v016incentive.DelegatorClaims { - claims := make(v016incentive.DelegatorClaims, len(oldClaims)) - for i, oldClaim := range oldClaims { - claims[i] = v016incentive.DelegatorClaim{ - BaseMultiClaim: v016incentive.BaseMultiClaim{ - Owner: oldClaim.BaseMultiClaim.Owner, - Reward: oldClaim.BaseMultiClaim.Reward, - }, - RewardIndexes: migrateMultiRewardIndexes(oldClaim.RewardIndexes), - } - } - return claims -} - -func migrateSwapClaims(oldClaims v015incentive.SwapClaims) v016incentive.SwapClaims { - claims := make(v016incentive.SwapClaims, len(oldClaims)) - for i, oldClaim := range oldClaims { - claims[i] = v016incentive.SwapClaim{ - BaseMultiClaim: v016incentive.BaseMultiClaim{ - Owner: oldClaim.BaseMultiClaim.Owner, - Reward: oldClaim.BaseMultiClaim.Reward, - }, - RewardIndexes: migrateMultiRewardIndexes(oldClaim.RewardIndexes), - } - } - return claims -} - -// Migrate converts v0.15 incentive state and returns it in v0.16 format -func Migrate(oldState v015incentive.GenesisState) *v016incentive.GenesisState { - return &v016incentive.GenesisState{ - Params: migrateParams(oldState.Params), - USDXRewardState: migrateRewardState(oldState.USDXRewardState), - HardSupplyRewardState: migrateRewardState(oldState.HardSupplyRewardState), - HardBorrowRewardState: migrateRewardState(oldState.HardBorrowRewardState), - DelegatorRewardState: migrateRewardState(oldState.DelegatorRewardState), - SwapRewardState: migrateRewardState(oldState.SwapRewardState), - USDXMintingClaims: migrateUSDXMintingClaims(oldState.USDXMintingClaims), - HardLiquidityProviderClaims: migrateHardLiquidityProviderClaims(oldState.HardLiquidityProviderClaims), - DelegatorClaims: migrateDelegatorClaims(oldState.DelegatorClaims), - SwapClaims: migrateSwapClaims(oldState.SwapClaims), - } -} diff --git a/x/incentive/legacy/v0_16/migrate_test.go b/x/incentive/legacy/v0_16/migrate_test.go deleted file mode 100644 index 9a002418..00000000 --- a/x/incentive/legacy/v0_16/migrate_test.go +++ /dev/null @@ -1,560 +0,0 @@ -package v0_16 - -import ( - "io/ioutil" - "path/filepath" - "testing" - "time" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - app "github.com/0glabs/0g-chain/app" - v015incentive "github.com/0glabs/0g-chain/x/incentive/legacy/v0_15" - v016incentive "github.com/0glabs/0g-chain/x/incentive/types" -) - -type migrateTestSuite struct { - suite.Suite - - addresses []sdk.AccAddress - cdc codec.Codec - legacyCdc *codec.LegacyAmino -} - -func (s *migrateTestSuite) SetupTest() { - app.SetSDKConfig() - - config := app.MakeEncodingConfig() - s.cdc = config.Marshaler - - legacyCodec := codec.NewLegacyAmino() - s.legacyCdc = legacyCodec - - _, accAddresses := app.GeneratePrivKeyAddressPairs(10) - s.addresses = accAddresses -} - -func (s *migrateTestSuite) TestMigrate_JSON() { - file := filepath.Join("testdata", "v15-incentive.json") - data, err := ioutil.ReadFile(file) - s.Require().NoError(err) - var v15genstate v015incentive.GenesisState - err = s.legacyCdc.UnmarshalJSON(data, &v15genstate) - s.Require().NoError(err) - genstate := Migrate(v15genstate) - actual := s.cdc.MustMarshalJSON(genstate) - - file = filepath.Join("testdata", "v16-incentive.json") - expected, err := ioutil.ReadFile(file) - s.Require().NoError(err) - s.Require().JSONEq(string(expected), string(actual)) -} - -func (s *migrateTestSuite) TestMigrate_GenState() { - v15genstate := v015incentive.GenesisState{ - Params: v015incentive.Params{ - ClaimEnd: time.Date(2020, time.March, 1, 2, 0, 0, 0, time.UTC), - USDXMintingRewardPeriods: []v015incentive.RewardPeriod{ - { - Active: true, - CollateralType: "usdx", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoin("usdx", sdkmath.NewInt(10)), - }, - }, - HardSupplyRewardPeriods: v015incentive.MultiRewardPeriods{ - { - Active: true, - CollateralType: "usdx", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(10))), - }, - }, - HardBorrowRewardPeriods: v015incentive.MultiRewardPeriods{ - { - Active: true, - CollateralType: "bnb", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10))), - }, - }, - DelegatorRewardPeriods: v015incentive.MultiRewardPeriods{ - { - Active: true, - CollateralType: "bnb", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10))), - }, - }, - SwapRewardPeriods: v015incentive.MultiRewardPeriods{ - { - Active: true, - CollateralType: "bnb", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10))), - }, - }, - ClaimMultipliers: v015incentive.MultipliersPerDenom{ - { - Denom: "usdx", - Multipliers: v015incentive.Multipliers{ - { - Name: v015incentive.Small, - MonthsLockup: 6, - Factor: sdk.MustNewDecFromStr("0.5"), - }, - { - Name: v015incentive.Large, - MonthsLockup: 12, - Factor: sdk.MustNewDecFromStr("0.8"), - }, - { - Name: v015incentive.Medium, - MonthsLockup: 9, - Factor: sdk.MustNewDecFromStr("0.7"), - }, - }, - }, - }, - }, - USDXRewardState: v015incentive.GenesisRewardState{ - AccumulationTimes: v015incentive.AccumulationTimes{ - { - CollateralType: "usdx", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v015incentive.MultiRewardIndexes{ - { - CollateralType: "usdx", - RewardIndexes: []v015incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.15"), - }, - }, - }, - }, - }, - USDXMintingClaims: v015incentive.USDXMintingClaims{ - { - BaseClaim: v015incentive.BaseClaim{ - Owner: s.addresses[0], - Reward: sdk.NewCoin("usdx", sdkmath.NewInt(100)), - }, - RewardIndexes: v015incentive.RewardIndexes{ - { - CollateralType: "kava", - RewardFactor: sdk.MustNewDecFromStr("0.5"), - }, - }, - }, - }, - HardSupplyRewardState: v015incentive.GenesisRewardState{ - AccumulationTimes: v015incentive.AccumulationTimes{ - { - CollateralType: "usdx", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v015incentive.MultiRewardIndexes{ - { - CollateralType: "usdx", - RewardIndexes: []v015incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.15"), - }, - }, - }, - }, - }, - HardBorrowRewardState: v015incentive.GenesisRewardState{ - AccumulationTimes: v015incentive.AccumulationTimes{ - { - CollateralType: "hard", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v015incentive.MultiRewardIndexes{ - { - CollateralType: "hard", - RewardIndexes: []v015incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.15"), - }, - }, - }, - }, - }, - DelegatorRewardState: v015incentive.GenesisRewardState{ - AccumulationTimes: v015incentive.AccumulationTimes{ - { - CollateralType: "usdx", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v015incentive.MultiRewardIndexes{ - { - CollateralType: "usdx", - RewardIndexes: []v015incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.15"), - }, - }, - }, - }, - }, - SwapRewardState: v015incentive.GenesisRewardState{ - AccumulationTimes: v015incentive.AccumulationTimes{ - { - CollateralType: "swap", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v015incentive.MultiRewardIndexes{ - { - CollateralType: "swap", - RewardIndexes: []v015incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - }, - HardLiquidityProviderClaims: v015incentive.HardLiquidityProviderClaims{ - { - BaseMultiClaim: v015incentive.BaseMultiClaim{ - Owner: s.addresses[1], - Reward: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100))), - }, - SupplyRewardIndexes: v015incentive.MultiRewardIndexes{ - { - CollateralType: "bnb", - RewardIndexes: []v015incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - BorrowRewardIndexes: v015incentive.MultiRewardIndexes{ - { - CollateralType: "bnb", - RewardIndexes: []v015incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - }, - }, - DelegatorClaims: v015incentive.DelegatorClaims{ - { - BaseMultiClaim: v015incentive.BaseMultiClaim{ - Owner: s.addresses[1], - Reward: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100))), - }, - RewardIndexes: v015incentive.MultiRewardIndexes{ - { - CollateralType: "bnb", - RewardIndexes: []v015incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - }, - }, - SwapClaims: v015incentive.SwapClaims{ - { - BaseMultiClaim: v015incentive.BaseMultiClaim{ - Owner: s.addresses[1], - Reward: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100))), - }, - RewardIndexes: v015incentive.MultiRewardIndexes{ - { - CollateralType: "bnb", - RewardIndexes: []v015incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - }, - }, - } - expected := v016incentive.GenesisState{ - USDXRewardState: v016incentive.GenesisRewardState{ - AccumulationTimes: v016incentive.AccumulationTimes{ - { - CollateralType: "usdx", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v016incentive.MultiRewardIndexes{ - { - CollateralType: "usdx", - RewardIndexes: []v016incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.15"), - }, - }, - }, - }, - }, - Params: v016incentive.Params{ - ClaimEnd: time.Date(2020, time.March, 1, 2, 0, 0, 0, time.UTC), - USDXMintingRewardPeriods: []v016incentive.RewardPeriod{ - { - Active: true, - CollateralType: "usdx", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoin("usdx", sdkmath.NewInt(10)), - }, - }, - HardSupplyRewardPeriods: v016incentive.MultiRewardPeriods{ - { - Active: true, - CollateralType: "usdx", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(10))), - }, - }, - HardBorrowRewardPeriods: v016incentive.MultiRewardPeriods{ - { - Active: true, - CollateralType: "bnb", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10))), - }, - }, - DelegatorRewardPeriods: v016incentive.MultiRewardPeriods{ - { - Active: true, - CollateralType: "bnb", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10))), - }, - }, - SwapRewardPeriods: v016incentive.MultiRewardPeriods{ - { - Active: true, - CollateralType: "bnb", - Start: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2021, time.January, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10))), - }, - }, - ClaimMultipliers: []v016incentive.MultipliersPerDenom{ - { - Denom: "usdx", - Multipliers: v016incentive.Multipliers{ - { - Name: "small", - MonthsLockup: 6, - Factor: sdk.MustNewDecFromStr("0.5"), - }, - { - Name: "large", - MonthsLockup: 12, - Factor: sdk.MustNewDecFromStr("0.8"), - }, - { - Name: "medium", - MonthsLockup: 9, - Factor: sdk.MustNewDecFromStr("0.7"), - }, - }, - }, - }, - }, - USDXMintingClaims: v016incentive.USDXMintingClaims{ - { - BaseClaim: v016incentive.BaseClaim{ - Owner: s.addresses[0], - Reward: sdk.NewCoin("usdx", sdkmath.NewInt(100)), - }, - RewardIndexes: v016incentive.RewardIndexes{ - { - CollateralType: "kava", - RewardFactor: sdk.MustNewDecFromStr("0.5"), - }, - }, - }, - }, - HardSupplyRewardState: v016incentive.GenesisRewardState{ - AccumulationTimes: v016incentive.AccumulationTimes{ - { - CollateralType: "usdx", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v016incentive.MultiRewardIndexes{ - { - CollateralType: "usdx", - RewardIndexes: []v016incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.15"), - }, - }, - }, - }, - }, - HardBorrowRewardState: v016incentive.GenesisRewardState{ - AccumulationTimes: v016incentive.AccumulationTimes{ - { - CollateralType: "hard", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v016incentive.MultiRewardIndexes{ - { - CollateralType: "hard", - RewardIndexes: []v016incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.15"), - }, - }, - }, - }, - }, - DelegatorRewardState: v016incentive.GenesisRewardState{ - AccumulationTimes: v016incentive.AccumulationTimes{ - { - CollateralType: "usdx", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v016incentive.MultiRewardIndexes{ - { - CollateralType: "usdx", - RewardIndexes: []v016incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.15"), - }, - }, - }, - }, - }, - SwapRewardState: v016incentive.GenesisRewardState{ - AccumulationTimes: v016incentive.AccumulationTimes{ - { - CollateralType: "swap", - PreviousAccumulationTime: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC), - }, - }, - MultiRewardIndexes: v016incentive.MultiRewardIndexes{ - { - CollateralType: "swap", - RewardIndexes: []v016incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - }, - HardLiquidityProviderClaims: v016incentive.HardLiquidityProviderClaims{ - { - BaseMultiClaim: v016incentive.BaseMultiClaim{ - Owner: s.addresses[1], - Reward: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100))), - }, - SupplyRewardIndexes: v016incentive.MultiRewardIndexes{ - { - CollateralType: "bnb", - RewardIndexes: []v016incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - BorrowRewardIndexes: v016incentive.MultiRewardIndexes{ - { - CollateralType: "bnb", - RewardIndexes: []v016incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - }, - }, - DelegatorClaims: v016incentive.DelegatorClaims{ - { - BaseMultiClaim: v016incentive.BaseMultiClaim{ - Owner: s.addresses[1], - Reward: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100))), - }, - RewardIndexes: v016incentive.MultiRewardIndexes{ - { - CollateralType: "bnb", - RewardIndexes: []v016incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - }, - }, - SwapClaims: v016incentive.SwapClaims{ - { - BaseMultiClaim: v016incentive.BaseMultiClaim{ - Owner: s.addresses[1], - Reward: sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(100))), - }, - RewardIndexes: v016incentive.MultiRewardIndexes{ - { - CollateralType: "bnb", - RewardIndexes: []v016incentive.RewardIndex{ - { - CollateralType: "bnb", - RewardFactor: sdk.MustNewDecFromStr("0.25"), - }, - }, - }, - }, - }, - }, - } - genState := Migrate(v15genstate) - s.Require().Equal(expected, *genState) -} - -func TestIncentiveMigrateTestSuite(t *testing.T) { - suite.Run(t, new(migrateTestSuite)) -} diff --git a/x/incentive/legacy/v0_16/testdata/v15-incentive.json b/x/incentive/legacy/v0_16/testdata/v15-incentive.json deleted file mode 100644 index baca2819..00000000 --- a/x/incentive/legacy/v0_16/testdata/v15-incentive.json +++ /dev/null @@ -1,400 +0,0 @@ -{ - "params": { - "usdx_minting_reward_periods": [ - { - "active": true, - "rewards_per_second": { - "amount": "122354", - "denom": "ukava" - }, - "collateral_type": "bnb-a", - "start": "2021-07-20T14:00:00Z", - "end": "2024-10-16T14:00:00Z" - }, - { - "active": true, - "rewards_per_second": { - "amount": "23809", - "denom": "ukava" - }, - "collateral_type": "hard-a", - "start": "2021-07-20T14:00:00Z", - "end": "2024-10-16T14:00:00Z" - } - ], - "hard_supply_reward_periods": [ - { - "active": true, - "collateral_type": "bnb", - "start": "2021-07-20T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { - "amount": "123455", - "denom": "hard" - } - ] - }, - { - "active": true, - "collateral_type": "hard", - "start": "2021-07-20T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { - "amount": "123455", - "denom": "hard" - } - ] - } - ], - "hard_borrow_reward_periods": [ - { - "active": true, - "collateral_type": "bnb", - "start": "2020-01-01T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { - "amount": "12345", - "denom": "hard" - } - ] - }, - { - "active": true, - "collateral_type": "btcb", - "start": "2020-01-01T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { - "amount": "12345", - "denom": "hard" - } - ] - } - ], - "delegator_reward_periods": [ - { - "active": true, - "collateral_type": "ukava", - "start": "2020-01-01T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { - "amount": "316880", - "denom": "hard" - }, - { - "amount": "316880", - "denom": "swp" - } - ] - } - ], - "swap_reward_periods": [ - { - "active": true, - "collateral_type": "ukava:usdx", - "start": "2021-07-14T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { - "amount": "316880", - "denom": "swp" - }, - { - "amount": "31688", - "denom": "ukava" - } - ] - }, - { - "active": true, - "collateral_type": "swp:usdx", - "start": "2021-07-14T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { - "amount": "616880", - "denom": "swp" - }, - { - "amount": "31688", - "denom": "ukava" - } - ] - } - ], - "claim_multipliers": [ - { - "denom": "hard", - "multipliers": [ - { - "name": "small", - "months_lockup": "1", - "factor": "0.2" - }, - { - "name": "large", - "months_lockup": "12", - "factor": "1.0" - } - ] - }, - { - "denom": "swp", - "multipliers": [ - { - "name": "small", - "months_lockup": "1", - "factor": "0.1" - }, - { - "name": "large", - "months_lockup": "12", - "factor": "1.0" - } - ] - } - ], - "claim_end": "2025-01-01T00:00:00Z" - }, - "delegator_reward_state": { - "accumulation_times": [ - { - "collateral_type": "ukava", - "previous_accumulation_time": "2021-11-05T21:13:12.85608847Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "ukava", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "0.078380843036861815" - }, - { - "collateral_type": "swp", - "reward_factor": "0.013629025935176301" - } - ] - } - ] - }, - "hard_borrow_reward_state": { - "accumulation_times": [ - { - "collateral_type": "btcb", - "previous_accumulation_time": "2021-11-05T21:13:12.85608847Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "btcb", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "88.582200355378048199" - } - ] - } - ] - }, - "hard_supply_reward_state": { - "accumulation_times": [ - { - "collateral_type": "bnb", - "previous_accumulation_time": "2021-11-05T21:13:12.85608847Z" - }, - { - "collateral_type": "hard", - "previous_accumulation_time": "2021-11-05T21:13:12.85608847Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "bnb", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "32.458112657412585027" - } - ] - }, - { - "collateral_type": "hard", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "35.000000000000000000" - } - ] - } - ] - }, - "swap_reward_state": { - "accumulation_times": [ - { - "collateral_type": "btcb-a", - "previous_accumulation_time": "2021-06-10T16:43:11.679705Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "btcb:usdx", - "reward_indexes": [ - { - "collateral_type": "swp", - "reward_factor": "6.145396761233172901" - } - ] - } - ] - }, - "usdx_reward_state": { - "accumulation_times": [ - { - "collateral_type": "bnb-a", - "previous_accumulation_time": "2021-06-10T16:43:11.679705Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "bnb-a", - "reward_indexes": [ - { - "collateral_type": "ukava", - "reward_factor": "0.043949244534927716" - } - ] - } - ] - }, - "delegator_claims": [ - { - "base_claim": { - "owner": "kava1qqqvdyv8w0xdu7gjdtt598q78gtgqyukct4yz2", - "reward": [] - }, - "reward_indexes": [ - { - "collateral_type": "ukava", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "0.000000000000000000" - }, - { - "collateral_type": "swp", - "reward_factor": "0.000000100000000000" - } - ] - } - ] - } - ], - "hard_liquidity_provider_claims": [ - { - "base_claim": { - "owner": "kava1qqqvdyv8w0xdu7gjdtt598q78gtgqyukct4yz2", - "reward": [ - { - "amount": "1747514", - "denom": "hard" - } - ] - }, - "borrow_reward_indexes": [ - { - "collateral_type": "btc", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "88.582200355378048199" - } - ] - } - ], - "supply_reward_indexes": [ - { - "collateral_type": "bnb", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "22.000000000000000000" - } - ] - }, - { - "collateral_type": "hard", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "30.000000000000000000" - } - ] - } - ] - }, - { - "base_claim": { - "owner": "kava1w2uj6rpejrma47vjx4rcghh3fndhmrvs6pmxph", - "reward": [ - { - "amount": "1747514", - "denom": "hard" - } - ] - }, - "borrow_reward_indexes": [], - "supply_reward_indexes": [] - } - ], - "usdx_minting_claims": [ - { - "base_claim": { - "owner": "kava1qptt5vu26cmxpmv0hf2tnnmf293x266pjcsjar", - "reward": { - "amount": "550", - "denom": "ukava" - } - }, - "reward_indexes": [ - { - "collateral_type": "bnb-a", - "reward_factor": "0.043949244534927716" - }, - { - "collateral_type": "btcb-a", - "reward_factor": "0.046551281526135881" - } - ] - } - ], - "swap_claims": [ - { - "base_claim": { - "owner": "kava1qzease8mre5adak7wcc2twh6ryh9evnxpr6caj", - "reward": [ - { - "amount": "1960368", - "denom": "swp" - } - ] - }, - "reward_indexes": [ - { - "collateral_type": "busd:usdx", - "reward_indexes": [ - { - "collateral_type": "swp", - "reward_factor": "0.018083281889996318" - } - ] - } - ] - } - ] -} diff --git a/x/incentive/legacy/v0_16/testdata/v16-incentive.json b/x/incentive/legacy/v0_16/testdata/v16-incentive.json deleted file mode 100644 index 95da6e01..00000000 --- a/x/incentive/legacy/v0_16/testdata/v16-incentive.json +++ /dev/null @@ -1,337 +0,0 @@ -{ - "params": { - "usdx_minting_reward_periods": [ - { - "active": true, - "collateral_type": "bnb-a", - "start": "2021-07-20T14:00:00Z", - "end": "2024-10-16T14:00:00Z", - "rewards_per_second": { "denom": "ukava", "amount": "122354" } - }, - { - "active": true, - "collateral_type": "hard-a", - "start": "2021-07-20T14:00:00Z", - "end": "2024-10-16T14:00:00Z", - "rewards_per_second": { "denom": "ukava", "amount": "23809" } - } - ], - "hard_supply_reward_periods": [ - { - "active": true, - "collateral_type": "bnb", - "start": "2021-07-20T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [{ "denom": "hard", "amount": "123455" }] - }, - { - "active": true, - "collateral_type": "hard", - "start": "2021-07-20T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [{ "denom": "hard", "amount": "123455" }] - } - ], - "hard_borrow_reward_periods": [ - { - "active": true, - "collateral_type": "bnb", - "start": "2020-01-01T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [{ "denom": "hard", "amount": "12345" }] - }, - { - "active": true, - "collateral_type": "btcb", - "start": "2020-01-01T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [{ "denom": "hard", "amount": "12345" }] - } - ], - "delegator_reward_periods": [ - { - "active": true, - "collateral_type": "ukava", - "start": "2020-01-01T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { "denom": "hard", "amount": "316880" }, - { "denom": "swp", "amount": "316880" } - ] - } - ], - "swap_reward_periods": [ - { - "active": true, - "collateral_type": "ukava:usdx", - "start": "2021-07-14T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { "denom": "swp", "amount": "316880" }, - { "denom": "ukava", "amount": "31688" } - ] - }, - { - "active": true, - "collateral_type": "swp:usdx", - "start": "2021-07-14T00:00:00Z", - "end": "2024-01-01T00:00:00Z", - "rewards_per_second": [ - { "denom": "swp", "amount": "616880" }, - { "denom": "ukava", "amount": "31688" } - ] - } - ], - "savings_reward_periods": [], - "claim_multipliers": [ - { - "denom": "hard", - "multipliers": [ - { - "name": "small", - "months_lockup": "1", - "factor": "0.200000000000000000" - }, - { - "name": "large", - "months_lockup": "12", - "factor": "1.000000000000000000" - } - ] - }, - { - "denom": "swp", - "multipliers": [ - { - "name": "small", - "months_lockup": "1", - "factor": "0.100000000000000000" - }, - { - "name": "large", - "months_lockup": "12", - "factor": "1.000000000000000000" - } - ] - } - ], - "claim_end": "2025-01-01T00:00:00Z" - }, - "usdx_reward_state": { - "accumulation_times": [ - { - "collateral_type": "bnb-a", - "previous_accumulation_time": "2021-06-10T16:43:11.679705Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "bnb-a", - "reward_indexes": [ - { - "collateral_type": "ukava", - "reward_factor": "0.043949244534927716" - } - ] - } - ] - }, - "hard_supply_reward_state": { - "accumulation_times": [ - { - "collateral_type": "bnb", - "previous_accumulation_time": "2021-11-05T21:13:12.856088470Z" - }, - { - "collateral_type": "hard", - "previous_accumulation_time": "2021-11-05T21:13:12.856088470Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "bnb", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "32.458112657412585027" - } - ] - }, - { - "collateral_type": "hard", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "35.000000000000000000" - } - ] - } - ] - }, - "hard_borrow_reward_state": { - "accumulation_times": [ - { - "collateral_type": "btcb", - "previous_accumulation_time": "2021-11-05T21:13:12.856088470Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "btcb", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "88.582200355378048199" - } - ] - } - ] - }, - "delegator_reward_state": { - "accumulation_times": [ - { - "collateral_type": "ukava", - "previous_accumulation_time": "2021-11-05T21:13:12.856088470Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "ukava", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "0.078380843036861815" - }, - { "collateral_type": "swp", "reward_factor": "0.013629025935176301" } - ] - } - ] - }, - "swap_reward_state": { - "accumulation_times": [ - { - "collateral_type": "btcb-a", - "previous_accumulation_time": "2021-06-10T16:43:11.679705Z" - } - ], - "multi_reward_indexes": [ - { - "collateral_type": "btcb:usdx", - "reward_indexes": [ - { "collateral_type": "swp", "reward_factor": "6.145396761233172901" } - ] - } - ] - }, - "savings_reward_state": { - "accumulation_times": [], - "multi_reward_indexes": [] - }, - "usdx_minting_claims": [ - { - "base_claim": { - "owner": "kava1qptt5vu26cmxpmv0hf2tnnmf293x266pjcsjar", - "reward": { "denom": "ukava", "amount": "550" } - }, - "reward_indexes": [ - { "collateral_type": "bnb-a", "reward_factor": "0.043949244534927716" }, - { "collateral_type": "btcb-a", "reward_factor": "0.046551281526135881" } - ] - } - ], - "hard_liquidity_provider_claims": [ - { - "base_claim": { - "owner": "kava1qqqvdyv8w0xdu7gjdtt598q78gtgqyukct4yz2", - "reward": [{ "denom": "hard", "amount": "1747514" }] - }, - "supply_reward_indexes": [ - { - "collateral_type": "bnb", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "22.000000000000000000" - } - ] - }, - { - "collateral_type": "hard", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "30.000000000000000000" - } - ] - } - ], - "borrow_reward_indexes": [ - { - "collateral_type": "btc", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "88.582200355378048199" - } - ] - } - ] - }, - { - "base_claim": { - "owner": "kava1w2uj6rpejrma47vjx4rcghh3fndhmrvs6pmxph", - "reward": [ - { - "amount": "1747514", - "denom": "hard" - } - ] - }, - "borrow_reward_indexes": [], - "supply_reward_indexes": [] - } - ], - "delegator_claims": [ - { - "base_claim": { - "owner": "kava1qqqvdyv8w0xdu7gjdtt598q78gtgqyukct4yz2", - "reward": [] - }, - "reward_indexes": [ - { - "collateral_type": "ukava", - "reward_indexes": [ - { - "collateral_type": "hard", - "reward_factor": "0.000000000000000000" - }, - { - "collateral_type": "swp", - "reward_factor": "0.000000100000000000" - } - ] - } - ] - } - ], - "swap_claims": [ - { - "base_claim": { - "owner": "kava1qzease8mre5adak7wcc2twh6ryh9evnxpr6caj", - "reward": [{ "denom": "swp", "amount": "1960368" }] - }, - "reward_indexes": [ - { - "collateral_type": "busd:usdx", - "reward_indexes": [ - { - "collateral_type": "swp", - "reward_factor": "0.018083281889996318" - } - ] - } - ] - } - ], - "savings_claims": [] -} diff --git a/x/incentive/module.go b/x/incentive/module.go deleted file mode 100644 index 3ef56b5a..00000000 --- a/x/incentive/module.go +++ /dev/null @@ -1,143 +0,0 @@ -package incentive - -import ( - "context" - "encoding/json" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/0glabs/0g-chain/x/incentive/client/cli" - "github.com/0glabs/0g-chain/x/incentive/keeper" - "github.com/0glabs/0g-chain/x/incentive/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic defines the basic application module used by the incentive module. -type AppModuleBasic struct{} - -// Name returns the incentive module's name. -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis returns default genesis state as raw bytes for the incentive -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - gs := types.DefaultGenesisState() - return cdc.MustMarshalJSON(&gs) -} - -// ValidateGenesis performs genesis state validation for the incentive module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - if err := cdc.UnmarshalJSON(bz, &gs); err != nil { - return err - } - return gs.Validate() -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the incentive module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return 1 -} - -// GetTxCmd returns the root tx command for the incentive module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the incentive module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -// AppModule implements the sdk.AppModule interface. -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - cdpKeeper types.CdpKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, ak types.AccountKeeper, bk types.BankKeeper, ck types.CdpKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: ak, - bankKeeper: bk, - cdpKeeper: ck, - } -} - -// Name returns the incentive module's name. -func (AppModule) Name() string { - return types.ModuleName -} - -// RegisterInvariants registers the incentive module invariants. -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) -} - -// InitGenesis performs genesis initialization for the incentive module. It returns no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { - var genState types.GenesisState - // Initialize global index to index in genesis state - cdc.MustUnmarshalJSON(gs, &genState) - - InitGenesis(ctx, am.keeper, am.accountKeeper, am.bankKeeper, am.cdpKeeper, genState) - return []abci.ValidatorUpdate{} -} - -// ExportGenesis returns the exported genesis state as raw bytes for the incentive module -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(&gs) -} - -// BeginBlock returns the begin blocker for the incentive module. -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { - BeginBlocker(ctx, am.keeper) -} - -// EndBlock returns the end blocker for the incentive module. It returns no validator updates. -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/incentive/spec/01_concepts.md b/x/incentive/spec/01_concepts.md deleted file mode 100644 index efc8678c..00000000 --- a/x/incentive/spec/01_concepts.md +++ /dev/null @@ -1,110 +0,0 @@ - - -# Concepts - -This module implements governance controlled user incentives. When users take a certain action, for example opening a CDP, they become eligible for rewards. Rewards are **opt in** meaning that users must submit a message before the claim deadline to claim their rewards. The goals and background of this module were subject of a previous Kava governance proposal, which can be found [here](https://ipfs.io/ipfs/QmSYedssC3nyQacDJmNcREtgmTPyaMx2JX7RNkMdAVkdkr/user-growth-fund-proposal.pdf) - -## General Reward Distribution - -Rewards target various user activity. For example, usdx borrowed from bnb CDPs, btcb supplied to the hard money market, or shares owned in a swap kava/usdx pool. - -Each second, the rewards accumulate at a rate set in the params, eg 100 ukava per second. These are then distributed to all users ratably based on their percentage involvement in the rewarded activity. For example if a user holds 1% of all funds deposited to the kava/usdx swap pool. They will receive 1% of the total rewards each second. - -The quantity tracking a user's involvement is referred to as "source shares". And the total across all users the "total source shares". The quotient then gives their percentage involvement, eg if a user borrowed 10,000 usdx, and there is 100,000 usdx borrowed by all users, then they will get 10% of rewards. - -## Efficiency - -Paying out rewards to every user every block would be slow and lead to long block times. Instead rewards are calculated lazily only when needed. - -First, every block, the amount of rewards to be distributed in that block are divided by the total source shares to get the rewards per share. This is added to a global total (named "global indexes"). This is repeated every block such that the global indexes represents the total rewards a user should be owed per source share if they had held a deposit from when the rewards were created. - -Then, if a user has deposited (say into a CDP) at the very start of the chain (and never changed their deposit), their current reward balance can be calculated at any time $t$ as - -$$ -\texttt{rewards}_ t = \texttt{globalIndexes}_ t \cdot \texttt{sourceShares}_ t -$$ - -If a user modifies their source shares (at say time $t-10$) we can still calculate their total rewards: - -$$ -\texttt{rewards}_ t= \text{rewards accrued up to time t-10} + \text{rewards accrued from time t-10 to time t} -$$ - -$$ -\texttt{rewards}_ t = \texttt{globalIndexes}_ {t-10} \cdot \texttt{sourceShares}_ {t-10} + (\texttt{globalIndexes}_ t - \texttt{globalIndexes}_ {t-10}) \cdot \texttt{sourceShares}_ t -$$ - -This generalizes to any number of source share modifications. - -In code, to avoid storing the entire history of a user's source shares and global index values, rewards are calculated on every source shares change and added to a reward balance: - -$$ -\texttt{rewards}_ t = \texttt{rewardBalance}_ {t -10} + (\texttt{globalIndexes}_ t - \texttt{globalIndexes}_ {t-10}) \cdot \texttt{sourceShares}_ t -$$ - -Old values of $\texttt{rewardBalance}$ and $\texttt{globalIndexes}$ ares stored in a `Claim` object for each user as `rewardBalance` and `rewardIndexes` respectively. - -Listeners on external modules fire to update these values when source shares change. For example, when a user deposits to hard, a method in incentive is called. This fundamental operation is called "sync". It calculates the rewards accrued since last time the `sourceShares` changed, adds it to the claim, and stores the current `globalIndexes` in the `rewardIndexes`. Sync must be called whenever source shares change, otherwise incorrect rewards will be distributed. - -Enumeration of 'sync' input states: -- `sourceShares`, `globalIndexes`, or `rewardIndexes` should never be negative -- `globalIndexes` >= `rewardIndexes` (global indexes must never decrease) -- `globalIndexes` and `rewardIndexes` can be positive or 0, where not existing in the store is counted as 0 - -- `sourceShares` are the value before the update (eg before a hard deposit) - - | `globalIndexes` | `rewardIndexes` | `sourceShares` | description | - |------------------|-----------------|-----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| - | positive | positive | positive | normal sync | - | positive | positive | 0 | normal (can happen when a user is creating a deposit (so shares are increasing from 0)) | - | positive | 0 | positive | The claim doesn't hold indexes, so the global indexes must have been added since last sync (eg a new denom was added to reward params). This is indistinguishable from a claim accidentally being deleted, where it will accrue a large amount of rewards. | - | positive | 0 | 0 | User is creating source shares. | - | 0 | positive | positive | global indexes < claim indexes - fatal error, otherwise the new rewards will be negative | - | 0 | positive | 0 | global indexes < claim indexes - fatal error | - | 0 | 0 | positive | Source has no rewards yet. User is updating their shares. | - | 0 | 0 | 0 | Source has no rewards yet. User is creating source shares. | - -It is important that: -- claim indexes are not deleted - - Otherwise when sync is called, it will fill them in with 0 values and perform sync as if the user had deposit since the beginning of the rewards (usually accumulating a lot of rewards). -- global indexes are not deleted - - Otherwise claims cannot be synced. Problematic if a sync happens in a begin blocker and it panics. -- hooks are called any time source shares change - - If source shares can be updated without a sync, it can be possible to accumulate far too much rewards. For example, a user who holds a small deposit for a long time could deposit a large amount and skip the sync, then trigger a sync which will calculate rewards as if the large deposit was there for a long time. - -The code is further complicated by: -- Claim objects contain indexes for several source shares. -- Rewards for hard borrows and hard deposits use the same claim object. -- Savings and hard hooks trigger any time one in a group of source shares change, but don't identify which changed. -- The hard `BeforeXModified` hooks don't show source shares that have increased from zero (eg when a new denom is deposited to an existing deposit). So there is an additional `AfterXModified` hook, and the claim indexes double up as a copy of the borrow/deposit denoms. -- The sync operation is split between two methods to try to protect against indexes being deleted. - - `InitXRewards` performs a sync assuming source shares are 0, it mostly fires in cases where `sourceShares` = 0 above (except for hard and supply) - - `SyncXRewards` performs a sync, but skips it if `globalIndexes` are not found or `rewardIndexes` are not found (only when claim object not found) -- Usdx rewards do not support multiple reward denoms. - -## HARD Token distribution - -The incentive module also distributes the HARD token on the Kava blockchain. HARD tokens are distributed to two types of ecosystem participants: - -1. Kava stakers - any address that stakes (delegates) KAVA tokens will be eligible to claim HARD tokens. For each delegator, HARD tokens are accumulated ratably based on the total number of kava tokens staked. For example, if a user stakes 1 million KAVA tokens and there are 100 million staked KAVA, that user will accumulate 1% of HARD tokens earmarked for stakers during the distribution period. Distribution periods are defined by a start date, an end date, and a number of HARD tokens that are distributed per second. -2. Depositors/Borrows - any address that deposits and/or borrows eligible tokens to the hard module will be eligible to claim HARD tokens. For each depositor, HARD tokens are accumulated ratably based on the total number of tokens staked of that denomination. For example, if a user deposits 1 million "xyz" tokens and there are 100 million xyz deposited, that user will accumulate 1% of HARD tokens earmarked for depositors of that denomination during the distribution period. Distribution periods are defined by a start date, an end date, and a number of HARD tokens that are distributed per second. - -Users are not air-dropped tokens, rather they accumulate `Claim` objects that they may submit a transaction in order to claim. In order to better align long term incentives, when users claim HARD tokens, they have options, called 'multipliers', for how tokens are distributed. - -The exact multipliers will be voted by governance and can be changed via a governance vote. An example multiplier schedule would be: - -- Short-term locked - 20% multiplier and 1 month transfer restriction. Users receive 20% as many tokens as users who choose long-term locked tokens. -- Long-term locked - 100% multiplier and 1 year transfer restriction. Users receive 5x as many tokens as users who choose short-term locked tokens. - -## USDX Minting Rewards - -The incentive module is responsible for distribution of KAVA tokens to users who mint USDX. When governance adds a collateral type to be eligible for rewards, they set the rate (coins/second) at which rewards are given to users, the length of each reward period, the length of each claim period, and the amount of time reward coins must vest before users who claim them can transfer them. For the duration of a reward period, any user that has minted USDX using an eligible collateral type will ratably accumulate rewards in a `USDXMintingClaim` object. For example, if a user has minted 10% of all USDX for the duration of the reward period, they will earn 10% of all rewards for that period. When the reward period ends, the claim period begins immediately, at which point users can submit a message to claim their rewards. Rewards are time-locked, meaning that when a user claims rewards they will receive them as a vesting balance on their account. Vesting balances can be used to stake coins, but cannot be transferred until the vesting period ends. In addition to vesting, rewards can have multipliers that vary the number of tokens received. For example, a reward with a vesting period of 1 month may have a multiplier of 0.25, meaning that the user will receive 25% of the reward balance if they choose that vesting schedule. - -## SWP Token Distribution - -The incentive module distributes the SWP token on the Kava blockchain. SWP tokens are distributed to two types of ecosystem participants: - -1. Kava stakers - any address that stakes (delegates) KAVA tokens will be eligible to claim SWP tokens. For each delegator, SWP tokens are accumulated ratably based on the total number of kava tokens staked. For example, if a user stakes 1 million KAVA tokens and there are 100 million staked KAVA, that user will accumulate 1% of SWP tokens earmarked for stakers during the distribution period. Distribution periods are defined by a start date, an end date, and a number of SWP tokens that are distributed per second. -2. Liquidity providers - any address that provides liquidity to eligible Swap protocol pools will be eligible to claim SWP tokens. For each liquidity provider, SWP tokens are accumulated ratably based on the total amount of pool shares. For example, if a liquidity provider deposits "xyz" and "abc" tokens into the "abc:xyz" pool to receive 10 shares and the pool has 50 total shares, then that user will accumulate 20% of SWP tokens earmarked for liquidity providers of that pool during the distribution period. Distribution periods are defined by a start date, an end date, and a number of SWP tokens that are distributed per second. diff --git a/x/incentive/spec/02_state.md b/x/incentive/spec/02_state.md deleted file mode 100644 index d76bfd9d..00000000 --- a/x/incentive/spec/02_state.md +++ /dev/null @@ -1,141 +0,0 @@ - - -# State - -## Parameters and Genesis State - -`Parameters` define the types of incentives that are available and the rewards that are available for each incentive. - -```go -// Params governance parameters for the incentive module -type Params struct { - USDXMintingRewardPeriods RewardPeriods `json:"usdx_minting_reward_periods" yaml:"usdx_minting_reward_periods"` - HardSupplyRewardPeriods MultiRewardPeriods `json:"hard_supply_reward_periods" yaml:"hard_supply_reward_periods"` - HardBorrowRewardPeriods MultiRewardPeriods `json:"hard_borrow_reward_periods" yaml:"hard_borrow_reward_periods"` - DelegatorRewardPeriods MultiRewardPeriods `json:"delegator_reward_periods" yaml:"delegator_reward_periods"` - SwapRewardPeriods MultiRewardPeriods `json:"swap_reward_periods" yaml:"swap_reward_periods"` - ClaimMultipliers Multipliers `json:"claim_multipliers" yaml:"claim_multipliers"` - ClaimEnd time.Time `json:"claim_end" yaml:"claim_end"` -} - -``` - -Each `RewardPeriod` defines a particular collateral for which rewards are eligible and the amount of rewards available. - -```go -// RewardPeriod stores the state of an ongoing reward -type RewardPeriod struct { - Active bool `json:"active" yaml:"active"` // if the reward is active - CollateralType string `json:"collateral_type" yaml:"collateral_type"` // the collateral type for which rewards apply - Start time.Time `json:"start" yaml:"start"` // when the rewards start - End time.Time `json:"end" yaml:"end"` // when the rewards end - RewardsPerSecond sdk.Coin `json:"rewards_per_second" yaml:"rewards_per_second"` // per second reward payouts -} -``` - -Each `MultiRewardPeriod` defines a particular collateral for which one or more reward tokens are eligible and the amount of rewards available - -```go -// MultiRewardPeriod supports multiple reward types -type MultiRewardPeriod struct { - Active bool `json:"active" yaml:"active"` - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - Start time.Time `json:"start" yaml:"start"` - End time.Time `json:"end" yaml:"end"` - RewardsPerSecond sdk.Coins `json:"rewards_per_second" yaml:"rewards_per_second"` // per second reward payouts -} -``` - -`GenesisState` defines the state that must be persisted when the blockchain stops/restarts in order for normal function of the incentive module to resume. - -```go -// GenesisState is the state that must be provided at genesis. -type GenesisState struct { - Params Params `json:"params" yaml:"params"` - - USDXRewardState GenesisRewardState `json:"usdx_reward_state" yaml:"usdx_reward_state"` - HardSupplyRewardState GenesisRewardState `json:"hard_supply_reward_state" yaml:"hard_supply_reward_state"` - HardBorrowRewardState GenesisRewardState `json:"hard_borrow_reward_state" yaml:"hard_borrow_reward_state"` - DelegatorRewardState GenesisRewardState `json:"delegator_reward_state" yaml:"delegator_reward_state"` - SwapRewardState GenesisRewardState `json:"swap_reward_state" yaml:"swap_reward_state"` - - USDXMintingClaims USDXMintingClaims `json:"usdx_minting_claims" yaml:"usdx_minting_claims"` - HardLiquidityProviderClaims HardLiquidityProviderClaims `json:"hard_liquidity_provider_claims" yaml:"hard_liquidity_provider_claims"` - DelegatorClaims DelegatorClaims `json:"delegator_claims" yaml:"delegator_claims"` - SwapClaims SwapClaims `json:"swap_claims" yaml:"swap_claims"` -} -``` - -## Store - -For complete details for how items are stored, see [keys.go](../types/keys.go). - -### Claim Creation - -When users take incentivized actions, the `incentive` module will create or update a `Claim` object in the store, which represents the amount of rewards that the user is eligible to claim. Each `Claim` object contains one or several RewardIndexes, which are used to calculate the amount of rewards a user can claim. There are four defined claim objects: - -- `USDXMintingClaim` -- `HardLiquidityProviderClaim` -- `DelegatorClaim` -- `SwapClaim` - -```go - -// Claim is an interface for handling common claim actions -type Claim interface { - GetOwner() sdk.AccAddress - GetReward() sdk.Coin - GetType() string -} - -// BaseClaim is a common type shared by all Claims -type BaseClaim struct { - Owner sdk.AccAddress `json:"owner" yaml:"owner"` - Reward sdk.Coin `json:"reward" yaml:"reward"` -} - -// BaseMultiClaim is a common type shared by all Claims with multiple reward denoms -type BaseMultiClaim struct { - Owner sdk.AccAddress `json:"owner" yaml:"owner"` - Reward sdk.Coins `json:"reward" yaml:"reward"` -} - -// RewardIndex stores reward accumulation information -type RewardIndex struct { - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - RewardFactor sdk.Dec `json:"reward_factor" yaml:"reward_factor"` -} - -// MultiRewardIndex stores reward accumulation information on multiple reward types -type MultiRewardIndex struct { - CollateralType string `json:"collateral_type" yaml:"collateral_type"` - RewardIndexes RewardIndexes `json:"reward_indexes" yaml:"reward_indexes"` -} - -// USDXMintingClaim is for USDX minting rewards -type USDXMintingClaim struct { - BaseClaim `json:"base_claim" yaml:"base_claim"` - RewardIndexes RewardIndexes `json:"reward_indexes" yaml:"reward_indexes"` -} - -// HardLiquidityProviderClaim stores the hard liquidity provider rewards that can be claimed by owner -type HardLiquidityProviderClaim struct { - BaseMultiClaim `json:"base_claim" yaml:"base_claim"` - SupplyRewardIndexes MultiRewardIndexes `json:"supply_reward_indexes" yaml:"supply_reward_indexes"` - BorrowRewardIndexes MultiRewardIndexes `json:"borrow_reward_indexes" yaml:"borrow_reward_indexes"` -} - -// DelegatorClaim stores delegation rewards that can be claimed by owner -type DelegatorClaim struct { - BaseMultiClaim `json:"base_claim" yaml:"base_claim"` - RewardIndexes MultiRewardIndexes `json:"reward_indexes" yaml:"reward_indexes"` -} - -// SwapClaim stores the swap rewards that can be claimed by owner -type SwapClaim struct { - BaseMultiClaim `json:"base_claim" yaml:"base_claim"` - RewardIndexes MultiRewardIndexes `json:"reward_indexes" yaml:"reward_indexes"` -} -``` diff --git a/x/incentive/spec/03_messages.md b/x/incentive/spec/03_messages.md deleted file mode 100644 index 8cc3a4da..00000000 --- a/x/incentive/spec/03_messages.md +++ /dev/null @@ -1,42 +0,0 @@ - - -# Messages - -Users claim rewards using messages that correspond to each claim type. - -```go -// MsgClaimUSDXMintingReward message type used to claim USDX minting rewards -type MsgClaimUSDXMintingReward struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - MultiplierName string `json:"multiplier_name" yaml:"multiplier_name"` -} - -// MsgClaimHardReward message type used to claim Hard liquidity provider rewards -type MsgClaimHardReward struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - MultiplierName string `json:"multiplier_name" yaml:"multiplier_name"` - DenomsToClaim []string `json:"denoms_to_claim" yaml:"denoms_to_claim"` -} - -// MsgClaimDelegatorReward message type used to claim delegator rewards -type MsgClaimDelegatorReward struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - MultiplierName string `json:"multiplier_name" yaml:"multiplier_name"` - DenomsToClaim []string `json:"denoms_to_claim" yaml:"denoms_to_claim"` -} - -// MsgClaimSwapReward message type used to claim delegator rewards -type MsgClaimSwapReward struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - MultiplierName string `json:"multiplier_name" yaml:"multiplier_name"` - DenomsToClaim []string `json:"denoms_to_claim" yaml:"denoms_to_claim"` -} -``` - -## State Modifications - -- Accumulated rewards for active claims are transferred from the `kavadist` module account to the users account as vesting coins -- The number of coins transferred is determined by the multiplier in the message. For example, the multiplier equals 1.0, 100% of the claim's reward value is transferred. If the multiplier equals 0.5, 50% of the claim's reward value is transferred. -- The corresponding claim object is reset to zero in the store diff --git a/x/incentive/spec/04_events.md b/x/incentive/spec/04_events.md deleted file mode 100644 index 8901b93d..00000000 --- a/x/incentive/spec/04_events.md +++ /dev/null @@ -1,17 +0,0 @@ - - -# Events - -The `x/incentive` module emits the following events: - -## ClaimReward - -| Type | Attribute Key | Attribute Value | -| ------------ | ------------- | -------------------- | -| claim_reward | claimed_by | `{claiming address}' | -| claim_reward | claim_amount | `{amount claimed}' | -| claim_reward | claim_type | `{amount claimed}' | -| message | module | incentive | -| message | sender | claim_reward | diff --git a/x/incentive/spec/05_params.md b/x/incentive/spec/05_params.md deleted file mode 100644 index f9debed4..00000000 --- a/x/incentive/spec/05_params.md +++ /dev/null @@ -1,45 +0,0 @@ - - -# Parameters - -The incentive module contains the following parameters: - -| Key | Type | Example | Description | -| ------------------------ | ------------------ | ---------------------- | -------------------------------------------- | -| USDXMintingRewardPeriods | RewardPeriods | [{see below}] | USDX minting reward periods | -| HardSupplyRewardPeriods | MultiRewardPeriods | [{see below}] | Hard supply reward periods | -| HardBorrowRewardPeriods | MultiRewardPeriods | [{see below}] | Hard borrow reward periods | -| DelegatorRewardPeriods | MultiRewardPeriods | [{see below}] | Delegator reward periods | -| SwapRewardPeriods | MultiRewardPeriods | [{see below}] | Swap reward periods | -| ClaimMultipliers | Multipliers | [{see below}] | Multipliers applied when rewards are claimed | -| ClaimMultipliers | Time | "2025-12-02T14:00:00Z" | Time when reward claiming ends | - -Each `RewardPeriod` has the following parameters - -| Key | Type | Example | Description | -| ---------------- | ------------- | ---------------------------------- | ----------------------------------------------------- | -| Active | bool | "true | boolean for if rewards for this collateral are active | -| CollateralType | string | "bnb-a" | the collateral for which rewards are eligible | -| Start | Time | "2020-12-02T14:00:00Z" | the time at which rewards start | -| End | Time | "2023-12-02T14:00:00Z" | the time at which rewards end | -| AvailableRewards | object (coin) | `{"denom":"hard","amount":"1000"}` | the rewards available per reward period | - -Each `MultiRewardPeriod` has the following parameters - -| Key | Type | Example | Description | -| ---------------- | ------------- | ----------------------------------------------------------------------- | ----------------------------------------------------- | -| Active | bool | "true | boolean for if rewards for this collateral are active | -| CollateralType | string | "bnb-a" | the collateral for which rewards are eligible | -| Start | Time | "2020-12-02T14:00:00Z" | the time at which rewards start | -| End | Time | "2023-12-02T14:00:00Z" | the time at which rewards end | -| AvailableRewards | array (coins) | `[{"denom":"hard","amount":"1000"}, {"denom":"ukava","amount":"1000"}]` | the rewards available per reward period | - -Each `Multiplier` has the following parameters: - -| Key | Type | Example | Description | -| ------------ | ------ | ------- | ---------------------------------------------------------- | -| Name | string | "large" | the unique name of the reward multiplier | -| MonthsLockup | int | "6" | number of months tokens with this multiplier are locked | -| Factor | Dec | "0.5" | the scaling factor for tokens claimed with this multiplier | diff --git a/x/incentive/spec/06_hooks.md b/x/incentive/spec/06_hooks.md deleted file mode 100644 index b532fa33..00000000 --- a/x/incentive/spec/06_hooks.md +++ /dev/null @@ -1,127 +0,0 @@ - - -# Hooks - -This module implements the `Hooks` interface for the following modules: - -- cdp -- hard -- swap -- staking (defined in cosmos-sdk) - -CDP module hooks manage the creation and synchronization of USDX minting incentives. - -```go -// ------------------- Cdp Module Hooks ------------------- - -// AfterCDPCreated function that runs after a cdp is created -func (h Hooks) AfterCDPCreated(ctx sdk.Context, cdp cdptypes.CDP) { - h.k.InitializeUSDXMintingClaim(ctx, cdp) -} - -// BeforeCDPModified function that runs before a cdp is modified -// note that this is called immediately after interest is synchronized, and so could potentially -// be called AfterCDPInterestUpdated or something like that, if we we're to expand the scope of cdp hooks -func (h Hooks) BeforeCDPModified(ctx sdk.Context, cdp cdptypes.CDP) { - h.k.SynchronizeUSDXMintingReward(ctx, cdp) -} -``` - -Hard module hooks manage the creation and synchronization of hard supply and borrow rewards. - -```go -// ------------------- Hard Module Hooks ------------------- - -// AfterDepositCreated function that runs after a deposit is created -func (h Hooks) AfterDepositCreated(ctx sdk.Context, deposit hardtypes.Deposit) { - h.k.InitializeHardSupplyReward(ctx, deposit) -} - -// BeforeDepositModified function that runs before a deposit is modified -func (h Hooks) BeforeDepositModified(ctx sdk.Context, deposit hardtypes.Deposit) { - h.k.SynchronizeHardSupplyReward(ctx, deposit) -} - -// AfterDepositModified function that runs after a deposit is modified -func (h Hooks) AfterDepositModified(ctx sdk.Context, deposit hardtypes.Deposit) { - h.k.UpdateHardSupplyIndexDenoms(ctx, deposit) -} - -// AfterBorrowCreated function that runs after a borrow is created -func (h Hooks) AfterBorrowCreated(ctx sdk.Context, borrow hardtypes.Borrow) { - h.k.InitializeHardBorrowReward(ctx, borrow) -} - -// BeforeBorrowModified function that runs before a borrow is modified -func (h Hooks) BeforeBorrowModified(ctx sdk.Context, borrow hardtypes.Borrow) { - h.k.SynchronizeHardBorrowReward(ctx, borrow) -} - -// AfterBorrowModified function that runs after a borrow is modified -func (h Hooks) AfterBorrowModified(ctx sdk.Context, borrow hardtypes.Borrow) { - h.k.UpdateHardBorrowIndexDenoms(ctx, borrow) -} -``` - -Staking module hooks manage the creation and synchronization of hard delegator rewards. - -```go -// ------------------- Staking Module Hooks ------------------- - -// BeforeDelegationCreated runs before a delegation is created -func (h Hooks) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - h.k.InitializeHardDelegatorReward(ctx, delAddr) -} - -// BeforeDelegationSharesModified runs before an existing delegation is modified -func (h Hooks) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { - h.k.SynchronizeHardDelegatorRewards(ctx, delAddr) -} - -// NOTE: following hooks are just implemented to ensure StakingHooks interface compliance - -// BeforeValidatorSlashed is called before a validator is slashed -func (h Hooks) BeforeValidatorSlashed(ctx sdk.Context, valAddr sdk.ValAddress, fraction sdk.Dec) {} - -// AfterValidatorBeginUnbonding is called after a validator begins unbonding -func (h Hooks) AfterValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { -} - -// AfterValidatorBonded is called after a validator is bonded -func (h Hooks) AfterValidatorBonded(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { -} - -// AfterDelegationModified runs after a delegation is modified -func (h Hooks) AfterDelegationModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { -} - -// BeforeDelegationRemoved runs directly before a delegation is deleted -func (h Hooks) BeforeDelegationRemoved(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) { -} - -// AfterValidatorCreated runs after a validator is created -func (h Hooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) {} - -// BeforeValidatorModified runs before a validator is modified -func (h Hooks) BeforeValidatorModified(ctx sdk.Context, valAddr sdk.ValAddress) {} - -// AfterValidatorRemoved runs after a validator is removed -func (h Hooks) AfterValidatorRemoved(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) { -} -``` - -Swap module hooks manage the creation and synchronization of Swap protocol liquidity provider rewards. - -```go -// ------------------- Swap Module Hooks ------------------- - -func (h Hooks) AfterPoolDepositCreated(ctx sdk.Context, poolID string, depositor sdk.AccAddress, _ sdkmath.Int) { - h.k.InitializeSwapReward(ctx, poolID, depositor) -} - -func (h Hooks) BeforePoolDepositModified(ctx sdk.Context, poolID string, depositor sdk.AccAddress, sharesOwned sdkmath.Int) { - h.k.SynchronizeSwapReward(ctx, poolID, depositor, sharesOwned) -} -``` diff --git a/x/incentive/spec/07_begin_block.md b/x/incentive/spec/07_begin_block.md deleted file mode 100644 index b66af81b..00000000 --- a/x/incentive/spec/07_begin_block.md +++ /dev/null @@ -1,31 +0,0 @@ - - -# Begin Block - -At the start of each block, rewards are accumulated for each reward time. Accumulation refers to computing the total amount of rewards that have accumulated since the previous block and updating a global accumulator value such that whenever a `Claim` object is accessed, it is synchronized with the latest global state. This ensures that all rewards are accurately accounted for without having to iterate over each claim object in the begin blocker. - -```go -// BeginBlocker runs at the start of every block -func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { - - params := k.GetParams(ctx) - - for _, rp := range params.USDXMintingRewardPeriods { - k.AccumulateUSDXMintingRewards(ctx, rp) - } - for _, rp := range params.HardSupplyRewardPeriods { - k.AccumulateHardSupplyRewards(ctx, rp) - } - for _, rp := range params.HardBorrowRewardPeriods { - k.AccumulateHardBorrowRewards(ctx, rp) - } - for _, rp := range params.DelegatorRewardPeriods { - k.AccumulateDelegatorRewards(ctx, rp) - } - for _, rp := range params.SwapRewardPeriods { - k.AccumulateSwapRewards(ctx, rp) - } -} -``` diff --git a/x/incentive/spec/README.md b/x/incentive/spec/README.md deleted file mode 100644 index 0c1a5bb2..00000000 --- a/x/incentive/spec/README.md +++ /dev/null @@ -1,25 +0,0 @@ - - -# `incentive` - - -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** -5. **[Params](05_params.md)** -6. **[Hooks](06_hooks.md)** -7. **[BeginBlock](07_begin_block.md)** - -## Abstract - -`x/incentive` is an implementation of a Cosmos SDK Module that allows for governance controlled user incentives for users who take certain actions, such as opening a collateralized debt position (CDP). Governance proposes an array of rewards, with each item representing a collateral type that will be eligible for rewards. Each collateral reward specifies the number of coins awarded per second, the length of rewards periods. Governance can alter the collateral rewards using parameter change proposals as well as adding or removing collateral types. All changes to parameters would take place in the _next_ period. User rewards are __opt in__, ie. users must claim rewards in order to receive them. If users fail to claim rewards before the claim period expiry, they are no longer eligible for rewards. - -### Dependencies - -This module uses hooks to update user rewards. Currently, `incentive` implements hooks from the `cdp`, `hard`, `swap`, and `staking` (comsos-sdk) modules. All rewards are paid out from the `kavadist` module account. diff --git a/x/incentive/testutil/builder.go b/x/incentive/testutil/builder.go deleted file mode 100644 index 97484201..00000000 --- a/x/incentive/testutil/builder.go +++ /dev/null @@ -1,343 +0,0 @@ -package testutil - -import ( - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/app" - hardtypes "github.com/0glabs/0g-chain/x/hard/types" - "github.com/0glabs/0g-chain/x/incentive/types" - savingstypes "github.com/0glabs/0g-chain/x/savings/types" -) - -const ( - oneYear time.Duration = time.Hour * 24 * 365 -) - -type GenesisBuilder interface { - BuildMarshalled(cdc codec.JSONCodec) app.GenesisState -} - -// IncentiveGenesisBuilder is a tool for creating an incentive genesis state. -// Helper methods add values onto a default genesis state. -// All methods are immutable and return updated copies of the builder. -type IncentiveGenesisBuilder struct { - types.GenesisState - genesisTime time.Time -} - -func NewIncentiveGenesisBuilder() IncentiveGenesisBuilder { - return IncentiveGenesisBuilder{ - GenesisState: types.DefaultGenesisState(), - genesisTime: time.Time{}, - } -} - -func (builder IncentiveGenesisBuilder) Build() types.GenesisState { - return builder.GenesisState -} - -func (builder IncentiveGenesisBuilder) BuildMarshalled(cdc codec.JSONCodec) app.GenesisState { - built := builder.Build() - - return app.GenesisState{ - types.ModuleName: cdc.MustMarshalJSON(&built), - } -} - -func (builder IncentiveGenesisBuilder) WithGenesisTime(time time.Time) IncentiveGenesisBuilder { - builder.genesisTime = time - builder.Params.ClaimEnd = time.Add(5 * oneYear) - return builder -} - -// WithInitializedBorrowRewardPeriod sets the genesis time as the previous accumulation time for the specified period. -// This can be helpful in tests. With no prev time set, the first block accrues no rewards as it just sets the prev time to the current. -func (builder IncentiveGenesisBuilder) WithInitializedBorrowRewardPeriod(period types.MultiRewardPeriod) IncentiveGenesisBuilder { - builder.Params.HardBorrowRewardPeriods = append(builder.Params.HardBorrowRewardPeriods, period) - - accumulationTimeForPeriod := types.NewAccumulationTime(period.CollateralType, builder.genesisTime) - builder.HardBorrowRewardState.AccumulationTimes = append( - builder.HardBorrowRewardState.AccumulationTimes, - accumulationTimeForPeriod, - ) - - // TODO remove to better reflect real states - builder.HardBorrowRewardState.MultiRewardIndexes = builder.HardBorrowRewardState.MultiRewardIndexes.With( - period.CollateralType, - newZeroRewardIndexesFromCoins(period.RewardsPerSecond...), - ) - - return builder -} - -func (builder IncentiveGenesisBuilder) WithSimpleBorrowRewardPeriod(ctype string, rewardsPerSecond sdk.Coins) IncentiveGenesisBuilder { - return builder.WithInitializedBorrowRewardPeriod(builder.simpleRewardPeriod(ctype, rewardsPerSecond)) -} - -// WithInitializedSupplyRewardPeriod sets the genesis time as the previous accumulation time for the specified period. -// This can be helpful in tests. With no prev time set, the first block accrues no rewards as it just sets the prev time to the current. -func (builder IncentiveGenesisBuilder) WithInitializedSupplyRewardPeriod(period types.MultiRewardPeriod) IncentiveGenesisBuilder { - builder.Params.HardSupplyRewardPeriods = append(builder.Params.HardSupplyRewardPeriods, period) - - accumulationTimeForPeriod := types.NewAccumulationTime(period.CollateralType, builder.genesisTime) - builder.HardSupplyRewardState.AccumulationTimes = append( - builder.HardSupplyRewardState.AccumulationTimes, - accumulationTimeForPeriod, - ) - - // TODO remove to better reflect real states - builder.HardSupplyRewardState.MultiRewardIndexes = builder.HardSupplyRewardState.MultiRewardIndexes.With( - period.CollateralType, - newZeroRewardIndexesFromCoins(period.RewardsPerSecond...), - ) - - return builder -} - -func (builder IncentiveGenesisBuilder) WithSimpleSupplyRewardPeriod(ctype string, rewardsPerSecond sdk.Coins) IncentiveGenesisBuilder { - return builder.WithInitializedSupplyRewardPeriod(builder.simpleRewardPeriod(ctype, rewardsPerSecond)) -} - -// WithInitializedDelegatorRewardPeriod sets the genesis time as the previous accumulation time for the specified period. -// This can be helpful in tests. With no prev time set, the first block accrues no rewards as it just sets the prev time to the current. -func (builder IncentiveGenesisBuilder) WithInitializedDelegatorRewardPeriod(period types.MultiRewardPeriod) IncentiveGenesisBuilder { - builder.Params.DelegatorRewardPeriods = append(builder.Params.DelegatorRewardPeriods, period) - - accumulationTimeForPeriod := types.NewAccumulationTime(period.CollateralType, builder.genesisTime) - builder.DelegatorRewardState.AccumulationTimes = append( - builder.DelegatorRewardState.AccumulationTimes, - accumulationTimeForPeriod, - ) - - // TODO remove to better reflect real states - builder.DelegatorRewardState.MultiRewardIndexes = builder.DelegatorRewardState.MultiRewardIndexes.With( - period.CollateralType, - newZeroRewardIndexesFromCoins(period.RewardsPerSecond...), - ) - - return builder -} - -func (builder IncentiveGenesisBuilder) WithSimpleDelegatorRewardPeriod(ctype string, rewardsPerSecond sdk.Coins) IncentiveGenesisBuilder { - return builder.WithInitializedDelegatorRewardPeriod(builder.simpleRewardPeriod(ctype, rewardsPerSecond)) -} - -// WithInitializedSwapRewardPeriod sets the genesis time as the previous accumulation time for the specified period. -// This can be helpful in tests. With no prev time set, the first block accrues no rewards as it just sets the prev time to the current. -func (builder IncentiveGenesisBuilder) WithInitializedSwapRewardPeriod(period types.MultiRewardPeriod) IncentiveGenesisBuilder { - builder.Params.SwapRewardPeriods = append(builder.Params.SwapRewardPeriods, period) - - accumulationTimeForPeriod := types.NewAccumulationTime(period.CollateralType, builder.genesisTime) - builder.SwapRewardState.AccumulationTimes = append( - builder.SwapRewardState.AccumulationTimes, - accumulationTimeForPeriod, - ) - - return builder -} - -func (builder IncentiveGenesisBuilder) WithSimpleSwapRewardPeriod(poolID string, rewardsPerSecond sdk.Coins) IncentiveGenesisBuilder { - return builder.WithInitializedSwapRewardPeriod(builder.simpleRewardPeriod(poolID, rewardsPerSecond)) -} - -// WithInitializedUSDXRewardPeriod sets the genesis time as the previous accumulation time for the specified period. -// This can be helpful in tests. With no prev time set, the first block accrues no rewards as it just sets the prev time to the current. -func (builder IncentiveGenesisBuilder) WithInitializedUSDXRewardPeriod(period types.RewardPeriod) IncentiveGenesisBuilder { - builder.Params.USDXMintingRewardPeriods = append(builder.Params.USDXMintingRewardPeriods, period) - - accumulationTimeForPeriod := types.NewAccumulationTime(period.CollateralType, builder.genesisTime) - builder.USDXRewardState.AccumulationTimes = append( - builder.USDXRewardState.AccumulationTimes, - accumulationTimeForPeriod, - ) - - // TODO remove to better reflect real states - builder.USDXRewardState.MultiRewardIndexes = builder.USDXRewardState.MultiRewardIndexes.With( - period.CollateralType, - newZeroRewardIndexesFromCoins(period.RewardsPerSecond), - ) - - return builder -} - -func (builder IncentiveGenesisBuilder) WithSimpleUSDXRewardPeriod(ctype string, rewardsPerSecond sdk.Coin) IncentiveGenesisBuilder { - return builder.WithInitializedUSDXRewardPeriod(types.NewRewardPeriod( - true, - ctype, - builder.genesisTime, - builder.genesisTime.Add(4*oneYear), - rewardsPerSecond, - )) -} - -// WithInitializedEarnRewardPeriod sets the genesis time as the previous accumulation time for the specified period. -// This can be helpful in tests. With no prev time set, the first block accrues no rewards as it just sets the prev time to the current. -func (builder IncentiveGenesisBuilder) WithInitializedEarnRewardPeriod(period types.MultiRewardPeriod) IncentiveGenesisBuilder { - builder.Params.EarnRewardPeriods = append(builder.Params.EarnRewardPeriods, period) - - accumulationTimeForPeriod := types.NewAccumulationTime(period.CollateralType, builder.genesisTime) - builder.EarnRewardState.AccumulationTimes = append( - builder.EarnRewardState.AccumulationTimes, - accumulationTimeForPeriod, - ) - - return builder -} - -func (builder IncentiveGenesisBuilder) WithSimpleEarnRewardPeriod(ctype string, rewardsPerSecond sdk.Coins) IncentiveGenesisBuilder { - return builder.WithInitializedEarnRewardPeriod(builder.simpleRewardPeriod(ctype, rewardsPerSecond)) -} - -func (builder IncentiveGenesisBuilder) WithMultipliers(multipliers types.MultipliersPerDenoms) IncentiveGenesisBuilder { - builder.Params.ClaimMultipliers = multipliers - - return builder -} - -func (builder IncentiveGenesisBuilder) simpleRewardPeriod(ctype string, rewardsPerSecond sdk.Coins) types.MultiRewardPeriod { - return types.NewMultiRewardPeriod( - true, - ctype, - builder.genesisTime, - builder.genesisTime.Add(4*oneYear), - rewardsPerSecond, - ) -} - -func newZeroRewardIndexesFromCoins(coins ...sdk.Coin) types.RewardIndexes { - var ri types.RewardIndexes - for _, coin := range coins { - ri = ri.With(coin.Denom, sdk.ZeroDec()) - } - return ri -} - -// HardGenesisBuilder is a tool for creating a hard genesis state. -// Helper methods add values onto a default genesis state. -// All methods are immutable and return updated copies of the builder. -type HardGenesisBuilder struct { - hardtypes.GenesisState - genesisTime time.Time -} - -func NewHardGenesisBuilder() HardGenesisBuilder { - return HardGenesisBuilder{ - GenesisState: hardtypes.DefaultGenesisState(), - } -} - -func (builder HardGenesisBuilder) Build() hardtypes.GenesisState { - return builder.GenesisState -} - -func (builder HardGenesisBuilder) BuildMarshalled(cdc codec.JSONCodec) app.GenesisState { - built := builder.Build() - - return app.GenesisState{ - hardtypes.ModuleName: cdc.MustMarshalJSON(&built), - } -} - -func (builder HardGenesisBuilder) WithGenesisTime(genTime time.Time) HardGenesisBuilder { - builder.genesisTime = genTime - return builder -} - -func (builder HardGenesisBuilder) WithInitializedMoneyMarket(market hardtypes.MoneyMarket) HardGenesisBuilder { - builder.Params.MoneyMarkets = append(builder.Params.MoneyMarkets, market) - - builder.PreviousAccumulationTimes = append( - builder.PreviousAccumulationTimes, - hardtypes.NewGenesisAccumulationTime(market.Denom, builder.genesisTime, sdk.OneDec(), sdk.OneDec()), - ) - return builder -} - -func (builder HardGenesisBuilder) WithMinBorrow(minUSDValue sdk.Dec) HardGenesisBuilder { - builder.Params.MinimumBorrowUSDValue = minUSDValue - return builder -} - -func NewStandardMoneyMarket(denom string) hardtypes.MoneyMarket { - return hardtypes.NewMoneyMarket( - denom, - hardtypes.NewBorrowLimit( - false, - sdk.NewDec(1e15), - sdk.MustNewDecFromStr("0.6"), - ), - denom+":usd", - sdkmath.NewInt(1e6), - hardtypes.NewInterestRateModel( - sdk.MustNewDecFromStr("0.05"), - sdk.MustNewDecFromStr("2"), - sdk.MustNewDecFromStr("0.8"), - sdk.MustNewDecFromStr("10"), - ), - sdk.MustNewDecFromStr("0.05"), - sdk.ZeroDec(), - ) -} - -// WithInitializedSavingsRewardPeriod sets the genesis time as the previous accumulation time for the specified period. -// This can be helpful in tests. With no prev time set, the first block accrues no rewards as it just sets the prev time to the current. -func (builder IncentiveGenesisBuilder) WithInitializedSavingsRewardPeriod(period types.MultiRewardPeriod) IncentiveGenesisBuilder { - builder.Params.SavingsRewardPeriods = append(builder.Params.SavingsRewardPeriods, period) - - accumulationTimeForPeriod := types.NewAccumulationTime(period.CollateralType, builder.genesisTime) - builder.SavingsRewardState.AccumulationTimes = append( - builder.SavingsRewardState.AccumulationTimes, - accumulationTimeForPeriod, - ) - - builder.SavingsRewardState.MultiRewardIndexes = builder.SavingsRewardState.MultiRewardIndexes.With( - period.CollateralType, - newZeroRewardIndexesFromCoins(period.RewardsPerSecond...), - ) - - return builder -} - -func (builder IncentiveGenesisBuilder) WithSimpleSavingsRewardPeriod(ctype string, rewardsPerSecond sdk.Coins) IncentiveGenesisBuilder { - return builder.WithInitializedSavingsRewardPeriod(builder.simpleRewardPeriod(ctype, rewardsPerSecond)) -} - -// SavingsGenesisBuilder is a tool for creating a savings genesis state. -// Helper methods add values onto a default genesis state. -// All methods are immutable and return updated copies of the builder. -type SavingsGenesisBuilder struct { - savingstypes.GenesisState - genesisTime time.Time -} - -func NewSavingsGenesisBuilder() SavingsGenesisBuilder { - return SavingsGenesisBuilder{ - GenesisState: savingstypes.DefaultGenesisState(), - } -} - -func (builder SavingsGenesisBuilder) Build() savingstypes.GenesisState { - return builder.GenesisState -} - -func (builder SavingsGenesisBuilder) BuildMarshalled(cdc codec.JSONCodec) app.GenesisState { - built := builder.Build() - - return app.GenesisState{ - savingstypes.ModuleName: cdc.MustMarshalJSON(&built), - } -} - -func (builder SavingsGenesisBuilder) WithGenesisTime(genTime time.Time) SavingsGenesisBuilder { - builder.genesisTime = genTime - return builder -} - -func (builder SavingsGenesisBuilder) WithSupportedDenoms(denoms ...string) SavingsGenesisBuilder { - builder.Params.SupportedDenoms = append(builder.Params.SupportedDenoms, denoms...) - return builder -} diff --git a/x/incentive/testutil/earn_builder.go b/x/incentive/testutil/earn_builder.go deleted file mode 100644 index 668a9e65..00000000 --- a/x/incentive/testutil/earn_builder.go +++ /dev/null @@ -1,40 +0,0 @@ -package testutil - -import ( - "github.com/0glabs/0g-chain/app" - "github.com/cosmos/cosmos-sdk/codec" - - earntypes "github.com/0glabs/0g-chain/x/earn/types" -) - -// EarnGenesisBuilder is a tool for creating a earn genesis state. -// Helper methods add values onto a default genesis state. -// All methods are immutable and return updated copies of the builder. -type EarnGenesisBuilder struct { - earntypes.GenesisState -} - -var _ GenesisBuilder = (*EarnGenesisBuilder)(nil) - -func NewEarnGenesisBuilder() EarnGenesisBuilder { - return EarnGenesisBuilder{ - GenesisState: earntypes.DefaultGenesisState(), - } -} - -func (builder EarnGenesisBuilder) Build() earntypes.GenesisState { - return builder.GenesisState -} - -func (builder EarnGenesisBuilder) BuildMarshalled(cdc codec.JSONCodec) app.GenesisState { - built := builder.Build() - - return app.GenesisState{ - earntypes.ModuleName: cdc.MustMarshalJSON(&built), - } -} - -func (builder EarnGenesisBuilder) WithAllowedVaults(vault ...earntypes.AllowedVault) EarnGenesisBuilder { - builder.Params.AllowedVaults = append(builder.Params.AllowedVaults, vault...) - return builder -} diff --git a/x/incentive/testutil/integration.go b/x/incentive/testutil/integration.go deleted file mode 100644 index 023b7544..00000000 --- a/x/incentive/testutil/integration.go +++ /dev/null @@ -1,602 +0,0 @@ -package testutil - -import ( - "errors" - "fmt" - "time" - - sdkmath "cosmossdk.io/math" - abcitypes "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - proposaltypes "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/app" - cdpkeeper "github.com/0glabs/0g-chain/x/cdp/keeper" - cdptypes "github.com/0glabs/0g-chain/x/cdp/types" - committeekeeper "github.com/0glabs/0g-chain/x/committee/keeper" - committeetypes "github.com/0glabs/0g-chain/x/committee/types" - earnkeeper "github.com/0glabs/0g-chain/x/earn/keeper" - earntypes "github.com/0glabs/0g-chain/x/earn/types" - hardkeeper "github.com/0glabs/0g-chain/x/hard/keeper" - hardtypes "github.com/0glabs/0g-chain/x/hard/types" - incentivekeeper "github.com/0glabs/0g-chain/x/incentive/keeper" - "github.com/0glabs/0g-chain/x/incentive/types" - liquidkeeper "github.com/0glabs/0g-chain/x/liquid/keeper" - liquidtypes "github.com/0glabs/0g-chain/x/liquid/types" - routerkeeper "github.com/0glabs/0g-chain/x/router/keeper" - routertypes "github.com/0glabs/0g-chain/x/router/types" - swapkeeper "github.com/0glabs/0g-chain/x/swap/keeper" - swaptypes "github.com/0glabs/0g-chain/x/swap/types" -) - -type IntegrationTester struct { - suite.Suite - App app.TestApp - Ctx sdk.Context - - GenesisTime time.Time -} - -func (suite *IntegrationTester) SetupSuite() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - // Default genesis time, can be overridden with WithGenesisTime - suite.GenesisTime = time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC) -} - -func (suite *IntegrationTester) SetApp() { - suite.App = app.NewTestApp() -} - -func (suite *IntegrationTester) SetupTest() { - suite.SetApp() -} - -func (suite *IntegrationTester) WithGenesisTime(genesisTime time.Time) { - suite.GenesisTime = genesisTime -} - -func (suite *IntegrationTester) StartChainWithBuilders(builders ...GenesisBuilder) { - var builtGenStates []app.GenesisState - for _, builder := range builders { - builtGenStates = append(builtGenStates, builder.BuildMarshalled(suite.App.AppCodec())) - } - - suite.StartChain(builtGenStates...) -} - -func (suite *IntegrationTester) StartChain(genesisStates ...app.GenesisState) { - suite.App.InitializeFromGenesisStatesWithTimeAndChainID( - suite.GenesisTime, - app.TestChainId, - genesisStates..., - ) - - suite.Ctx = suite.App.NewContext(false, tmproto.Header{ - Height: 1, - Time: suite.GenesisTime, - ChainID: app.TestChainId, - }) -} - -func (suite *IntegrationTester) NextBlockAfter(blockDuration time.Duration) { - suite.NextBlockAfterWithReq( - blockDuration, - abcitypes.RequestEndBlock{}, - abcitypes.RequestBeginBlock{}, - ) -} - -func (suite *IntegrationTester) NextBlockAfterWithReq( - blockDuration time.Duration, - reqEnd abcitypes.RequestEndBlock, - reqBegin abcitypes.RequestBeginBlock, -) (abcitypes.ResponseEndBlock, abcitypes.ResponseBeginBlock) { - return suite.NextBlockAtWithRequest( - suite.Ctx.BlockTime().Add(blockDuration), - reqEnd, - reqBegin, - ) -} - -func (suite *IntegrationTester) NextBlockAt( - blockTime time.Time, -) (abcitypes.ResponseEndBlock, abcitypes.ResponseBeginBlock) { - return suite.NextBlockAtWithRequest( - blockTime, - abcitypes.RequestEndBlock{}, - abcitypes.RequestBeginBlock{}, - ) -} - -func (suite *IntegrationTester) NextBlockAtWithRequest( - blockTime time.Time, - reqEnd abcitypes.RequestEndBlock, - reqBegin abcitypes.RequestBeginBlock, -) (abcitypes.ResponseEndBlock, abcitypes.ResponseBeginBlock) { - if !suite.Ctx.BlockTime().Before(blockTime) { - panic(fmt.Sprintf("new block time %s must be after current %s", blockTime, suite.Ctx.BlockTime())) - } - blockHeight := suite.Ctx.BlockHeight() + 1 - - responseEndBlock := suite.App.EndBlocker(suite.Ctx, reqEnd) - suite.Ctx = suite.Ctx.WithBlockTime(blockTime).WithBlockHeight(blockHeight).WithChainID(app.TestChainId) - responseBeginBlock := suite.App.BeginBlocker(suite.Ctx, reqBegin) // height and time in RequestBeginBlock are ignored by module begin blockers - - return responseEndBlock, responseBeginBlock -} - -func (suite *IntegrationTester) DeliverIncentiveMsg(msg sdk.Msg) error { - msgServer := incentivekeeper.NewMsgServerImpl(suite.App.GetIncentiveKeeper()) - - var err error - - switch msg := msg.(type) { - case *types.MsgClaimHardReward: - _, err = msgServer.ClaimHardReward(sdk.WrapSDKContext(suite.Ctx), msg) - case *types.MsgClaimSwapReward: - _, err = msgServer.ClaimSwapReward(sdk.WrapSDKContext(suite.Ctx), msg) - case *types.MsgClaimUSDXMintingReward: - _, err = msgServer.ClaimUSDXMintingReward(sdk.WrapSDKContext(suite.Ctx), msg) - case *types.MsgClaimDelegatorReward: - _, err = msgServer.ClaimDelegatorReward(sdk.WrapSDKContext(suite.Ctx), msg) - case *types.MsgClaimEarnReward: - _, err = msgServer.ClaimEarnReward(sdk.WrapSDKContext(suite.Ctx), msg) - default: - panic("unhandled incentive msg") - } - - return err -} - -// MintLiquidAnyValAddr mints liquid tokens with the given validator address, -// creating the validator if it does not already exist. -// **Note:** This will increment the block height/time and run the End and Begin -// blockers! -func (suite *IntegrationTester) MintLiquidAnyValAddr( - owner sdk.AccAddress, - validator sdk.ValAddress, - amount sdk.Coin, -) (sdk.Coin, error) { - // Check if validator already created - _, found := suite.App.GetStakingKeeper().GetValidator(suite.Ctx, validator) - if !found { - // Create validator - if err := suite.DeliverMsgCreateValidator(validator, sdk.NewCoin("ukava", sdkmath.NewInt(1e9))); err != nil { - return sdk.Coin{}, err - } - - // new block required to bond validator - suite.NextBlockAfter(7 * time.Second) - } - - // Delegate and mint liquid tokens - return suite.DeliverMsgDelegateMint(owner, validator, amount) -} - -func (suite *IntegrationTester) GetAbciValidator(valAddr sdk.ValAddress) abcitypes.Validator { - sk := suite.App.GetStakingKeeper() - - val, found := sk.GetValidator(suite.Ctx, valAddr) - suite.Require().True(found) - - pk, err := val.ConsPubKey() - suite.Require().NoError(err) - - return abcitypes.Validator{ - Address: pk.Address(), - Power: val.GetConsensusPower(sk.PowerReduction(suite.Ctx)), - } -} - -func (suite *IntegrationTester) DeliverMsgCreateValidator(address sdk.ValAddress, selfDelegation sdk.Coin) error { - msg, err := stakingtypes.NewMsgCreateValidator( - address, - ed25519.GenPrivKey().PubKey(), - selfDelegation, - stakingtypes.Description{}, - stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - sdkmath.NewInt(1_000_000), - ) - if err != nil { - return err - } - - msgServer := stakingkeeper.NewMsgServerImpl(suite.App.GetStakingKeeper()) - _, err = msgServer.CreateValidator(sdk.WrapSDKContext(suite.Ctx), msg) - - return err -} - -func (suite *IntegrationTester) DeliverMsgDelegate(delegator sdk.AccAddress, validator sdk.ValAddress, amount sdk.Coin) error { - msg := stakingtypes.NewMsgDelegate( - delegator, - validator, - amount, - ) - msgServer := stakingkeeper.NewMsgServerImpl(suite.App.GetStakingKeeper()) - _, err := msgServer.Delegate(sdk.WrapSDKContext(suite.Ctx), msg) - return err -} - -func (suite *IntegrationTester) DeliverSwapMsgDeposit(depositor sdk.AccAddress, tokenA, tokenB sdk.Coin, slippage sdk.Dec) error { - msg := swaptypes.NewMsgDeposit( - depositor.String(), - tokenA, - tokenB, - slippage, - suite.Ctx.BlockTime().Add(time.Hour).Unix(), // ensure msg will not fail due to short deadline - ) - msgServer := swapkeeper.NewMsgServerImpl(suite.App.GetSwapKeeper()) - _, err := msgServer.Deposit(sdk.WrapSDKContext(suite.Ctx), msg) - - return err -} - -func (suite *IntegrationTester) DeliverHardMsgDeposit(owner sdk.AccAddress, deposit sdk.Coins) error { - msg := hardtypes.NewMsgDeposit(owner, deposit) - msgServer := hardkeeper.NewMsgServerImpl(suite.App.GetHardKeeper()) - - _, err := msgServer.Deposit(sdk.WrapSDKContext(suite.Ctx), &msg) - return err -} - -func (suite *IntegrationTester) DeliverHardMsgBorrow(owner sdk.AccAddress, borrow sdk.Coins) error { - msg := hardtypes.NewMsgBorrow(owner, borrow) - msgServer := hardkeeper.NewMsgServerImpl(suite.App.GetHardKeeper()) - - _, err := msgServer.Borrow(sdk.WrapSDKContext(suite.Ctx), &msg) - return err -} - -func (suite *IntegrationTester) DeliverHardMsgRepay(owner sdk.AccAddress, repay sdk.Coins) error { - msg := hardtypes.NewMsgRepay(owner, owner, repay) - msgServer := hardkeeper.NewMsgServerImpl(suite.App.GetHardKeeper()) - - _, err := msgServer.Repay(sdk.WrapSDKContext(suite.Ctx), &msg) - return err -} - -func (suite *IntegrationTester) DeliverHardMsgWithdraw(owner sdk.AccAddress, withdraw sdk.Coins) error { - msg := hardtypes.NewMsgWithdraw(owner, withdraw) - msgServer := hardkeeper.NewMsgServerImpl(suite.App.GetHardKeeper()) - - _, err := msgServer.Withdraw(sdk.WrapSDKContext(suite.Ctx), &msg) - return err -} - -func (suite *IntegrationTester) DeliverMsgCreateCDP(owner sdk.AccAddress, collateral, principal sdk.Coin, collateralType string) error { - msg := cdptypes.NewMsgCreateCDP(owner, collateral, principal, collateralType) - msgServer := cdpkeeper.NewMsgServerImpl(suite.App.GetCDPKeeper()) - - _, err := msgServer.CreateCDP(sdk.WrapSDKContext(suite.Ctx), &msg) - return err -} - -func (suite *IntegrationTester) DeliverCDPMsgRepay(owner sdk.AccAddress, collateralType string, payment sdk.Coin) error { - msg := cdptypes.NewMsgRepayDebt(owner, collateralType, payment) - msgServer := cdpkeeper.NewMsgServerImpl(suite.App.GetCDPKeeper()) - - _, err := msgServer.RepayDebt(sdk.WrapSDKContext(suite.Ctx), &msg) - return err -} - -func (suite *IntegrationTester) DeliverCDPMsgBorrow(owner sdk.AccAddress, collateralType string, draw sdk.Coin) error { - msg := cdptypes.NewMsgDrawDebt(owner, collateralType, draw) - msgServer := cdpkeeper.NewMsgServerImpl(suite.App.GetCDPKeeper()) - - _, err := msgServer.DrawDebt(sdk.WrapSDKContext(suite.Ctx), &msg) - return err -} - -func (suite *IntegrationTester) DeliverMsgMintDerivative( - sender sdk.AccAddress, - validator sdk.ValAddress, - amount sdk.Coin, -) (sdk.Coin, error) { - msg := liquidtypes.NewMsgMintDerivative(sender, validator, amount) - msgServer := liquidkeeper.NewMsgServerImpl(suite.App.GetLiquidKeeper()) - - res, err := msgServer.MintDerivative(sdk.WrapSDKContext(suite.Ctx), &msg) - if err != nil { - // Instead of returning res.Received, as res will be nil if there is an error - return sdk.Coin{}, err - } - - return res.Received, err -} - -func (suite *IntegrationTester) DeliverEarnMsgDeposit( - depositor sdk.AccAddress, - amount sdk.Coin, - strategy earntypes.StrategyType, -) error { - msg := earntypes.NewMsgDeposit(depositor.String(), amount, strategy) - msgServer := earnkeeper.NewMsgServerImpl(suite.App.GetEarnKeeper()) - - _, err := msgServer.Deposit(sdk.WrapSDKContext(suite.Ctx), msg) - return err -} - -func (suite *IntegrationTester) ProposeAndVoteOnNewParams(voter sdk.AccAddress, committeeID uint64, changes []proposaltypes.ParamChange) { - propose, err := committeetypes.NewMsgSubmitProposal( - proposaltypes.NewParameterChangeProposal( - "test title", - "test description", - changes, - ), - voter, - committeeID, - ) - suite.NoError(err) - - msgServer := committeekeeper.NewMsgServerImpl(suite.App.GetCommitteeKeeper()) - - res, err := msgServer.SubmitProposal(sdk.WrapSDKContext(suite.Ctx), propose) - suite.NoError(err) - - proposalID := res.ProposalID - vote := committeetypes.NewMsgVote(voter, proposalID, committeetypes.VOTE_TYPE_YES) - _, err = msgServer.Vote(sdk.WrapSDKContext(suite.Ctx), vote) - suite.NoError(err) -} - -func (suite *IntegrationTester) GetAccount(addr sdk.AccAddress) authtypes.AccountI { - ak := suite.App.GetAccountKeeper() - return ak.GetAccount(suite.Ctx, addr) -} - -func (suite *IntegrationTester) GetModuleAccount(name string) authtypes.ModuleAccountI { - ak := suite.App.GetAccountKeeper() - return ak.GetModuleAccount(suite.Ctx, name) -} - -func (suite *IntegrationTester) GetBalance(address sdk.AccAddress) sdk.Coins { - bk := suite.App.GetBankKeeper() - return bk.GetAllBalances(suite.Ctx, address) -} - -func (suite *IntegrationTester) ErrorIs(err, target error) bool { - return suite.Truef(errors.Is(err, target), "err didn't match: %s, it was: %s", target, err) -} - -func (suite *IntegrationTester) BalanceEquals(address sdk.AccAddress, expected sdk.Coins) { - bk := suite.App.GetBankKeeper() - suite.Equalf( - expected, - bk.GetAllBalances(suite.Ctx, address), - "expected account balance to equal coins %s, but got %s", - expected, - bk.GetAllBalances(suite.Ctx, address), - ) -} - -func (suite *IntegrationTester) BalanceInEpsilon(address sdk.AccAddress, expected sdk.Coins, epsilon float64) { - actual := suite.GetBalance(address) - - allDenoms := expected.Add(actual...) - for _, coin := range allDenoms { - suite.InEpsilonf( - expected.AmountOf(coin.Denom).Int64(), - actual.AmountOf(coin.Denom).Int64(), - epsilon, - "expected balance to be within %f%% of coins %s, but got %s", epsilon*100, expected, actual, - ) - } -} - -func (suite *IntegrationTester) VestingPeriodsEqual(address sdk.AccAddress, expectedPeriods []vestingtypes.Period) { - acc := suite.App.GetAccountKeeper().GetAccount(suite.Ctx, address) - suite.Require().NotNil(acc, "expected vesting account not to be nil") - vacc, ok := acc.(*vestingtypes.PeriodicVestingAccount) - suite.Require().True(ok, "expected vesting account to be type PeriodicVestingAccount") - suite.Equal(expectedPeriods, vacc.VestingPeriods) -} - -// ----------------------------------------------------------------------------- -// x/incentive - -func (suite *IntegrationTester) SwapRewardEquals(owner sdk.AccAddress, expected sdk.Coins) { - claim, found := suite.App.GetIncentiveKeeper().GetSwapClaim(suite.Ctx, owner) - suite.Require().Truef(found, "expected swap claim to be found for %s", owner) - suite.Equalf(expected, claim.Reward, "expected swap claim reward to be %s, but got %s", expected, claim.Reward) -} - -func (suite *IntegrationTester) DelegatorRewardEquals(owner sdk.AccAddress, expected sdk.Coins) { - claim, found := suite.App.GetIncentiveKeeper().GetDelegatorClaim(suite.Ctx, owner) - suite.Require().Truef(found, "expected delegator claim to be found for %s", owner) - suite.Equalf(expected, claim.Reward, "expected delegator claim reward to be %s, but got %s", expected, claim.Reward) -} - -func (suite *IntegrationTester) HardRewardEquals(owner sdk.AccAddress, expected sdk.Coins) { - claim, found := suite.App.GetIncentiveKeeper().GetHardLiquidityProviderClaim(suite.Ctx, owner) - suite.Require().Truef(found, "expected delegator claim to be found for %s", owner) - suite.Equalf(expected, claim.Reward, "expected delegator claim reward to be %s, but got %s", expected, claim.Reward) -} - -func (suite *IntegrationTester) USDXRewardEquals(owner sdk.AccAddress, expected sdk.Coin) { - claim, found := suite.App.GetIncentiveKeeper().GetUSDXMintingClaim(suite.Ctx, owner) - suite.Require().Truef(found, "expected delegator claim to be found for %s", owner) - suite.Equalf(expected, claim.Reward, "expected delegator claim reward to be %s, but got %s", expected, claim.Reward) -} - -func (suite *IntegrationTester) EarnRewardEquals(owner sdk.AccAddress, expected sdk.Coins) { - claim, found := suite.App.GetIncentiveKeeper().GetEarnClaim(suite.Ctx, owner) - suite.Require().Truef(found, "expected earn claim to be found for %s", owner) - suite.Truef(expected.IsEqual(claim.Reward), "expected earn claim reward to be %s, but got %s", expected, claim.Reward) -} - -// AddTestAddrsFromPubKeys adds the addresses into the SimApp providing only the public keys. -func (suite *IntegrationTester) AddTestAddrsFromPubKeys(ctx sdk.Context, pubKeys []cryptotypes.PubKey, accAmt sdkmath.Int) { - initCoins := sdk.NewCoins(sdk.NewCoin(suite.App.GetStakingKeeper().BondDenom(ctx), accAmt)) - - for _, pk := range pubKeys { - suite.App.FundAccount(ctx, sdk.AccAddress(pk.Address()), initCoins) - } -} - -func (suite *IntegrationTester) StoredEarnTimeEquals(denom string, expected time.Time) { - storedTime, found := suite.App.GetIncentiveKeeper().GetEarnRewardAccrualTime(suite.Ctx, denom) - suite.Equal(found, expected != time.Time{}, "expected time is %v but time found = %v", expected, found) - if found { - suite.Equal(expected, storedTime) - } else { - suite.Empty(storedTime) - } -} - -func (suite *IntegrationTester) StoredEarnIndexesEqual(denom string, expected types.RewardIndexes) { - storedIndexes, found := suite.App.GetIncentiveKeeper().GetEarnRewardIndexes(suite.Ctx, denom) - suite.Equal(found, expected != nil) - - if found { - suite.Equal(expected, storedIndexes) - } else { - // Can't compare Equal for types.RewardIndexes(nil) vs types.RewardIndexes{} - suite.Empty(storedIndexes) - } -} - -func (suite *IntegrationTester) AddIncentiveEarnMultiRewardPeriod(period types.MultiRewardPeriod) { - ik := suite.App.GetIncentiveKeeper() - params := ik.GetParams(suite.Ctx) - - for i, reward := range params.EarnRewardPeriods { - if reward.CollateralType == period.CollateralType { - // Replace existing reward period if the collateralType exists. - // Params are invalid if there are multiple reward periods for the - // same collateral type. - params.EarnRewardPeriods[i] = period - ik.SetParams(suite.Ctx, params) - return - } - } - - params.EarnRewardPeriods = append(params.EarnRewardPeriods, period) - - suite.NoError(params.Validate()) - ik.SetParams(suite.Ctx, params) -} - -// ----------------------------------------------------------------------------- -// x/router - -func (suite *IntegrationTester) DeliverRouterMsgDelegateMintDeposit( - depositor sdk.AccAddress, - validator sdk.ValAddress, - amount sdk.Coin, -) error { - msg := routertypes.MsgDelegateMintDeposit{ - Depositor: depositor.String(), - Validator: validator.String(), - Amount: amount, - } - msgServer := routerkeeper.NewMsgServerImpl(suite.App.GetRouterKeeper()) - - _, err := msgServer.DelegateMintDeposit(sdk.WrapSDKContext(suite.Ctx), &msg) - return err -} - -func (suite *IntegrationTester) DeliverRouterMsgMintDeposit( - depositor sdk.AccAddress, - validator sdk.ValAddress, - amount sdk.Coin, -) error { - msg := routertypes.MsgMintDeposit{ - Depositor: depositor.String(), - Validator: validator.String(), - Amount: amount, - } - msgServer := routerkeeper.NewMsgServerImpl(suite.App.GetRouterKeeper()) - - _, err := msgServer.MintDeposit(sdk.WrapSDKContext(suite.Ctx), &msg) - return err -} - -func (suite *IntegrationTester) DeliverMsgDelegateMint( - delegator sdk.AccAddress, - validator sdk.ValAddress, - amount sdk.Coin, -) (sdk.Coin, error) { - if err := suite.DeliverMsgDelegate(delegator, validator, amount); err != nil { - return sdk.Coin{}, err - } - - return suite.DeliverMsgMintDerivative(delegator, validator, amount) -} - -// ----------------------------------------------------------------------------- -// x/distribution - -func (suite *IntegrationTester) GetBeginBlockClaimedStakingRewards( - resBeginBlock abcitypes.ResponseBeginBlock, -) (validatorRewards map[string]sdk.Coins, totalRewards sdk.Coins) { - // Events emitted in BeginBlocker are in the ResponseBeginBlock, not in - // ctx.EventManager().Events() as BeginBlock is called with a NewEventManager() - // cosmos-sdk/types/module/module.go: func(m *Manager) BeginBlock(...) - - // We also need to parse the events to get the rewards as querying state will - // always contain 0 rewards -- rewards are always claimed right after - // mint+distribution in BeginBlocker which resets distribution state back to - // 0 for reward amounts - blockRewardsClaimed := make(map[string]sdk.Coins) - for _, event := range resBeginBlock.Events { - if event.Type != distributiontypes.EventTypeWithdrawRewards { - continue - } - - // Example event attributes, amount can be empty for no rewards - // - // Event: withdraw_rewards - // - amount: - // - validator: kavavaloper1em2mlkrkx0qsa6327tgvl3g0fh8a95hjnqvrwh - // Event: withdraw_rewards - // - amount: 523909ukava - // - validator: kavavaloper1nmgpgr8l4t8pw9zqx9cltuymvz85wmw9sy8kjy - attrsMap := attrsToMap(event.Attributes) - - validator, found := attrsMap[distributiontypes.AttributeKeyValidator] - suite.Require().Truef(found, "expected validator attribute to be found in event %s", event) - - amountStr, found := attrsMap[sdk.AttributeKeyAmount] - suite.Require().Truef(found, "expected amount attribute to be found in event %s", event) - - amount := sdk.NewCoins() - - // Only parse amount if it is not empty - if len(amountStr) > 0 { - parsedAmt, err := sdk.ParseCoinNormalized(amountStr) - suite.Require().NoError(err) - amount = amount.Add(parsedAmt) - } - - blockRewardsClaimed[validator] = amount - } - - totalClaimedRewards := sdk.NewCoins() - for _, amount := range blockRewardsClaimed { - totalClaimedRewards = totalClaimedRewards.Add(amount...) - } - - return blockRewardsClaimed, totalClaimedRewards -} - -func attrsToMap(attrs []abcitypes.EventAttribute) map[string]string { - out := make(map[string]string) - - for _, attr := range attrs { - out[string(attr.Key)] = string(attr.Value) - } - - return out -} diff --git a/x/incentive/testutil/mint_builder.go b/x/incentive/testutil/mint_builder.go deleted file mode 100644 index 80ba292f..00000000 --- a/x/incentive/testutil/mint_builder.go +++ /dev/null @@ -1,68 +0,0 @@ -package testutil - -import ( - "github.com/0glabs/0g-chain/app" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" -) - -// MintGenesisBuilder is a tool for creating a mint genesis state. -// Helper methods add values onto a default genesis state. -// All methods are immutable and return updated copies of the builder. -type MintGenesisBuilder struct { - minttypes.GenesisState -} - -var _ GenesisBuilder = (*MintGenesisBuilder)(nil) - -func NewMintGenesisBuilder() MintGenesisBuilder { - gen := minttypes.DefaultGenesisState() - gen.Params.MintDenom = "ukava" - - return MintGenesisBuilder{ - GenesisState: *gen, - } -} - -func (builder MintGenesisBuilder) Build() minttypes.GenesisState { - return builder.GenesisState -} - -func (builder MintGenesisBuilder) BuildMarshalled(cdc codec.JSONCodec) app.GenesisState { - built := builder.Build() - - return app.GenesisState{ - minttypes.ModuleName: cdc.MustMarshalJSON(&built), - } -} - -func (builder MintGenesisBuilder) WithMinter( - inflation sdk.Dec, - annualProvisions sdk.Dec, -) MintGenesisBuilder { - builder.Minter = minttypes.NewMinter(inflation, annualProvisions) - return builder -} - -func (builder MintGenesisBuilder) WithInflationMax( - inflationMax sdk.Dec, -) MintGenesisBuilder { - builder.Params.InflationMax = inflationMax - return builder -} - -func (builder MintGenesisBuilder) WithInflationMin( - inflationMin sdk.Dec, -) MintGenesisBuilder { - builder.Params.InflationMin = inflationMin - return builder -} - -func (builder MintGenesisBuilder) WithMintDenom( - mintDenom string, -) MintGenesisBuilder { - builder.Params.MintDenom = mintDenom - return builder -} diff --git a/x/incentive/testutil/staking_builder.go b/x/incentive/testutil/staking_builder.go deleted file mode 100644 index 14da250a..00000000 --- a/x/incentive/testutil/staking_builder.go +++ /dev/null @@ -1,38 +0,0 @@ -package testutil - -import ( - "github.com/0glabs/0g-chain/app" - "github.com/cosmos/cosmos-sdk/codec" - - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// StakingGenesisBuilder is a tool for creating a staking genesis state. -// Helper methods add values onto a default genesis state. -// All methods are immutable and return updated copies of the builder. -type StakingGenesisBuilder struct { - stakingtypes.GenesisState -} - -var _ GenesisBuilder = (*StakingGenesisBuilder)(nil) - -func NewStakingGenesisBuilder() StakingGenesisBuilder { - gen := stakingtypes.DefaultGenesisState() - gen.Params.BondDenom = "ukava" - - return StakingGenesisBuilder{ - GenesisState: *gen, - } -} - -func (builder StakingGenesisBuilder) Build() stakingtypes.GenesisState { - return builder.GenesisState -} - -func (builder StakingGenesisBuilder) BuildMarshalled(cdc codec.JSONCodec) app.GenesisState { - built := builder.Build() - - return app.GenesisState{ - stakingtypes.ModuleName: cdc.MustMarshalJSON(&built), - } -} diff --git a/x/incentive/types/accumulator.go b/x/incentive/types/accumulator.go deleted file mode 100644 index e9937cc8..00000000 --- a/x/incentive/types/accumulator.go +++ /dev/null @@ -1,144 +0,0 @@ -package types - -import ( - "fmt" - "math" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// An Accumulator handles calculating and tracking global reward distributions. -type Accumulator struct { - PreviousAccumulationTime time.Time - Indexes RewardIndexes -} - -func NewAccumulator(previousAccrual time.Time, indexes RewardIndexes) *Accumulator { - return &Accumulator{ - PreviousAccumulationTime: previousAccrual, - Indexes: indexes, - } -} - -// Accumulate accrues rewards up to the current time. -// -// It calculates new rewards and adds them to the reward indexes for the period from PreviousAccumulationTime to currentTime. -// It stores the currentTime in PreviousAccumulationTime to be used for later accumulations. -// -// Rewards are not accrued for times outside of the start and end times of a reward period. -// If a period ends before currentTime, the PreviousAccrualTime is shortened to the end time. This allows accumulate to be called sequentially on consecutive reward periods. -// -// totalSourceShares is the sum of all users' source shares. For example:total btcb supplied to hard, total usdx borrowed from all bnb CDPs, or total shares in a swap pool. -func (acc *Accumulator) Accumulate(period MultiRewardPeriod, totalSourceShares sdk.Dec, currentTime time.Time) { - acc.AccumulateDecCoins( - period.Start, - period.End, - sdk.NewDecCoinsFromCoins(period.RewardsPerSecond...), - totalSourceShares, - currentTime, - ) -} - -// AccumulateDecCoins -func (acc *Accumulator) AccumulateDecCoins( - periodStart time.Time, - periodEnd time.Time, - periodRewardsPerSecond sdk.DecCoins, - totalSourceShares sdk.Dec, - currentTime time.Time, -) { - accumulationDuration := acc.getTimeElapsedWithinLimits(acc.PreviousAccumulationTime, currentTime, periodStart, periodEnd) - - indexesIncrement := acc.calculateNewRewards(periodRewardsPerSecond, totalSourceShares, accumulationDuration) - - acc.Indexes = acc.Indexes.Add(indexesIncrement) - acc.PreviousAccumulationTime = minTime(periodEnd, currentTime) -} - -// getTimeElapsedWithinLimits returns the duration between start and end times, capped by min and max times. -// If the start and end range is outside the min to max time range then zero duration is returned. -func (*Accumulator) getTimeElapsedWithinLimits(start, end, limitMin, limitMax time.Time) time.Duration { - if start.After(end) { - panic(fmt.Sprintf("start time (%s) cannot be after end time (%s)", start, end)) - } - if limitMin.After(limitMax) { - panic(fmt.Sprintf("minimum limit time (%s) cannot be after maximum limit time (%s)", limitMin, limitMax)) - } - if start.After(limitMax) || end.Before(limitMin) { - // no intersection between the start-end and limitMin-limitMax time ranges - return 0 - } - return minTime(end, limitMax).Sub(maxTime(start, limitMin)) -} - -// calculateNewRewards calculates the amount to increase the global reward indexes by, for a given reward rate, duration, and number of source shares. -// The total rewards to distribute in this block are given by reward rate * duration. This value divided by the sum of all source shares to give -// total rewards per source share, which is what the indexes store. -// Note, duration is rounded to the nearest second to keep rewards calculation consistent with kava-7. -func (*Accumulator) calculateNewRewards(rewardsPerSecond sdk.DecCoins, totalSourceShares sdk.Dec, duration time.Duration) RewardIndexes { - if totalSourceShares.LTE(sdk.ZeroDec()) { - // When there is zero source shares, there is no users with deposits/borrows/delegations to pay out the current block's rewards to. - // So drop the rewards and pay out nothing. - return nil - } - durationSeconds := int64(math.RoundToEven(duration.Seconds())) - if durationSeconds <= 0 { - // If the duration is zero, there will be no increment. - // So return an empty increment instead of one full of zeros. - return nil - } - increment := NewRewardIndexesFromCoins(rewardsPerSecond) - increment = increment.Mul(sdk.NewDec(durationSeconds)).Quo(totalSourceShares) - return increment -} - -// minTime returns the earliest of two times. -func minTime(t1, t2 time.Time) time.Time { - if t2.Before(t1) { - return t2 - } - return t1 -} - -// maxTime returns the latest of two times. -func maxTime(t1, t2 time.Time) time.Time { - if t2.After(t1) { - return t2 - } - return t1 -} - -// NewRewardIndexesFromCoins is a helper function to initialize a RewardIndexes slice with the values from a Coins slice. -func NewRewardIndexesFromCoins(coins sdk.DecCoins) RewardIndexes { - var indexes RewardIndexes - for _, coin := range coins { - indexes = append(indexes, NewRewardIndex(coin.Denom, coin.Amount)) - } - return indexes -} - -func CalculatePerSecondRewards( - periodStart time.Time, - periodEnd time.Time, - periodRewardsPerSecond sdk.DecCoins, - previousTime, currentTime time.Time, -) (sdk.DecCoins, time.Time) { - duration := (&Accumulator{}).getTimeElapsedWithinLimits( - previousTime, - currentTime, - periodStart, - periodEnd, - ) - - upTo := minTime(periodEnd, currentTime) - - durationSeconds := int64(math.RoundToEven(duration.Seconds())) - if durationSeconds <= 0 { - // If the duration is zero, there will be no increment. - // So return an empty increment instead of one full of zeros. - return nil, upTo // TODO - } - - return periodRewardsPerSecond.MulDec(sdk.NewDec(durationSeconds)), upTo -} diff --git a/x/incentive/types/accumulator_test.go b/x/incentive/types/accumulator_test.go deleted file mode 100644 index f1792847..00000000 --- a/x/incentive/types/accumulator_test.go +++ /dev/null @@ -1,413 +0,0 @@ -package types - -import ( - "testing" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestAccumulator(t *testing.T) { - t.Run("getTimeElapsedWithinLimits", func(t *testing.T) { - type args struct { - start, end time.Time - limitMin, limitMax time.Time - } - testcases := []struct { - name string - args args - expected time.Duration - }{ - { - name: "given time range is before limits and is non zero, return 0 duration", - args: args{ - start: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - end: time.Date(1998, 1, 1, 0, 0, 1, 0, time.UTC), - limitMin: time.Date(2098, 1, 1, 0, 0, 0, 0, time.UTC), - limitMax: time.Date(2098, 1, 1, 0, 0, 0, 0, time.UTC), - }, - expected: 0, - }, - { - name: "given time range is after limits and is non zero, return 0 duration", - args: args{ - start: time.Date(2098, 1, 1, 0, 0, 0, 0, time.UTC), - end: time.Date(2098, 1, 1, 0, 0, 1, 0, time.UTC), - limitMin: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - limitMax: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - expected: 0, - }, - { - name: "given time range is within limits and is non zero, return duration", - args: args{ - start: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - end: time.Date(1998, 1, 1, 0, 0, 1, 0, time.UTC), - limitMin: time.Date(1990, 1, 1, 0, 0, 0, 0, time.UTC), - limitMax: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), - }, - expected: time.Second, - }, - { - name: "given time range is within limits and is zero, return 0 duration", - args: args{ - start: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - end: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - limitMin: time.Date(1990, 1, 1, 0, 0, 0, 0, time.UTC), - limitMax: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), - }, - expected: 0, - }, - { - name: "given time range overlaps limitMax and is non zero, return capped duration", - args: args{ - start: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - end: time.Date(1998, 1, 1, 0, 0, 2, 0, time.UTC), - limitMin: time.Date(1990, 1, 1, 0, 0, 0, 0, time.UTC), - limitMax: time.Date(1998, 1, 1, 0, 0, 1, 0, time.UTC), - }, - expected: time.Second, - }, - { - name: "given time range overlaps limitMin and is non zero, return capped duration", - args: args{ - start: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - end: time.Date(1998, 1, 1, 0, 0, 2, 0, time.UTC), - limitMin: time.Date(1998, 1, 1, 0, 0, 1, 0, time.UTC), - limitMax: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), - }, - expected: time.Second, - }, - { - name: "given time range is larger than limits, return capped duration", - args: args{ - start: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - end: time.Date(1998, 1, 1, 0, 0, 10, 0, time.UTC), - limitMin: time.Date(1998, 1, 1, 0, 0, 1, 0, time.UTC), - limitMax: time.Date(1998, 1, 1, 0, 0, 9, 0, time.UTC), - }, - expected: 8 * time.Second, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - acc := &Accumulator{} - duration := acc.getTimeElapsedWithinLimits(tc.args.start, tc.args.end, tc.args.limitMin, tc.args.limitMax) - - require.Equal(t, tc.expected, duration) - }) - } - }) - t.Run("calculateNewRewards", func(t *testing.T) { - type args struct { - rewardsPerSecond sdk.Coins - duration time.Duration - totalSourceShares sdk.Dec - } - testcases := []struct { - name string - args args - expected RewardIndexes - }{ - { - name: "rewards calculated normally", - args: args{ - rewardsPerSecond: cs(c("hard", 1000), c("swap", 100)), - duration: 10 * time.Second, - totalSourceShares: d("1000"), - }, - expected: RewardIndexes{ - {CollateralType: "hard", RewardFactor: d("10")}, - {CollateralType: "swap", RewardFactor: d("1")}, - }, - }, - { - name: "duration is rounded to nearest even second", - args: args{ - rewardsPerSecond: cs(c("hard", 1000)), - duration: 10*time.Second + 500*time.Millisecond, - totalSourceShares: d("1000"), - }, - expected: RewardIndexes{ - {CollateralType: "hard", RewardFactor: d("10")}, - }, - }, - { - name: "reward indexes have enough precision for extreme params", - args: args{ - rewardsPerSecond: cs(c("anydenom", 1)), // minimum possible rewards - duration: 1 * time.Second, // minimum possible duration (beyond zero as it's rounded) - totalSourceShares: d("100000000000000000"), // approximate shares in a $1B pool of 10^8 precision assets - }, - expected: RewardIndexes{ - // smallest reward amount over smallest accumulation duration does not go past 10^-18 decimal precision - {CollateralType: "anydenom", RewardFactor: d("0.000000000000000010")}, - }, - }, - { - name: "when duration is zero there is no rewards", - args: args{ - rewardsPerSecond: cs(c("hard", 1000)), - duration: 0, - totalSourceShares: d("1000"), - }, - expected: nil, - }, - { - name: "when rewards per second are nil there is no rewards", - args: args{ - rewardsPerSecond: cs(), - duration: 10 * time.Second, - totalSourceShares: d("1000"), - }, - expected: nil, - }, - { - name: "when the source total is zero there is no rewards", - args: args{ - rewardsPerSecond: cs(c("hard", 1000)), - duration: 10 * time.Second, - totalSourceShares: d("0"), - }, - expected: nil, - }, - { - name: "when all args are zero there is no rewards", - args: args{ - rewardsPerSecond: cs(), - duration: 0, - totalSourceShares: d("0"), - }, - expected: nil, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - acc := &Accumulator{} - indexes := acc.calculateNewRewards( - sdk.NewDecCoinsFromCoins(tc.args.rewardsPerSecond...), - tc.args.totalSourceShares, - tc.args.duration, - ) - - require.Equal(t, tc.expected, indexes) - }) - } - }) - t.Run("Accumulate", func(t *testing.T) { - type args struct { - accumulator Accumulator - period MultiRewardPeriod - totalSourceShares sdk.Dec - currentTime time.Time - } - testcases := []struct { - name string - args args - expected Accumulator - }{ - { - name: "normal", - args: args{ - accumulator: Accumulator{ - PreviousAccumulationTime: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - Indexes: RewardIndexes{ - {CollateralType: "hard", RewardFactor: d("0.1")}, - {CollateralType: "swap", RewardFactor: d("0.2")}, - }, - }, - period: MultiRewardPeriod{ - Start: time.Date(1990, 1, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: cs(c("hard", 1000)), - }, - totalSourceShares: d("1000"), - currentTime: time.Date(1998, 1, 1, 0, 0, 5, 0, time.UTC), - }, - expected: Accumulator{ - PreviousAccumulationTime: time.Date(1998, 1, 1, 0, 0, 5, 0, time.UTC), - Indexes: RewardIndexes{ - {CollateralType: "hard", RewardFactor: d("5.1")}, - {CollateralType: "swap", RewardFactor: d("0.2")}, - }, - }, - }, - { - name: "empty reward indexes are added to correctly", - args: args{ - accumulator: Accumulator{ - PreviousAccumulationTime: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - Indexes: RewardIndexes{}, - }, - period: MultiRewardPeriod{ - Start: time.Date(1990, 1, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: cs(c("hard", 1000)), - }, - totalSourceShares: d("1000"), - currentTime: time.Date(1998, 1, 1, 0, 0, 5, 0, time.UTC), - }, - expected: Accumulator{ - PreviousAccumulationTime: time.Date(1998, 1, 1, 0, 0, 5, 0, time.UTC), - Indexes: RewardIndexes{{CollateralType: "hard", RewardFactor: d("5.0")}}, - }, - }, - { - name: "empty reward indexes are unchanged when there's no rewards", - args: args{ - accumulator: Accumulator{ - PreviousAccumulationTime: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - Indexes: RewardIndexes{}, - }, - period: MultiRewardPeriod{ - Start: time.Date(1990, 1, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: cs(), - }, - totalSourceShares: d("1000"), - currentTime: time.Date(1998, 1, 1, 0, 0, 5, 0, time.UTC), - }, - expected: Accumulator{ - PreviousAccumulationTime: time.Date(1998, 1, 1, 0, 0, 5, 0, time.UTC), - Indexes: RewardIndexes{}, - }, - }, - { - name: "when a period is enclosed within block the accumulation time is set to the period end time", - args: args{ - accumulator: Accumulator{ - PreviousAccumulationTime: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - Indexes: RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.1")}}, - }, - period: MultiRewardPeriod{ - Start: time.Date(1998, 1, 1, 0, 0, 5, 0, time.UTC), - End: time.Date(1998, 1, 1, 0, 0, 7, 0, time.UTC), - RewardsPerSecond: cs(c("hard", 1000)), - }, - totalSourceShares: d("1000"), - currentTime: time.Date(1998, 1, 1, 0, 0, 10, 0, time.UTC), - }, - expected: Accumulator{ - PreviousAccumulationTime: time.Date(1998, 1, 1, 0, 0, 7, 0, time.UTC), - Indexes: RewardIndexes{{CollateralType: "hard", RewardFactor: d("2.1")}}, - }, - }, - { - name: "accumulation duration is capped at param start when previous stored time is in the distant past", - // This could happend in the default time value time.Time{} was accidentally stored, or if a reward period was - // removed from the params, then added back a long time later. - args: args{ - accumulator: Accumulator{ - PreviousAccumulationTime: time.Time{}, - Indexes: RewardIndexes{{CollateralType: "hard", RewardFactor: d("0.1")}}, - }, - period: MultiRewardPeriod{ - Start: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - End: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), - RewardsPerSecond: cs(c("hard", 1000)), - }, - totalSourceShares: d("1000"), - currentTime: time.Date(1998, 1, 1, 0, 0, 10, 0, time.UTC), - }, - expected: Accumulator{ - PreviousAccumulationTime: time.Date(1998, 1, 1, 0, 0, 10, 0, time.UTC), - Indexes: RewardIndexes{{CollateralType: "hard", RewardFactor: d("10.1")}}, - }, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - tc.args.accumulator.Accumulate(tc.args.period, tc.args.totalSourceShares, tc.args.currentTime) - require.Equal(t, tc.expected, tc.args.accumulator) - }) - } - }) -} - -func TestMinTime(t *testing.T) { - type args struct { - t1, t2 time.Time - } - testcases := []struct { - name string - args args - expected time.Time - }{ - { - name: "last arg greater than first", - args: args{ - t1: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - t2: time.Date(1998, 1, 1, 0, 0, 0, 1, time.UTC), - }, - expected: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - { - name: "first arg greater than last", - args: args{ - t2: time.Date(1998, 1, 1, 0, 0, 0, 1, time.UTC), - t1: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - expected: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - { - name: "first and last args equal", - args: args{ - t2: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - t1: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - expected: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - require.Equal(t, tc.expected, minTime(tc.args.t1, tc.args.t2)) - }) - } -} - -func TestMaxTime(t *testing.T) { - type args struct { - t1, t2 time.Time - } - testcases := []struct { - name string - args args - expected time.Time - }{ - { - name: "last arg greater than first", - args: args{ - t1: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - t2: time.Date(1998, 1, 1, 0, 0, 0, 1, time.UTC), - }, - expected: time.Date(1998, 1, 1, 0, 0, 0, 1, time.UTC), - }, - { - name: "first arg greater than last", - args: args{ - t2: time.Date(1998, 1, 1, 0, 0, 0, 1, time.UTC), - t1: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - expected: time.Date(1998, 1, 1, 0, 0, 0, 1, time.UTC), - }, - { - name: "first and last args equal", - args: args{ - t2: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - t1: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - expected: time.Date(1998, 1, 1, 0, 0, 0, 0, time.UTC), - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - require.Equal(t, tc.expected, maxTime(tc.args.t1, tc.args.t2)) - }) - } -} diff --git a/x/incentive/types/apy.go b/x/incentive/types/apy.go deleted file mode 100644 index d7e54462..00000000 --- a/x/incentive/types/apy.go +++ /dev/null @@ -1,14 +0,0 @@ -package types - -import sdk "github.com/cosmos/cosmos-sdk/types" - -// NewAPY returns a new instance of APY -func NewAPY(collateralType string, apy sdk.Dec) Apy { - return Apy{ - CollateralType: collateralType, - Apy: apy, - } -} - -// APYs is a slice of APY -type APYs []Apy diff --git a/x/incentive/types/apy.pb.go b/x/incentive/types/apy.pb.go deleted file mode 100644 index 97304b7e..00000000 --- a/x/incentive/types/apy.pb.go +++ /dev/null @@ -1,372 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/incentive/v1beta1/apy.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// Apy contains the calculated APY for a given collateral type at a specific -// instant in time. -type Apy struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Apy github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=apy,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"apy"` -} - -func (m *Apy) Reset() { *m = Apy{} } -func (m *Apy) String() string { return proto.CompactTextString(m) } -func (*Apy) ProtoMessage() {} -func (*Apy) Descriptor() ([]byte, []int) { - return fileDescriptor_b2c1ad571f25cae9, []int{0} -} -func (m *Apy) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Apy) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Apy.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Apy) XXX_Merge(src proto.Message) { - xxx_messageInfo_Apy.Merge(m, src) -} -func (m *Apy) XXX_Size() int { - return m.Size() -} -func (m *Apy) XXX_DiscardUnknown() { - xxx_messageInfo_Apy.DiscardUnknown(m) -} - -var xxx_messageInfo_Apy proto.InternalMessageInfo - -func (m *Apy) GetCollateralType() string { - if m != nil { - return m.CollateralType - } - return "" -} - -func init() { - proto.RegisterType((*Apy)(nil), "kava.incentive.v1beta1.Apy") -} - -func init() { proto.RegisterFile("kava/incentive/v1beta1/apy.proto", fileDescriptor_b2c1ad571f25cae9) } - -var fileDescriptor_b2c1ad571f25cae9 = []byte{ - // 254 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xc8, 0x4e, 0x2c, 0x4b, - 0xd4, 0xcf, 0xcc, 0x4b, 0x4e, 0xcd, 0x2b, 0xc9, 0x2c, 0x4b, 0xd5, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, - 0x49, 0x34, 0xd4, 0x4f, 0x2c, 0xa8, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x03, 0xa9, - 0xd0, 0x83, 0xab, 0xd0, 0x83, 0xaa, 0x90, 0x92, 0x4c, 0xce, 0x2f, 0xce, 0xcd, 0x2f, 0x8e, 0x07, - 0xab, 0xd2, 0x87, 0x70, 0x20, 0x5a, 0xa4, 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0x21, 0xe2, 0x20, 0x16, - 0x44, 0x54, 0xa9, 0x8e, 0x8b, 0xd9, 0xb1, 0xa0, 0x52, 0x48, 0x9d, 0x8b, 0x3f, 0x39, 0x3f, 0x27, - 0x27, 0xb1, 0x24, 0xb5, 0x28, 0x31, 0x27, 0xbe, 0xa4, 0xb2, 0x20, 0x55, 0x82, 0x51, 0x81, 0x51, - 0x83, 0x33, 0x88, 0x0f, 0x21, 0x1c, 0x52, 0x59, 0x90, 0x2a, 0xe4, 0xc7, 0xc5, 0x9c, 0x58, 0x50, - 0x29, 0xc1, 0x04, 0x92, 0x74, 0xb2, 0x39, 0x71, 0x4f, 0x9e, 0xe1, 0xd6, 0x3d, 0x79, 0xb5, 0xf4, - 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0xa8, 0x9d, 0x50, 0x4a, 0xb7, 0x38, 0x25, - 0x5b, 0x1f, 0x64, 0x5a, 0xb1, 0x9e, 0x4b, 0x6a, 0xf2, 0xa5, 0x2d, 0xba, 0x5c, 0x50, 0x27, 0xb9, - 0xa4, 0x26, 0x07, 0x81, 0x0c, 0x72, 0x72, 0x3b, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, - 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, - 0x86, 0x28, 0x1d, 0x24, 0x43, 0x0d, 0xd2, 0x73, 0x12, 0x93, 0x8a, 0xf5, 0x0d, 0xd2, 0x75, 0x93, - 0x33, 0x12, 0x33, 0xf3, 0xf4, 0x2b, 0x90, 0x02, 0x07, 0x6c, 0x7c, 0x12, 0x1b, 0xd8, 0x3b, 0xc6, - 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x6c, 0x70, 0x97, 0xf8, 0x3b, 0x01, 0x00, 0x00, -} - -func (m *Apy) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Apy) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Apy) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Apy.Size() - i -= size - if _, err := m.Apy.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintApy(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintApy(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintApy(dAtA []byte, offset int, v uint64) int { - offset -= sovApy(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Apy) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovApy(uint64(l)) - } - l = m.Apy.Size() - n += 1 + l + sovApy(uint64(l)) - return n -} - -func sovApy(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozApy(x uint64) (n int) { - return sovApy(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Apy) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowApy - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Apy: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Apy: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowApy - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthApy - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthApy - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Apy", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowApy - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthApy - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthApy - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Apy.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipApy(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthApy - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipApy(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowApy - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowApy - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowApy - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthApy - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupApy - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthApy - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthApy = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowApy = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupApy = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/incentive/types/claims.go b/x/incentive/types/claims.go deleted file mode 100644 index ac7bc5f6..00000000 --- a/x/incentive/types/claims.go +++ /dev/null @@ -1,636 +0,0 @@ -package types - -import ( - "errors" - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - USDXMintingClaimType = "usdx_minting" - HardLiquidityProviderClaimType = "hard_liquidity_provider" - DelegatorClaimType = "delegator_claim" - SwapClaimType = "swap" - SavingsClaimType = "savings" - EarnClaimType = "earn" -) - -// GetOwner is a getter for Claim Owner -func (c BaseClaim) GetOwner() sdk.AccAddress { return c.Owner } - -// GetReward is a getter for Claim Reward -func (c BaseClaim) GetReward() sdk.Coin { return c.Reward } - -// GetType returns the claim type, used to identify auctions in event attributes -func (c BaseClaim) GetType() string { return "base" } - -// Validate performs a basic check of a BaseClaim fields -func (c BaseClaim) Validate() error { - if c.Owner.Empty() { - return errors.New("claim owner cannot be empty") - } - if !c.Reward.IsValid() { - return fmt.Errorf("invalid reward amount: %s", c.Reward) - } - return nil -} - -// GetOwner is a getter for Claim Owner -func (c BaseMultiClaim) GetOwner() sdk.AccAddress { return c.Owner } - -// GetReward is a getter for Claim Reward -func (c BaseMultiClaim) GetReward() sdk.Coins { return c.Reward } - -// GetType returns the claim type, used to identify auctions in event attributes -func (c BaseMultiClaim) GetType() string { return "base" } - -// Validate performs a basic check of a BaseClaim fields -func (c BaseMultiClaim) Validate() error { - if c.Owner.Empty() { - return errors.New("claim owner cannot be empty") - } - if !c.Reward.IsValid() { - return fmt.Errorf("invalid reward amount: %s", c.Reward) - } - return nil -} - -// NewUSDXMintingClaim returns a new USDXMintingClaim -func NewUSDXMintingClaim(owner sdk.AccAddress, reward sdk.Coin, rewardIndexes RewardIndexes) USDXMintingClaim { - return USDXMintingClaim{ - BaseClaim: BaseClaim{ - Owner: owner, - Reward: reward, - }, - RewardIndexes: rewardIndexes, - } -} - -// GetType returns the claim's type -func (c USDXMintingClaim) GetType() string { return USDXMintingClaimType } - -// GetReward returns the claim's reward coin -func (c USDXMintingClaim) GetReward() sdk.Coin { return c.Reward } - -// GetOwner returns the claim's owner -func (c USDXMintingClaim) GetOwner() sdk.AccAddress { return c.Owner } - -// Validate performs a basic check of a Claim fields -func (c USDXMintingClaim) Validate() error { - if err := c.RewardIndexes.Validate(); err != nil { - return err - } - - return c.BaseClaim.Validate() -} - -// HasRewardIndex check if a claim has a reward index for the input collateral type -func (c USDXMintingClaim) HasRewardIndex(collateralType string) (int64, bool) { - for index, ri := range c.RewardIndexes { - if ri.CollateralType == collateralType { - return int64(index), true - } - } - return 0, false -} - -// USDXMintingClaims slice of USDXMintingClaim -type USDXMintingClaims []USDXMintingClaim - -// Validate checks if all the claims are valid and there are no duplicated -// entries. -func (cs USDXMintingClaims) Validate() error { - for _, c := range cs { - if err := c.Validate(); err != nil { - return err - } - } - - return nil -} - -// NewHardLiquidityProviderClaim returns a new HardLiquidityProviderClaim -func NewHardLiquidityProviderClaim(owner sdk.AccAddress, rewards sdk.Coins, - supplyRewardIndexes, borrowRewardIndexes MultiRewardIndexes, -) HardLiquidityProviderClaim { - return HardLiquidityProviderClaim{ - BaseMultiClaim: BaseMultiClaim{ - Owner: owner, - Reward: rewards, - }, - SupplyRewardIndexes: supplyRewardIndexes, - BorrowRewardIndexes: borrowRewardIndexes, - } -} - -// GetType returns the claim's type -func (c HardLiquidityProviderClaim) GetType() string { return HardLiquidityProviderClaimType } - -// GetReward returns the claim's reward coin -func (c HardLiquidityProviderClaim) GetReward() sdk.Coins { return c.Reward } - -// GetOwner returns the claim's owner -func (c HardLiquidityProviderClaim) GetOwner() sdk.AccAddress { return c.Owner } - -// Validate performs a basic check of a HardLiquidityProviderClaim fields -func (c HardLiquidityProviderClaim) Validate() error { - if err := c.SupplyRewardIndexes.Validate(); err != nil { - return err - } - - if err := c.BorrowRewardIndexes.Validate(); err != nil { - return err - } - - return c.BaseMultiClaim.Validate() -} - -// HasSupplyRewardIndex check if a claim has a supply reward index for the input collateral type -func (c HardLiquidityProviderClaim) HasSupplyRewardIndex(denom string) (int64, bool) { - for index, ri := range c.SupplyRewardIndexes { - if ri.CollateralType == denom { - return int64(index), true - } - } - return 0, false -} - -// HasBorrowRewardIndex check if a claim has a borrow reward index for the input collateral type -func (c HardLiquidityProviderClaim) HasBorrowRewardIndex(denom string) (int64, bool) { - for index, ri := range c.BorrowRewardIndexes { - if ri.CollateralType == denom { - return int64(index), true - } - } - return 0, false -} - -// HardLiquidityProviderClaims slice of HardLiquidityProviderClaim -type HardLiquidityProviderClaims []HardLiquidityProviderClaim - -// Validate checks if all the claims are valid and there are no duplicated -// entries. -func (cs HardLiquidityProviderClaims) Validate() error { - for _, c := range cs { - if err := c.Validate(); err != nil { - return err - } - } - - return nil -} - -// NewDelegatorClaim returns a new DelegatorClaim -func NewDelegatorClaim(owner sdk.AccAddress, rewards sdk.Coins, rewardIndexes MultiRewardIndexes) DelegatorClaim { - return DelegatorClaim{ - BaseMultiClaim: BaseMultiClaim{ - Owner: owner, - Reward: rewards, - }, - RewardIndexes: rewardIndexes, - } -} - -// GetType returns the claim's type -func (c DelegatorClaim) GetType() string { return DelegatorClaimType } - -// GetReward returns the claim's reward coin -func (c DelegatorClaim) GetReward() sdk.Coins { return c.Reward } - -// GetOwner returns the claim's owner -func (c DelegatorClaim) GetOwner() sdk.AccAddress { return c.Owner } - -// Validate performs a basic check of a DelegatorClaim fields -func (c DelegatorClaim) Validate() error { - if err := c.RewardIndexes.Validate(); err != nil { - return err - } - - return c.BaseMultiClaim.Validate() -} - -// HasRewardIndex checks if a DelegatorClaim has a reward index for the input collateral type -func (c DelegatorClaim) HasRewardIndex(collateralType string) (int64, bool) { - for index, ri := range c.RewardIndexes { - if ri.CollateralType == collateralType { - return int64(index), true - } - } - return 0, false -} - -// DelegatorClaim slice of DelegatorClaim -type DelegatorClaims []DelegatorClaim - -// Validate checks if all the claims are valid and there are no duplicated -// entries. -func (cs DelegatorClaims) Validate() error { - for _, c := range cs { - if err := c.Validate(); err != nil { - return err - } - } - - return nil -} - -// NewSwapClaim returns a new SwapClaim -func NewSwapClaim(owner sdk.AccAddress, rewards sdk.Coins, rewardIndexes MultiRewardIndexes) SwapClaim { - return SwapClaim{ - BaseMultiClaim: BaseMultiClaim{ - Owner: owner, - Reward: rewards, - }, - RewardIndexes: rewardIndexes, - } -} - -// GetType returns the claim's type -func (c SwapClaim) GetType() string { return SwapClaimType } - -// GetReward returns the claim's reward coin -func (c SwapClaim) GetReward() sdk.Coins { return c.Reward } - -// GetOwner returns the claim's owner -func (c SwapClaim) GetOwner() sdk.AccAddress { return c.Owner } - -// Validate performs a basic check of a SwapClaim fields -func (c SwapClaim) Validate() error { - if err := c.RewardIndexes.Validate(); err != nil { - return err - } - return c.BaseMultiClaim.Validate() -} - -// HasRewardIndex check if a claim has a reward index for the input pool ID. -func (c SwapClaim) HasRewardIndex(poolID string) (int64, bool) { - for index, ri := range c.RewardIndexes { - if ri.CollateralType == poolID { - return int64(index), true - } - } - return 0, false -} - -// SwapClaims slice of SwapClaim -type SwapClaims []SwapClaim - -// Validate checks if all the claims are valid. -func (cs SwapClaims) Validate() error { - for _, c := range cs { - if err := c.Validate(); err != nil { - return err - } - } - - return nil -} - -// NewSavingsClaim returns a new SavingsClaim -func NewSavingsClaim(owner sdk.AccAddress, rewards sdk.Coins, rewardIndexes MultiRewardIndexes) SavingsClaim { - return SavingsClaim{ - BaseMultiClaim: BaseMultiClaim{ - Owner: owner, - Reward: rewards, - }, - RewardIndexes: rewardIndexes, - } -} - -// GetType returns the claim's type -func (c SavingsClaim) GetType() string { return SavingsClaimType } - -// GetReward returns the claim's reward coin -func (c SavingsClaim) GetReward() sdk.Coins { return c.Reward } - -// GetOwner returns the claim's owner -func (c SavingsClaim) GetOwner() sdk.AccAddress { return c.Owner } - -// Validate performs a basic check of a SavingsClaim fields -func (c SavingsClaim) Validate() error { - if err := c.RewardIndexes.Validate(); err != nil { - return err - } - return c.BaseMultiClaim.Validate() -} - -// HasRewardIndex check if a claim has a reward index for the input denom -func (c SavingsClaim) HasRewardIndex(denom string) (int64, bool) { - for index, ri := range c.RewardIndexes { - if ri.CollateralType == denom { - return int64(index), true - } - } - return 0, false -} - -// SavingsClaims slice of SavingsClaim -type SavingsClaims []SavingsClaim - -// Validate checks if all the claims are valid. -func (cs SavingsClaims) Validate() error { - for _, c := range cs { - if err := c.Validate(); err != nil { - return err - } - } - - return nil -} - -// NewEarnClaim returns a new EarnClaim -func NewEarnClaim(owner sdk.AccAddress, rewards sdk.Coins, rewardIndexes MultiRewardIndexes) EarnClaim { - return EarnClaim{ - BaseMultiClaim: BaseMultiClaim{ - Owner: owner, - Reward: rewards, - }, - RewardIndexes: rewardIndexes, - } -} - -// GetType returns the claim's type -func (c EarnClaim) GetType() string { return EarnClaimType } - -// GetReward returns the claim's reward coin -func (c EarnClaim) GetReward() sdk.Coins { return c.Reward } - -// GetOwner returns the claim's owner -func (c EarnClaim) GetOwner() sdk.AccAddress { return c.Owner } - -// Validate performs a basic check of a SwapClaim fields -func (c EarnClaim) Validate() error { - if err := c.RewardIndexes.Validate(); err != nil { - return err - } - return c.BaseMultiClaim.Validate() -} - -// HasRewardIndex check if a claim has a reward index for the input pool ID. -func (c EarnClaim) HasRewardIndex(poolID string) (int64, bool) { - for index, ri := range c.RewardIndexes { - if ri.CollateralType == poolID { - return int64(index), true - } - } - return 0, false -} - -// EarnClaims slice of EarnClaim -type EarnClaims []EarnClaim - -// Validate checks if all the claims are valid. -func (cs EarnClaims) Validate() error { - for _, c := range cs { - if err := c.Validate(); err != nil { - return err - } - } - - return nil -} - -// ---------------------- Reward indexes are used internally in the store ---------------------- - -// NewRewardIndex returns a new RewardIndex -func NewRewardIndex(collateralType string, factor sdk.Dec) RewardIndex { - return RewardIndex{ - CollateralType: collateralType, - RewardFactor: factor, - } -} - -// Validate validates reward index -func (ri RewardIndex) Validate() error { - if ri.RewardFactor.IsNegative() { - return fmt.Errorf("reward factor value should be positive, is %s for %s", ri.RewardFactor, ri.CollateralType) - } - if strings.TrimSpace(ri.CollateralType) == "" { - return fmt.Errorf("collateral type should not be empty") - } - return nil -} - -// RewardIndexes slice of RewardIndex -type RewardIndexes []RewardIndex - -// GetRewardIndex fetches a RewardIndex by its denom -func (ris RewardIndexes) GetRewardIndex(denom string) (RewardIndex, bool) { - for _, ri := range ris { - if ri.CollateralType == denom { - return ri, true - } - } - return RewardIndex{}, false -} - -// Get fetches a RewardFactor by it's denom -func (ris RewardIndexes) Get(denom string) (sdk.Dec, bool) { - for _, ri := range ris { - if ri.CollateralType == denom { - return ri.RewardFactor, true - } - } - return sdk.Dec{}, false -} - -// With returns a copy of the indexes with a new reward factor added -func (ris RewardIndexes) With(denom string, factor sdk.Dec) RewardIndexes { - newIndexes := ris.copy() - - for i, ri := range newIndexes { - if ri.CollateralType == denom { - newIndexes[i].RewardFactor = factor - return newIndexes - } - } - return append(newIndexes, NewRewardIndex(denom, factor)) -} - -// GetFactorIndex gets the index of a specific reward index inside the array by its index -func (ris RewardIndexes) GetFactorIndex(denom string) (int, bool) { - for i, ri := range ris { - if ri.CollateralType == denom { - return i, true - } - } - return -1, false -} - -// Validate validation for reward indexes -func (ris RewardIndexes) Validate() error { - for _, ri := range ris { - if err := ri.Validate(); err != nil { - return err - } - } - return nil -} - -// Mul returns a copy of RewardIndexes with all factors multiplied by a single value. -func (ris RewardIndexes) Mul(multiplier sdk.Dec) RewardIndexes { - newIndexes := ris.copy() - - for i := range newIndexes { - newIndexes[i].RewardFactor = newIndexes[i].RewardFactor.Mul(multiplier) - } - return newIndexes -} - -// Quo returns a copy of RewardIndexes with all factors divided by a single value. -// It uses sdk.Dec.Quo for the division. -func (ris RewardIndexes) Quo(divisor sdk.Dec) RewardIndexes { - newIndexes := ris.copy() - - for i := range newIndexes { - newIndexes[i].RewardFactor = newIndexes[i].RewardFactor.Quo(divisor) - } - return newIndexes -} - -// Add combines two reward indexes by adding together factors with the same CollateralType. -// Any CollateralTypes unique to either reward indexes are included in the output as is. -func (ris RewardIndexes) Add(addend RewardIndexes) RewardIndexes { - newIndexes := ris.copy() - - for _, addRi := range addend { - found := false - for i, origRi := range newIndexes { - if origRi.CollateralType == addRi.CollateralType { - found = true - newIndexes[i].RewardFactor = newIndexes[i].RewardFactor.Add(addRi.RewardFactor) - } - } - if !found { - newIndexes = append(newIndexes, addRi) - } - } - return newIndexes -} - -// copy returns a copy of the reward indexes slice and underlying array -func (ris RewardIndexes) copy() RewardIndexes { - if ris == nil { // return nil rather than empty slice when ris is nil - return nil - } - newIndexes := make(RewardIndexes, len(ris)) - copy(newIndexes, ris) - return newIndexes -} - -// NewMultiRewardIndex returns a new MultiRewardIndex -func NewMultiRewardIndex(collateralType string, indexes RewardIndexes) MultiRewardIndex { - return MultiRewardIndex{ - CollateralType: collateralType, - RewardIndexes: indexes, - } -} - -// GetFactorIndex gets the index of a specific reward index inside the array by its index -func (mri MultiRewardIndex) GetFactorIndex(denom string) (int, bool) { - for i, ri := range mri.RewardIndexes { - if ri.CollateralType == denom { - return i, true - } - } - return -1, false -} - -// Validate validates multi-reward index -func (mri MultiRewardIndex) Validate() error { - for _, rf := range mri.RewardIndexes { - if rf.RewardFactor.IsNegative() { - return fmt.Errorf("reward index's factor value cannot be negative: %s", rf) - } - } - if strings.TrimSpace(mri.CollateralType) == "" { - return fmt.Errorf("collateral type should not be empty") - } - return nil -} - -// MultiRewardIndexes slice of MultiRewardIndex -type MultiRewardIndexes []MultiRewardIndex - -// GetRewardIndex fetches a RewardIndex from a MultiRewardIndex by its denom -func (mris MultiRewardIndexes) GetRewardIndex(denom string) (MultiRewardIndex, bool) { - for _, ri := range mris { - if ri.CollateralType == denom { - return ri, true - } - } - return MultiRewardIndex{}, false -} - -// Get fetches a RewardIndexes by it's denom -func (mris MultiRewardIndexes) Get(denom string) (RewardIndexes, bool) { - for _, mri := range mris { - if mri.CollateralType == denom { - return mri.RewardIndexes, true - } - } - return nil, false -} - -// GetRewardIndexIndex fetches a specific reward index inside the array by its denom -func (mris MultiRewardIndexes) GetRewardIndexIndex(denom string) (int, bool) { - for i, ri := range mris { - if ri.CollateralType == denom { - return i, true - } - } - return -1, false -} - -// With returns a copy of the indexes with a new RewardIndexes added -func (mris MultiRewardIndexes) With(denom string, indexes RewardIndexes) MultiRewardIndexes { - newIndexes := mris.copy() - - for i, mri := range newIndexes { - if mri.CollateralType == denom { - newIndexes[i].RewardIndexes = indexes - return newIndexes - } - } - return append(newIndexes, NewMultiRewardIndex(denom, indexes)) -} - -// GetCollateralTypes returns a slice of containing all collateral types -func (mris MultiRewardIndexes) GetCollateralTypes() []string { - var collateralTypes []string - for _, ri := range mris { - collateralTypes = append(collateralTypes, ri.CollateralType) - } - return collateralTypes -} - -// RemoveRewardIndex removes a denom's reward interest factor value -func (mris MultiRewardIndexes) RemoveRewardIndex(denom string) MultiRewardIndexes { - for i, ri := range mris { - if ri.CollateralType == denom { - // copy the slice and underlying array to avoid altering the original - copy := mris.copy() - return append(copy[:i], copy[i+1:]...) - } - } - return mris -} - -// Validate validation for reward indexes -func (mris MultiRewardIndexes) Validate() error { - for _, mri := range mris { - if err := mri.Validate(); err != nil { - return err - } - } - return nil -} - -// copy returns a copy of the slice and underlying array -func (mris MultiRewardIndexes) copy() MultiRewardIndexes { - newIndexes := make(MultiRewardIndexes, len(mris)) - copy(newIndexes, mris) - return newIndexes -} diff --git a/x/incentive/types/claims.pb.go b/x/incentive/types/claims.pb.go deleted file mode 100644 index 220bf48b..00000000 --- a/x/incentive/types/claims.pb.go +++ /dev/null @@ -1,2777 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/incentive/v1beta1/claims.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// BaseClaim is a claim with a single reward coin types -type BaseClaim struct { - Owner github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=owner,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"owner,omitempty"` - Reward types.Coin `protobuf:"bytes,2,opt,name=reward,proto3" json:"reward"` -} - -func (m *BaseClaim) Reset() { *m = BaseClaim{} } -func (m *BaseClaim) String() string { return proto.CompactTextString(m) } -func (*BaseClaim) ProtoMessage() {} -func (*BaseClaim) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{0} -} -func (m *BaseClaim) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *BaseClaim) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_BaseClaim.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *BaseClaim) XXX_Merge(src proto.Message) { - xxx_messageInfo_BaseClaim.Merge(m, src) -} -func (m *BaseClaim) XXX_Size() int { - return m.Size() -} -func (m *BaseClaim) XXX_DiscardUnknown() { - xxx_messageInfo_BaseClaim.DiscardUnknown(m) -} - -var xxx_messageInfo_BaseClaim proto.InternalMessageInfo - -// BaseMultiClaim is a claim with multiple reward coin types -type BaseMultiClaim struct { - Owner github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=owner,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"owner,omitempty"` - Reward github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=reward,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"reward"` -} - -func (m *BaseMultiClaim) Reset() { *m = BaseMultiClaim{} } -func (m *BaseMultiClaim) String() string { return proto.CompactTextString(m) } -func (*BaseMultiClaim) ProtoMessage() {} -func (*BaseMultiClaim) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{1} -} -func (m *BaseMultiClaim) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *BaseMultiClaim) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_BaseMultiClaim.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *BaseMultiClaim) XXX_Merge(src proto.Message) { - xxx_messageInfo_BaseMultiClaim.Merge(m, src) -} -func (m *BaseMultiClaim) XXX_Size() int { - return m.Size() -} -func (m *BaseMultiClaim) XXX_DiscardUnknown() { - xxx_messageInfo_BaseMultiClaim.DiscardUnknown(m) -} - -var xxx_messageInfo_BaseMultiClaim proto.InternalMessageInfo - -// RewardIndex stores reward accumulation information -type RewardIndex struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - RewardFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=reward_factor,json=rewardFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"reward_factor"` -} - -func (m *RewardIndex) Reset() { *m = RewardIndex{} } -func (m *RewardIndex) String() string { return proto.CompactTextString(m) } -func (*RewardIndex) ProtoMessage() {} -func (*RewardIndex) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{2} -} -func (m *RewardIndex) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *RewardIndex) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_RewardIndex.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *RewardIndex) XXX_Merge(src proto.Message) { - xxx_messageInfo_RewardIndex.Merge(m, src) -} -func (m *RewardIndex) XXX_Size() int { - return m.Size() -} -func (m *RewardIndex) XXX_DiscardUnknown() { - xxx_messageInfo_RewardIndex.DiscardUnknown(m) -} - -var xxx_messageInfo_RewardIndex proto.InternalMessageInfo - -// RewardIndexesProto defines a Protobuf wrapper around a RewardIndexes slice -type RewardIndexesProto struct { - RewardIndexes RewardIndexes `protobuf:"bytes,1,rep,name=reward_indexes,json=rewardIndexes,proto3,castrepeated=RewardIndexes" json:"reward_indexes"` -} - -func (m *RewardIndexesProto) Reset() { *m = RewardIndexesProto{} } -func (m *RewardIndexesProto) String() string { return proto.CompactTextString(m) } -func (*RewardIndexesProto) ProtoMessage() {} -func (*RewardIndexesProto) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{3} -} -func (m *RewardIndexesProto) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *RewardIndexesProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_RewardIndexesProto.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *RewardIndexesProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_RewardIndexesProto.Merge(m, src) -} -func (m *RewardIndexesProto) XXX_Size() int { - return m.Size() -} -func (m *RewardIndexesProto) XXX_DiscardUnknown() { - xxx_messageInfo_RewardIndexesProto.DiscardUnknown(m) -} - -var xxx_messageInfo_RewardIndexesProto proto.InternalMessageInfo - -// MultiRewardIndex stores reward accumulation information on multiple reward types -type MultiRewardIndex struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - RewardIndexes RewardIndexes `protobuf:"bytes,2,rep,name=reward_indexes,json=rewardIndexes,proto3,castrepeated=RewardIndexes" json:"reward_indexes"` -} - -func (m *MultiRewardIndex) Reset() { *m = MultiRewardIndex{} } -func (m *MultiRewardIndex) String() string { return proto.CompactTextString(m) } -func (*MultiRewardIndex) ProtoMessage() {} -func (*MultiRewardIndex) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{4} -} -func (m *MultiRewardIndex) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MultiRewardIndex) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MultiRewardIndex.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MultiRewardIndex) XXX_Merge(src proto.Message) { - xxx_messageInfo_MultiRewardIndex.Merge(m, src) -} -func (m *MultiRewardIndex) XXX_Size() int { - return m.Size() -} -func (m *MultiRewardIndex) XXX_DiscardUnknown() { - xxx_messageInfo_MultiRewardIndex.DiscardUnknown(m) -} - -var xxx_messageInfo_MultiRewardIndex proto.InternalMessageInfo - -// MultiRewardIndexesProto defines a Protobuf wrapper around a MultiRewardIndexes slice -type MultiRewardIndexesProto struct { - MultiRewardIndexes MultiRewardIndexes `protobuf:"bytes,1,rep,name=multi_reward_indexes,json=multiRewardIndexes,proto3,castrepeated=MultiRewardIndexes" json:"multi_reward_indexes"` -} - -func (m *MultiRewardIndexesProto) Reset() { *m = MultiRewardIndexesProto{} } -func (m *MultiRewardIndexesProto) String() string { return proto.CompactTextString(m) } -func (*MultiRewardIndexesProto) ProtoMessage() {} -func (*MultiRewardIndexesProto) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{5} -} -func (m *MultiRewardIndexesProto) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MultiRewardIndexesProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MultiRewardIndexesProto.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MultiRewardIndexesProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_MultiRewardIndexesProto.Merge(m, src) -} -func (m *MultiRewardIndexesProto) XXX_Size() int { - return m.Size() -} -func (m *MultiRewardIndexesProto) XXX_DiscardUnknown() { - xxx_messageInfo_MultiRewardIndexesProto.DiscardUnknown(m) -} - -var xxx_messageInfo_MultiRewardIndexesProto proto.InternalMessageInfo - -// USDXMintingClaim is for USDX minting rewards -type USDXMintingClaim struct { - BaseClaim `protobuf:"bytes,1,opt,name=base_claim,json=baseClaim,proto3,embedded=base_claim" json:"base_claim"` - RewardIndexes RewardIndexes `protobuf:"bytes,2,rep,name=reward_indexes,json=rewardIndexes,proto3,castrepeated=RewardIndexes" json:"reward_indexes"` -} - -func (m *USDXMintingClaim) Reset() { *m = USDXMintingClaim{} } -func (m *USDXMintingClaim) String() string { return proto.CompactTextString(m) } -func (*USDXMintingClaim) ProtoMessage() {} -func (*USDXMintingClaim) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{6} -} -func (m *USDXMintingClaim) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *USDXMintingClaim) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_USDXMintingClaim.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *USDXMintingClaim) XXX_Merge(src proto.Message) { - xxx_messageInfo_USDXMintingClaim.Merge(m, src) -} -func (m *USDXMintingClaim) XXX_Size() int { - return m.Size() -} -func (m *USDXMintingClaim) XXX_DiscardUnknown() { - xxx_messageInfo_USDXMintingClaim.DiscardUnknown(m) -} - -var xxx_messageInfo_USDXMintingClaim proto.InternalMessageInfo - -// HardLiquidityProviderClaim stores the hard liquidity provider rewards that can be claimed by owner -type HardLiquidityProviderClaim struct { - BaseMultiClaim `protobuf:"bytes,1,opt,name=base_claim,json=baseClaim,proto3,embedded=base_claim" json:"base_claim"` - SupplyRewardIndexes MultiRewardIndexes `protobuf:"bytes,2,rep,name=supply_reward_indexes,json=supplyRewardIndexes,proto3,castrepeated=MultiRewardIndexes" json:"supply_reward_indexes"` - BorrowRewardIndexes MultiRewardIndexes `protobuf:"bytes,3,rep,name=borrow_reward_indexes,json=borrowRewardIndexes,proto3,castrepeated=MultiRewardIndexes" json:"borrow_reward_indexes"` -} - -func (m *HardLiquidityProviderClaim) Reset() { *m = HardLiquidityProviderClaim{} } -func (m *HardLiquidityProviderClaim) String() string { return proto.CompactTextString(m) } -func (*HardLiquidityProviderClaim) ProtoMessage() {} -func (*HardLiquidityProviderClaim) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{7} -} -func (m *HardLiquidityProviderClaim) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *HardLiquidityProviderClaim) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_HardLiquidityProviderClaim.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *HardLiquidityProviderClaim) XXX_Merge(src proto.Message) { - xxx_messageInfo_HardLiquidityProviderClaim.Merge(m, src) -} -func (m *HardLiquidityProviderClaim) XXX_Size() int { - return m.Size() -} -func (m *HardLiquidityProviderClaim) XXX_DiscardUnknown() { - xxx_messageInfo_HardLiquidityProviderClaim.DiscardUnknown(m) -} - -var xxx_messageInfo_HardLiquidityProviderClaim proto.InternalMessageInfo - -// DelegatorClaim stores delegation rewards that can be claimed by owner -type DelegatorClaim struct { - BaseMultiClaim `protobuf:"bytes,1,opt,name=base_claim,json=baseClaim,proto3,embedded=base_claim" json:"base_claim"` - RewardIndexes MultiRewardIndexes `protobuf:"bytes,2,rep,name=reward_indexes,json=rewardIndexes,proto3,castrepeated=MultiRewardIndexes" json:"reward_indexes"` -} - -func (m *DelegatorClaim) Reset() { *m = DelegatorClaim{} } -func (m *DelegatorClaim) String() string { return proto.CompactTextString(m) } -func (*DelegatorClaim) ProtoMessage() {} -func (*DelegatorClaim) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{8} -} -func (m *DelegatorClaim) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DelegatorClaim) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DelegatorClaim.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *DelegatorClaim) XXX_Merge(src proto.Message) { - xxx_messageInfo_DelegatorClaim.Merge(m, src) -} -func (m *DelegatorClaim) XXX_Size() int { - return m.Size() -} -func (m *DelegatorClaim) XXX_DiscardUnknown() { - xxx_messageInfo_DelegatorClaim.DiscardUnknown(m) -} - -var xxx_messageInfo_DelegatorClaim proto.InternalMessageInfo - -// SwapClaim stores the swap rewards that can be claimed by owner -type SwapClaim struct { - BaseMultiClaim `protobuf:"bytes,1,opt,name=base_claim,json=baseClaim,proto3,embedded=base_claim" json:"base_claim"` - RewardIndexes MultiRewardIndexes `protobuf:"bytes,2,rep,name=reward_indexes,json=rewardIndexes,proto3,castrepeated=MultiRewardIndexes" json:"reward_indexes"` -} - -func (m *SwapClaim) Reset() { *m = SwapClaim{} } -func (m *SwapClaim) String() string { return proto.CompactTextString(m) } -func (*SwapClaim) ProtoMessage() {} -func (*SwapClaim) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{9} -} -func (m *SwapClaim) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *SwapClaim) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SwapClaim.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *SwapClaim) XXX_Merge(src proto.Message) { - xxx_messageInfo_SwapClaim.Merge(m, src) -} -func (m *SwapClaim) XXX_Size() int { - return m.Size() -} -func (m *SwapClaim) XXX_DiscardUnknown() { - xxx_messageInfo_SwapClaim.DiscardUnknown(m) -} - -var xxx_messageInfo_SwapClaim proto.InternalMessageInfo - -// SavingsClaim stores the savings rewards that can be claimed by owner -type SavingsClaim struct { - BaseMultiClaim `protobuf:"bytes,1,opt,name=base_claim,json=baseClaim,proto3,embedded=base_claim" json:"base_claim"` - RewardIndexes MultiRewardIndexes `protobuf:"bytes,2,rep,name=reward_indexes,json=rewardIndexes,proto3,castrepeated=MultiRewardIndexes" json:"reward_indexes"` -} - -func (m *SavingsClaim) Reset() { *m = SavingsClaim{} } -func (m *SavingsClaim) String() string { return proto.CompactTextString(m) } -func (*SavingsClaim) ProtoMessage() {} -func (*SavingsClaim) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{10} -} -func (m *SavingsClaim) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *SavingsClaim) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SavingsClaim.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *SavingsClaim) XXX_Merge(src proto.Message) { - xxx_messageInfo_SavingsClaim.Merge(m, src) -} -func (m *SavingsClaim) XXX_Size() int { - return m.Size() -} -func (m *SavingsClaim) XXX_DiscardUnknown() { - xxx_messageInfo_SavingsClaim.DiscardUnknown(m) -} - -var xxx_messageInfo_SavingsClaim proto.InternalMessageInfo - -// EarnClaim stores the earn rewards that can be claimed by owner -type EarnClaim struct { - BaseMultiClaim `protobuf:"bytes,1,opt,name=base_claim,json=baseClaim,proto3,embedded=base_claim" json:"base_claim"` - RewardIndexes MultiRewardIndexes `protobuf:"bytes,2,rep,name=reward_indexes,json=rewardIndexes,proto3,castrepeated=MultiRewardIndexes" json:"reward_indexes"` -} - -func (m *EarnClaim) Reset() { *m = EarnClaim{} } -func (m *EarnClaim) String() string { return proto.CompactTextString(m) } -func (*EarnClaim) ProtoMessage() {} -func (*EarnClaim) Descriptor() ([]byte, []int) { - return fileDescriptor_5f7515029623a895, []int{11} -} -func (m *EarnClaim) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *EarnClaim) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_EarnClaim.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *EarnClaim) XXX_Merge(src proto.Message) { - xxx_messageInfo_EarnClaim.Merge(m, src) -} -func (m *EarnClaim) XXX_Size() int { - return m.Size() -} -func (m *EarnClaim) XXX_DiscardUnknown() { - xxx_messageInfo_EarnClaim.DiscardUnknown(m) -} - -var xxx_messageInfo_EarnClaim proto.InternalMessageInfo - -func init() { - proto.RegisterType((*BaseClaim)(nil), "kava.incentive.v1beta1.BaseClaim") - proto.RegisterType((*BaseMultiClaim)(nil), "kava.incentive.v1beta1.BaseMultiClaim") - proto.RegisterType((*RewardIndex)(nil), "kava.incentive.v1beta1.RewardIndex") - proto.RegisterType((*RewardIndexesProto)(nil), "kava.incentive.v1beta1.RewardIndexesProto") - proto.RegisterType((*MultiRewardIndex)(nil), "kava.incentive.v1beta1.MultiRewardIndex") - proto.RegisterType((*MultiRewardIndexesProto)(nil), "kava.incentive.v1beta1.MultiRewardIndexesProto") - proto.RegisterType((*USDXMintingClaim)(nil), "kava.incentive.v1beta1.USDXMintingClaim") - proto.RegisterType((*HardLiquidityProviderClaim)(nil), "kava.incentive.v1beta1.HardLiquidityProviderClaim") - proto.RegisterType((*DelegatorClaim)(nil), "kava.incentive.v1beta1.DelegatorClaim") - proto.RegisterType((*SwapClaim)(nil), "kava.incentive.v1beta1.SwapClaim") - proto.RegisterType((*SavingsClaim)(nil), "kava.incentive.v1beta1.SavingsClaim") - proto.RegisterType((*EarnClaim)(nil), "kava.incentive.v1beta1.EarnClaim") -} - -func init() { - proto.RegisterFile("kava/incentive/v1beta1/claims.proto", fileDescriptor_5f7515029623a895) -} - -var fileDescriptor_5f7515029623a895 = []byte{ - // 693 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xdc, 0x56, 0xcf, 0x4e, 0x13, 0x41, - 0x18, 0xef, 0x80, 0x10, 0x3b, 0x94, 0x4a, 0x16, 0x50, 0xe8, 0x61, 0x8b, 0x25, 0xc1, 0x1e, 0xec, - 0x2e, 0xe0, 0xc1, 0xc4, 0x1b, 0x0b, 0x1a, 0x24, 0x12, 0xc9, 0x56, 0x13, 0xe3, 0xc1, 0x66, 0x76, - 0x77, 0x5c, 0x26, 0x6c, 0x77, 0xea, 0xce, 0xb6, 0xa5, 0xcf, 0xe0, 0x45, 0x5f, 0xc0, 0x07, 0xf0, - 0xe2, 0x85, 0x87, 0x20, 0xc6, 0x03, 0x31, 0x26, 0xfe, 0x39, 0x54, 0x84, 0xab, 0x4f, 0xe0, 0xc9, - 0xcc, 0x1f, 0x60, 0x81, 0x96, 0x10, 0x53, 0x3c, 0x70, 0x6a, 0xe7, 0x9b, 0x6f, 0xbe, 0xdf, 0x9f, - 0xf9, 0xf6, 0xdb, 0x85, 0xd3, 0x1b, 0xa8, 0x81, 0x4c, 0x12, 0xba, 0x38, 0x8c, 0x49, 0x03, 0x9b, - 0x8d, 0x39, 0x07, 0xc7, 0x68, 0xce, 0x74, 0x03, 0x44, 0xaa, 0xcc, 0xa8, 0x45, 0x34, 0xa6, 0xda, - 0x75, 0x9e, 0x64, 0x1c, 0x26, 0x19, 0x2a, 0x29, 0xa7, 0xbb, 0x94, 0x55, 0x29, 0x33, 0x1d, 0xc4, - 0x12, 0x27, 0x29, 0x09, 0xe5, 0xb9, 0xdc, 0xa4, 0xdc, 0xaf, 0x88, 0x95, 0x29, 0x17, 0x6a, 0x6b, - 0xcc, 0xa7, 0x3e, 0x95, 0x71, 0xfe, 0x4f, 0x46, 0x0b, 0x1f, 0x00, 0x4c, 0x5b, 0x88, 0xe1, 0x45, - 0x8e, 0xae, 0xbd, 0x80, 0x03, 0xb4, 0x19, 0xe2, 0x68, 0x02, 0x4c, 0x81, 0x62, 0xc6, 0x5a, 0xfe, - 0xd3, 0xce, 0x97, 0x7c, 0x12, 0xaf, 0xd7, 0x1d, 0xc3, 0xa5, 0x55, 0x55, 0x4f, 0xfd, 0x94, 0x98, - 0xb7, 0x61, 0xc6, 0xad, 0x1a, 0x66, 0xc6, 0x82, 0xeb, 0x2e, 0x78, 0x5e, 0x84, 0x19, 0xfb, 0xbc, - 0x55, 0x1a, 0x55, 0xa8, 0x2a, 0x62, 0xb5, 0x62, 0xcc, 0x6c, 0x59, 0x56, 0xbb, 0x0b, 0x07, 0x23, - 0xdc, 0x44, 0x91, 0x37, 0xd1, 0x37, 0x05, 0x8a, 0x43, 0xf3, 0x93, 0x86, 0x4a, 0xe6, 0x7a, 0x0e, - 0x44, 0x1a, 0x8b, 0x94, 0x84, 0xd6, 0x95, 0xed, 0x76, 0x3e, 0x65, 0xab, 0xf4, 0x7b, 0xe9, 0x8f, - 0x5b, 0xa5, 0x01, 0xc1, 0xb1, 0xb0, 0x0b, 0x60, 0x96, 0x33, 0x5e, 0xad, 0x07, 0x31, 0xf9, 0x3f, - 0xb4, 0xdd, 0x04, 0xed, 0xfe, 0xb3, 0x69, 0xcf, 0x72, 0xda, 0xef, 0x7f, 0xe6, 0x8b, 0xe7, 0xc0, - 0xe7, 0x07, 0x58, 0x27, 0x89, 0xaf, 0x01, 0x1c, 0xb2, 0x45, 0xf4, 0x61, 0xe8, 0xe1, 0x4d, 0xed, - 0x16, 0xbc, 0xe6, 0xd2, 0x20, 0x40, 0x31, 0x8e, 0x50, 0x50, 0xe1, 0x87, 0x85, 0xd2, 0xb4, 0x9d, - 0x3d, 0x0a, 0x3f, 0x69, 0xd5, 0xb0, 0x56, 0x86, 0xc3, 0xb2, 0x5a, 0xe5, 0x25, 0x72, 0x63, 0x1a, - 0x09, 0x9b, 0x33, 0x96, 0xc1, 0x49, 0xfd, 0x68, 0xe7, 0x67, 0xce, 0x41, 0x6a, 0x09, 0xbb, 0x76, - 0x46, 0x16, 0x79, 0x20, 0x6a, 0x14, 0x9a, 0x50, 0x4b, 0x90, 0xc1, 0x6c, 0x4d, 0x74, 0x28, 0x82, - 0x59, 0x05, 0x45, 0x64, 0x78, 0x02, 0x08, 0x6f, 0xa6, 0x8d, 0xce, 0xad, 0x6b, 0x24, 0x6a, 0x58, - 0xe3, 0xca, 0xa5, 0xe1, 0x63, 0x85, 0x6d, 0x45, 0x5e, 0x2d, 0x0b, 0xef, 0x00, 0x1c, 0x11, 0xb7, - 0xfc, 0x4f, 0x5e, 0x9c, 0x26, 0xd8, 0xd7, 0x6b, 0x82, 0x6f, 0x01, 0xbc, 0x71, 0x92, 0xe0, 0x81, - 0x3f, 0x0d, 0x38, 0x56, 0xe5, 0x5b, 0x95, 0x8e, 0x2e, 0x15, 0xbb, 0x91, 0x38, 0x59, 0xce, 0xca, - 0x29, 0x26, 0xda, 0x69, 0x20, 0x5b, 0xab, 0x9e, 0x8a, 0x15, 0x3e, 0x01, 0x38, 0xf2, 0xb4, 0xbc, - 0xf4, 0x6c, 0x95, 0x84, 0x31, 0x09, 0x7d, 0xf9, 0x80, 0xac, 0x40, 0xc8, 0x5b, 0xb5, 0x22, 0x66, - 0x8c, 0xf0, 0x6b, 0x68, 0xfe, 0x66, 0x37, 0x0a, 0x87, 0xe3, 0xc0, 0xba, 0xca, 0xb1, 0x77, 0xda, - 0x79, 0x60, 0xa7, 0x9d, 0xc3, 0x19, 0x71, 0xf1, 0xbe, 0x26, 0x1f, 0x85, 0xdf, 0x7d, 0x30, 0xb7, - 0x8c, 0x22, 0xef, 0x11, 0x79, 0x55, 0x27, 0x1e, 0x89, 0x5b, 0x6b, 0x11, 0x6d, 0x10, 0x0f, 0x47, - 0x92, 0xcc, 0xe3, 0x0e, 0xc2, 0x66, 0xce, 0x12, 0x76, 0x34, 0x35, 0x3a, 0xab, 0xdb, 0x84, 0xe3, - 0xac, 0x5e, 0xab, 0x05, 0xad, 0x4a, 0x47, 0x91, 0xbd, 0xb9, 0xb7, 0x51, 0x09, 0x71, 0x2c, 0xc8, - 0x91, 0x1d, 0x1a, 0x45, 0xb4, 0x79, 0x12, 0xb9, 0xbf, 0x97, 0xc8, 0x12, 0xc2, 0xee, 0x66, 0xf7, - 0x77, 0x00, 0xb3, 0x4b, 0x38, 0xc0, 0x3e, 0x8a, 0xe9, 0x45, 0x59, 0xbc, 0xd1, 0xa5, 0x81, 0x7a, - 0xa3, 0xb0, 0x7b, 0x2b, 0x7d, 0x01, 0x30, 0x5d, 0x6e, 0xa2, 0xda, 0x25, 0x93, 0xf5, 0x15, 0xc0, - 0x4c, 0x19, 0x35, 0x48, 0xe8, 0xb3, 0x4b, 0x78, 0x61, 0xf7, 0x51, 0x14, 0x5e, 0x2e, 0x59, 0xd6, - 0xca, 0xf6, 0x2f, 0x3d, 0xb5, 0xbd, 0xa7, 0x83, 0x9d, 0x3d, 0x1d, 0xec, 0xee, 0xe9, 0xe0, 0xcd, - 0xbe, 0x9e, 0xda, 0xd9, 0xd7, 0x53, 0xdf, 0xf6, 0xf5, 0xd4, 0xf3, 0xdb, 0x89, 0x77, 0xf4, 0xac, - 0x1f, 0x20, 0x87, 0x99, 0xb3, 0x7e, 0xc9, 0x5d, 0x47, 0x24, 0x34, 0x37, 0x13, 0x9f, 0x8d, 0xe2, - 0x6d, 0xed, 0x0c, 0x8a, 0xaf, 0xb8, 0x3b, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0xca, 0xda, 0x22, - 0x4d, 0x55, 0x0a, 0x00, 0x00, -} - -func (m *BaseClaim) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *BaseClaim) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *BaseClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Reward.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintClaims(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *BaseMultiClaim) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *BaseMultiClaim) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *BaseMultiClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Reward) > 0 { - for iNdEx := len(m.Reward) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Reward[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintClaims(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *RewardIndex) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *RewardIndex) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *RewardIndex) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.RewardFactor.Size() - i -= size - if _, err := m.RewardFactor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintClaims(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *RewardIndexesProto) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *RewardIndexesProto) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *RewardIndexesProto) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RewardIndexes) > 0 { - for iNdEx := len(m.RewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *MultiRewardIndex) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MultiRewardIndex) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MultiRewardIndex) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RewardIndexes) > 0 { - for iNdEx := len(m.RewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintClaims(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MultiRewardIndexesProto) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MultiRewardIndexesProto) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MultiRewardIndexesProto) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.MultiRewardIndexes) > 0 { - for iNdEx := len(m.MultiRewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.MultiRewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *USDXMintingClaim) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *USDXMintingClaim) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *USDXMintingClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RewardIndexes) > 0 { - for iNdEx := len(m.RewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.BaseClaim.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *HardLiquidityProviderClaim) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *HardLiquidityProviderClaim) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *HardLiquidityProviderClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.BorrowRewardIndexes) > 0 { - for iNdEx := len(m.BorrowRewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.BorrowRewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.SupplyRewardIndexes) > 0 { - for iNdEx := len(m.SupplyRewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SupplyRewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.BaseMultiClaim.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *DelegatorClaim) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *DelegatorClaim) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DelegatorClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RewardIndexes) > 0 { - for iNdEx := len(m.RewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.BaseMultiClaim.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *SwapClaim) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *SwapClaim) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SwapClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RewardIndexes) > 0 { - for iNdEx := len(m.RewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.BaseMultiClaim.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *SavingsClaim) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *SavingsClaim) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SavingsClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RewardIndexes) > 0 { - for iNdEx := len(m.RewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.BaseMultiClaim.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *EarnClaim) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *EarnClaim) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *EarnClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RewardIndexes) > 0 { - for iNdEx := len(m.RewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.BaseMultiClaim.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClaims(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintClaims(dAtA []byte, offset int, v uint64) int { - offset -= sovClaims(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *BaseClaim) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovClaims(uint64(l)) - } - l = m.Reward.Size() - n += 1 + l + sovClaims(uint64(l)) - return n -} - -func (m *BaseMultiClaim) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovClaims(uint64(l)) - } - if len(m.Reward) > 0 { - for _, e := range m.Reward { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func (m *RewardIndex) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovClaims(uint64(l)) - } - l = m.RewardFactor.Size() - n += 1 + l + sovClaims(uint64(l)) - return n -} - -func (m *RewardIndexesProto) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.RewardIndexes) > 0 { - for _, e := range m.RewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func (m *MultiRewardIndex) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovClaims(uint64(l)) - } - if len(m.RewardIndexes) > 0 { - for _, e := range m.RewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func (m *MultiRewardIndexesProto) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.MultiRewardIndexes) > 0 { - for _, e := range m.MultiRewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func (m *USDXMintingClaim) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseClaim.Size() - n += 1 + l + sovClaims(uint64(l)) - if len(m.RewardIndexes) > 0 { - for _, e := range m.RewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func (m *HardLiquidityProviderClaim) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseMultiClaim.Size() - n += 1 + l + sovClaims(uint64(l)) - if len(m.SupplyRewardIndexes) > 0 { - for _, e := range m.SupplyRewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - if len(m.BorrowRewardIndexes) > 0 { - for _, e := range m.BorrowRewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func (m *DelegatorClaim) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseMultiClaim.Size() - n += 1 + l + sovClaims(uint64(l)) - if len(m.RewardIndexes) > 0 { - for _, e := range m.RewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func (m *SwapClaim) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseMultiClaim.Size() - n += 1 + l + sovClaims(uint64(l)) - if len(m.RewardIndexes) > 0 { - for _, e := range m.RewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func (m *SavingsClaim) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseMultiClaim.Size() - n += 1 + l + sovClaims(uint64(l)) - if len(m.RewardIndexes) > 0 { - for _, e := range m.RewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func (m *EarnClaim) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.BaseMultiClaim.Size() - n += 1 + l + sovClaims(uint64(l)) - if len(m.RewardIndexes) > 0 { - for _, e := range m.RewardIndexes { - l = e.Size() - n += 1 + l + sovClaims(uint64(l)) - } - } - return n -} - -func sovClaims(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozClaims(x uint64) (n int) { - return sovClaims(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *BaseClaim) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: BaseClaim: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BaseClaim: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = append(m.Owner[:0], dAtA[iNdEx:postIndex]...) - if m.Owner == nil { - m.Owner = []byte{} - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Reward", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Reward.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *BaseMultiClaim) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: BaseMultiClaim: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BaseMultiClaim: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = append(m.Owner[:0], dAtA[iNdEx:postIndex]...) - if m.Owner == nil { - m.Owner = []byte{} - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Reward", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Reward = append(m.Reward, types.Coin{}) - if err := m.Reward[len(m.Reward)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *RewardIndex) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: RewardIndex: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: RewardIndex: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardFactor", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.RewardFactor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *RewardIndexesProto) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: RewardIndexesProto: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: RewardIndexesProto: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RewardIndexes = append(m.RewardIndexes, RewardIndex{}) - if err := m.RewardIndexes[len(m.RewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MultiRewardIndex) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MultiRewardIndex: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MultiRewardIndex: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RewardIndexes = append(m.RewardIndexes, RewardIndex{}) - if err := m.RewardIndexes[len(m.RewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MultiRewardIndexesProto) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MultiRewardIndexesProto: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MultiRewardIndexesProto: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MultiRewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MultiRewardIndexes = append(m.MultiRewardIndexes, MultiRewardIndex{}) - if err := m.MultiRewardIndexes[len(m.MultiRewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *USDXMintingClaim) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: USDXMintingClaim: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: USDXMintingClaim: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseClaim.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RewardIndexes = append(m.RewardIndexes, RewardIndex{}) - if err := m.RewardIndexes[len(m.RewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *HardLiquidityProviderClaim) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: HardLiquidityProviderClaim: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: HardLiquidityProviderClaim: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseMultiClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseMultiClaim.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SupplyRewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SupplyRewardIndexes = append(m.SupplyRewardIndexes, MultiRewardIndex{}) - if err := m.SupplyRewardIndexes[len(m.SupplyRewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BorrowRewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.BorrowRewardIndexes = append(m.BorrowRewardIndexes, MultiRewardIndex{}) - if err := m.BorrowRewardIndexes[len(m.BorrowRewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DelegatorClaim) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DelegatorClaim: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DelegatorClaim: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseMultiClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseMultiClaim.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RewardIndexes = append(m.RewardIndexes, MultiRewardIndex{}) - if err := m.RewardIndexes[len(m.RewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *SwapClaim) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: SwapClaim: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SwapClaim: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseMultiClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseMultiClaim.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RewardIndexes = append(m.RewardIndexes, MultiRewardIndex{}) - if err := m.RewardIndexes[len(m.RewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *SavingsClaim) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: SavingsClaim: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SavingsClaim: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseMultiClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseMultiClaim.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RewardIndexes = append(m.RewardIndexes, MultiRewardIndex{}) - if err := m.RewardIndexes[len(m.RewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *EarnClaim) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: EarnClaim: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: EarnClaim: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseMultiClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseMultiClaim.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClaims - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClaims - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClaims - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RewardIndexes = append(m.RewardIndexes, MultiRewardIndex{}) - if err := m.RewardIndexes[len(m.RewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClaims(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClaims - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipClaims(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowClaims - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowClaims - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowClaims - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthClaims - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupClaims - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthClaims - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthClaims = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowClaims = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupClaims = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/incentive/types/claims_test.go b/x/incentive/types/claims_test.go deleted file mode 100644 index 143b6f9d..00000000 --- a/x/incentive/types/claims_test.go +++ /dev/null @@ -1,794 +0,0 @@ -package types - -import ( - "fmt" - "testing" - - "github.com/cometbft/cometbft/crypto" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// d is a helper function for creating sdk.Dec values in tests -func d(str string) sdk.Dec { return sdk.MustNewDecFromStr(str) } - -// c is a helper function for created sdk.Coin types in tests -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } - -// c is a helper function for created sdk.Coins types in tests -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } - -func TestClaims_Validate(t *testing.T) { - owner := sdk.AccAddress(crypto.AddressHash([]byte("KavaTestUser1"))) - - t.Run("USDXMintingClaims", func(t *testing.T) { - testCases := []struct { - name string - claims USDXMintingClaims - expPass bool - }{ - { - "valid", - USDXMintingClaims{ - NewUSDXMintingClaim(owner, sdk.NewCoin("bnb", sdk.OneInt()), RewardIndexes{NewRewardIndex("bnb-a", sdk.ZeroDec())}), - }, - true, - }, - { - "invalid owner", - USDXMintingClaims{ - USDXMintingClaim{ - BaseClaim: BaseClaim{ - Owner: nil, - }, - }, - }, - false, - }, - { - "invalid reward", - USDXMintingClaims{ - { - BaseClaim: BaseClaim{ - Owner: owner, - Reward: sdk.Coin{Denom: "", Amount: sdk.ZeroInt()}, - }, - }, - }, - false, - }, - { - "invalid collateral type", - USDXMintingClaims{ - { - BaseClaim: BaseClaim{ - Owner: owner, - Reward: sdk.NewCoin("bnb", sdk.OneInt()), - }, - RewardIndexes: []RewardIndex{{"", sdk.ZeroDec()}}, - }, - }, - false, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.claims.Validate() - if tc.expPass { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } - }) - t.Run("SwapClaims", func(t *testing.T) { - validRewardIndexes := RewardIndexes{}.With("swap", d("0.002")) - validMultiRewardIndexes := MultiRewardIndexes{}.With("btcb/usdx", validRewardIndexes) - invalidRewardIndexes := RewardIndexes{}.With("swap", d("-0.002")) - invalidMultiRewardIndexes := MultiRewardIndexes{}.With("btcb/usdx", invalidRewardIndexes) - - testCases := []struct { - name string - claims SwapClaims - expPass bool - }{ - { - name: "valid", - claims: SwapClaims{ - NewSwapClaim(owner, cs(c("bnb", 1)), validMultiRewardIndexes), - }, - expPass: true, - }, - { - name: "invalid owner", - claims: SwapClaims{ - NewSwapClaim(nil, cs(c("bnb", 1)), validMultiRewardIndexes), - }, - expPass: false, - }, - { - name: "invalid reward", - claims: SwapClaims{ - NewSwapClaim(owner, sdk.Coins{sdk.Coin{Denom: "invalid😫"}}, validMultiRewardIndexes), - }, - expPass: false, - }, - { - name: "invalid indexes", - claims: SwapClaims{ - NewSwapClaim(nil, cs(c("bnb", 1)), invalidMultiRewardIndexes), - }, - expPass: false, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.claims.Validate() - if tc.expPass { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } - }) - - t.Run("SavingsClaims", func(t *testing.T) { - validRewardIndexes := RewardIndexes{}.With("ukava", d("0.002")) - validMultiRewardIndexes := MultiRewardIndexes{}.With("btcb/usdx", validRewardIndexes) - invalidRewardIndexes := RewardIndexes{}.With("ukava", d("-0.002")) - invalidMultiRewardIndexes := MultiRewardIndexes{}.With("btcb/usdx", invalidRewardIndexes) - - testCases := []struct { - name string - claims SavingsClaims - expPass bool - }{ - { - name: "valid", - claims: SavingsClaims{ - NewSavingsClaim(owner, cs(c("bnb", 1)), validMultiRewardIndexes), - }, - expPass: true, - }, - { - name: "invalid owner", - claims: SavingsClaims{ - NewSavingsClaim(nil, cs(c("bnb", 1)), validMultiRewardIndexes), - }, - expPass: false, - }, - { - name: "invalid reward", - claims: SavingsClaims{ - NewSavingsClaim(owner, sdk.Coins{sdk.Coin{Denom: "invalid😫"}}, validMultiRewardIndexes), - }, - expPass: false, - }, - { - name: "invalid indexes", - claims: SavingsClaims{ - NewSavingsClaim(nil, cs(c("bnb", 1)), invalidMultiRewardIndexes), - }, - expPass: false, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.claims.Validate() - if tc.expPass { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } - }) -} - -func TestRewardIndexes(t *testing.T) { - t.Run("With", func(t *testing.T) { - arbitraryDec := sdk.MustNewDecFromStr("0.1") - - type args struct { - denom string - factor sdk.Dec - } - testcases := []struct { - name string - rewardIndexes RewardIndexes - args args - expected RewardIndexes - }{ - { - name: "when index is not present, it's added and original isn't overwritten", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", arbitraryDec), - }, - args: args{ - denom: "otherdenom", - factor: arbitraryDec, - }, - expected: RewardIndexes{ - NewRewardIndex("denom", arbitraryDec), - NewRewardIndex("otherdenom", arbitraryDec), - }, - }, - { - name: "when index is present, it's updated and original isn't overwritten", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", arbitraryDec), - }, - args: args{ - denom: "denom", - factor: arbitraryDec.MulInt64(2), - }, - expected: RewardIndexes{ - NewRewardIndex("denom", arbitraryDec.MulInt64(2)), - }, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - newIndexes := tc.rewardIndexes.With(tc.args.denom, tc.args.factor) - - require.Equal(t, tc.expected, newIndexes) - require.NotEqual(t, tc.rewardIndexes, newIndexes) // check original slice not modified - }) - } - }) - t.Run("Get", func(t *testing.T) { - arbitraryDec := sdk.MustNewDecFromStr("0.1") - - type expected struct { - factor sdk.Dec - found bool - } - testcases := []struct { - name string - rewardIndexes RewardIndexes - arg_denom string - expected expected - }{ - { - name: "when index is present, it is found and returned", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", arbitraryDec), - }, - arg_denom: "denom", - expected: expected{ - factor: arbitraryDec, - found: true, - }, - }, - { - name: "when index is not present, it is not found", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", arbitraryDec), - }, - arg_denom: "notpresent", - expected: expected{ - found: false, - }, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - factor, found := tc.rewardIndexes.Get(tc.arg_denom) - - require.Equal(t, tc.expected.found, found) - require.Equal(t, tc.expected.factor, factor) - }) - } - }) - t.Run("Mul", func(t *testing.T) { - testcases := []struct { - name string - rewardIndexes RewardIndexes - multiplier sdk.Dec - expected RewardIndexes - }{ - { - name: "non zero values are all multiplied", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - NewRewardIndex("denom2", d("0.2")), - }, - multiplier: d("2.0"), - expected: RewardIndexes{ - NewRewardIndex("denom", d("0.2")), - NewRewardIndex("denom2", d("0.4")), - }, - }, - { - name: "multiplying by zero, zeros all values", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - NewRewardIndex("denom2", d("0.0")), - }, - multiplier: d("0.0"), - expected: RewardIndexes{ - NewRewardIndex("denom", d("0.0")), - NewRewardIndex("denom2", d("0.0")), - }, - }, - { - name: "empty indexes are unchanged", - rewardIndexes: RewardIndexes{}, - multiplier: d("2.0"), - expected: RewardIndexes{}, - }, - { - name: "nil indexes are unchanged", - rewardIndexes: nil, - multiplier: d("2.0"), - expected: nil, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - actual := tc.rewardIndexes.Mul(tc.multiplier) - - if len(tc.expected) == 0 { - require.Equal(t, actual, tc.expected) - } else { - require.Len(t, actual, len(tc.expected)) - for i := range tc.expected { - assert.Equal(t, - actual[i].CollateralType, - tc.expected[i].CollateralType, - ) - assert.True(t, - actual[i].RewardFactor.Equal(tc.expected[i].RewardFactor), - ) - } - } - }) - } - }) - t.Run("Quo", func(t *testing.T) { - type expected struct { - indexes RewardIndexes - panics bool - } - testcases := []struct { - name string - rewardIndexes RewardIndexes - divisor sdk.Dec - expected expected - }{ - { - name: "non zero values are all divided", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", d("0.6")), - NewRewardIndex("denom2", d("0.2")), - }, - divisor: d("3.0"), - expected: expected{ - indexes: RewardIndexes{ - NewRewardIndex("denom", d("0.2")), - NewRewardIndex("denom2", d("0.066666666666666667")), - }, - }, - }, - { - name: "diving by zero panics when values are present", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - NewRewardIndex("denom2", d("0.0")), - }, - divisor: d("0.0"), - expected: expected{ - panics: true, - }, - }, - { - name: "empty indexes are unchanged", - rewardIndexes: RewardIndexes{}, - divisor: d("2.0"), - expected: expected{ - indexes: RewardIndexes{}, - }, - }, - { - name: "nil indexes are unchanged", - rewardIndexes: nil, - divisor: d("2.0"), - expected: expected{ - indexes: nil, - }, - }, - } - - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - var actual RewardIndexes - quoFunc := func() { actual = tc.rewardIndexes.Quo(tc.divisor) } - if tc.expected.panics { - require.Panics(t, quoFunc) - return - } else { - require.NotPanics(t, quoFunc) - } - require.Equal(t, tc.expected.indexes, actual) - }) - } - }) - t.Run("Add", func(t *testing.T) { - testcases := []struct { - name string - rewardIndexes RewardIndexes - addend RewardIndexes - expected RewardIndexes - }{ - { - name: "same denoms are added", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - NewRewardIndex("denom2", d("0.2")), - }, - addend: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - NewRewardIndex("denom2", d("0.2")), - }, - expected: RewardIndexes{ - NewRewardIndex("denom", d("0.2")), - NewRewardIndex("denom2", d("0.4")), - }, - }, - { - name: "new denoms are appended", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - }, - addend: RewardIndexes{ - NewRewardIndex("denom", d("0.3")), - NewRewardIndex("denom2", d("0.2")), - }, - expected: RewardIndexes{ - NewRewardIndex("denom", d("0.4")), - NewRewardIndex("denom2", d("0.2")), - }, - }, - { - name: "missing denoms are unchanged", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - NewRewardIndex("denom2", d("0.2")), - }, - addend: RewardIndexes{ - NewRewardIndex("denom2", d("0.2")), - }, - expected: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - NewRewardIndex("denom2", d("0.4")), - }, - }, - { - name: "adding empty indexes does nothing", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - }, - addend: RewardIndexes{}, - expected: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - }, - }, - { - name: "adding nil indexes does nothing", - rewardIndexes: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - }, - addend: nil, - expected: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - }, - }, - { - name: "denom can be added to empty indexes", - rewardIndexes: RewardIndexes{}, - addend: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - }, - expected: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - }, - }, - { - name: "denom can be added to nil indexes", - rewardIndexes: nil, - addend: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - }, - expected: RewardIndexes{ - NewRewardIndex("denom", d("0.1")), - }, - }, - { - name: "adding empty indexes to nil does nothing", - rewardIndexes: nil, - addend: RewardIndexes{}, - expected: nil, - }, - { - name: "adding nil to empty indexes does nothing", - rewardIndexes: RewardIndexes{}, - addend: nil, - expected: RewardIndexes{}, - }, - { - name: "adding nil to nil indexes does nothing", - rewardIndexes: nil, - addend: nil, - expected: nil, - }, - { - name: "adding empty indexes to empty indexes does nothing", - rewardIndexes: RewardIndexes{}, - addend: RewardIndexes{}, - expected: RewardIndexes{}, - }, - } - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - sum := tc.rewardIndexes.Add(tc.addend) - require.Equal(t, tc.expected, sum) - }) - } - }) -} - -func TestMultiRewardIndexes(t *testing.T) { - arbitraryRewardIndexes := RewardIndexes{ - { - CollateralType: "reward", - RewardFactor: sdk.MustNewDecFromStr("0.1"), - }, - } - - t.Run("Get", func(t *testing.T) { - type expected struct { - rewardIndexes RewardIndexes - found bool - } - testcases := []struct { - name string - multiRewardIndexes MultiRewardIndexes - arg_denom string - expected expected - }{ - { - name: "when indexes are present, they are found and returned", - multiRewardIndexes: MultiRewardIndexes{ - { - CollateralType: "denom", - RewardIndexes: arbitraryRewardIndexes, - }, - }, - arg_denom: "denom", - expected: expected{ - found: true, - rewardIndexes: arbitraryRewardIndexes, - }, - }, - { - name: "when indexes are not present, they are not found", - multiRewardIndexes: MultiRewardIndexes{ - { - CollateralType: "denom", - RewardIndexes: arbitraryRewardIndexes, - }, - }, - arg_denom: "notpresent", - expected: expected{ - found: false, - }, - }, - } - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - rewardIndexes, found := tc.multiRewardIndexes.Get(tc.arg_denom) - - require.Equal(t, tc.expected.found, found) - require.Equal(t, tc.expected.rewardIndexes, rewardIndexes) - }) - } - }) - t.Run("With", func(t *testing.T) { - type args struct { - denom string - rewardIndexes RewardIndexes - } - testcases := []struct { - name string - multiRewardIndexes MultiRewardIndexes - args args - expected MultiRewardIndexes - }{ - { - name: "when indexes are not present, add them and do not update original", - multiRewardIndexes: MultiRewardIndexes{ - { - CollateralType: "denom", - RewardIndexes: arbitraryRewardIndexes, - }, - }, - args: args{ - denom: "otherdenom", - rewardIndexes: arbitraryRewardIndexes, - }, - expected: MultiRewardIndexes{ - { - CollateralType: "denom", - RewardIndexes: arbitraryRewardIndexes, - }, - { - CollateralType: "otherdenom", - RewardIndexes: arbitraryRewardIndexes, - }, - }, - }, - { - name: "when indexes are present, update them and do not update original", - multiRewardIndexes: MultiRewardIndexes{ - { - CollateralType: "denom", - RewardIndexes: arbitraryRewardIndexes, - }, - }, - args: args{ - denom: "denom", - rewardIndexes: appendUniqueRewardIndex(arbitraryRewardIndexes), - }, - expected: MultiRewardIndexes{ - { - CollateralType: "denom", - RewardIndexes: appendUniqueRewardIndex(arbitraryRewardIndexes), - }, - }, - }, - } - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - oldIndexes := tc.multiRewardIndexes.copy() - - newIndexes := tc.multiRewardIndexes.With(tc.args.denom, tc.args.rewardIndexes) - - require.Equal(t, tc.expected, newIndexes) - require.Equal(t, oldIndexes, tc.multiRewardIndexes) - }) - } - }) - t.Run("RemoveRewardIndex", func(t *testing.T) { - testcases := []struct { - name string - multiRewardIndexes MultiRewardIndexes - arg_denom string - expected MultiRewardIndexes - }{ - { - name: "when indexes are not present, do nothing", - multiRewardIndexes: MultiRewardIndexes{ - { - CollateralType: "denom", - RewardIndexes: arbitraryRewardIndexes, - }, - }, - arg_denom: "notpresent", - expected: MultiRewardIndexes{ - { - CollateralType: "denom", - RewardIndexes: arbitraryRewardIndexes, - }, - }, - }, - { - name: "when indexes are present, remove them and do not update original", - multiRewardIndexes: MultiRewardIndexes{ - { - CollateralType: "denom", - RewardIndexes: arbitraryRewardIndexes, - }, - { - CollateralType: "otherdenom", - RewardIndexes: arbitraryRewardIndexes, - }, - }, - arg_denom: "denom", - expected: MultiRewardIndexes{ - { - CollateralType: "otherdenom", - RewardIndexes: arbitraryRewardIndexes, - }, - }, - }, - } - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - oldIndexes := tc.multiRewardIndexes.copy() - - newIndexes := tc.multiRewardIndexes.RemoveRewardIndex(tc.arg_denom) - - require.Equal(t, tc.expected, newIndexes) - require.Equal(t, oldIndexes, tc.multiRewardIndexes) - }) - } - }) - t.Run("Validate", func(t *testing.T) { - testcases := []struct { - name string - multiRewardIndexes MultiRewardIndexes - wantErr bool - }{ - { - name: "normal case", - multiRewardIndexes: MultiRewardIndexes{ - {CollateralType: "btcb", RewardIndexes: normalRewardIndexes}, - {CollateralType: "bnb", RewardIndexes: normalRewardIndexes}, - }, - wantErr: false, - }, - { - name: "empty", - multiRewardIndexes: nil, - wantErr: false, - }, - { - name: "empty collateral type", - multiRewardIndexes: MultiRewardIndexes{ - {RewardIndexes: normalRewardIndexes}, - }, - wantErr: true, - }, - { - name: "invalid reward index", - multiRewardIndexes: MultiRewardIndexes{ - {CollateralType: "btcb", RewardIndexes: invalidRewardIndexes}, - }, - wantErr: true, - }, - } - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - err := tc.multiRewardIndexes.Validate() - if tc.wantErr { - require.NotNil(t, err) - } else { - require.Nil(t, err) - } - }) - } - }) -} - -var normalRewardIndexes = RewardIndexes{ - NewRewardIndex("hard", sdk.MustNewDecFromStr("0.000001")), - NewRewardIndex("ukava", sdk.MustNewDecFromStr("0.1")), -} - -var invalidRewardIndexes = RewardIndexes{ - RewardIndex{"hard", sdk.MustNewDecFromStr("-0.01")}, -} - -func appendUniqueRewardIndex(indexes RewardIndexes) RewardIndexes { - const uniqueDenom = "uniquereward" - - for _, mri := range indexes { - if mri.CollateralType == uniqueDenom { - panic(fmt.Sprintf("tried to add unique reward index with denom '%s', but denom already existed", uniqueDenom)) - } - } - - return append( - indexes, - NewRewardIndex(uniqueDenom, sdk.MustNewDecFromStr("0.02")), - ) -} diff --git a/x/incentive/types/codec.go b/x/incentive/types/codec.go deleted file mode 100644 index ccf56005..00000000 --- a/x/incentive/types/codec.go +++ /dev/null @@ -1,49 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the -// governance module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgClaimUSDXMintingReward{}, "incentive/MsgClaimUSDXMintingReward", nil) - cdc.RegisterConcrete(&MsgClaimHardReward{}, "incentive/MsgClaimHardReward", nil) - cdc.RegisterConcrete(&MsgClaimDelegatorReward{}, "incentive/MsgClaimDelegatorReward", nil) - cdc.RegisterConcrete(&MsgClaimSwapReward{}, "incentive/MsgClaimSwapReward", nil) - cdc.RegisterConcrete(&MsgClaimSavingsReward{}, "incentive/MsgClaimSavingsReward", nil) - cdc.RegisterConcrete(&MsgClaimEarnReward{}, "incentive/MsgClaimEarnReward", nil) -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgClaimUSDXMintingReward{}, - &MsgClaimHardReward{}, - &MsgClaimDelegatorReward{}, - &MsgClaimSwapReward{}, - &MsgClaimSavingsReward{}, - &MsgClaimEarnReward{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/incentive/types/errors.go b/x/incentive/types/errors.go deleted file mode 100644 index f14f7e40..00000000 --- a/x/incentive/types/errors.go +++ /dev/null @@ -1,21 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -// DONTCOVER - -// Incentive module errors -var ( - ErrClaimNotFound = errorsmod.Register(ModuleName, 2, "no claimable rewards found for user") - ErrRewardPeriodNotFound = errorsmod.Register(ModuleName, 3, "no reward period found for collateral type") - ErrInvalidAccountType = errorsmod.Register(ModuleName, 4, "account type not supported") - ErrNoClaimsFound = errorsmod.Register(ModuleName, 5, "no claimable rewards found") - ErrInsufficientModAccountBalance = errorsmod.Register(ModuleName, 6, "module account has insufficient balance to pay claim") - ErrAccountNotFound = errorsmod.Register(ModuleName, 7, "account not found") - ErrInvalidMultiplier = errorsmod.Register(ModuleName, 8, "invalid rewards multiplier") - ErrZeroClaim = errorsmod.Register(ModuleName, 9, "cannot claim - claim amount rounds to zero") - ErrClaimExpired = errorsmod.Register(ModuleName, 10, "claim has expired") - ErrInvalidClaimType = errorsmod.Register(ModuleName, 11, "invalid claim type") - ErrDecreasingRewardFactor = errorsmod.Register(ModuleName, 13, "found new reward factor less than an old reward factor") - ErrInvalidClaimDenoms = errorsmod.Register(ModuleName, 14, "invalid claim denoms") -) diff --git a/x/incentive/types/events.go b/x/incentive/types/events.go deleted file mode 100644 index 5255d1c4..00000000 --- a/x/incentive/types/events.go +++ /dev/null @@ -1,16 +0,0 @@ -package types - -// Events emitted by the incentive module -const ( - EventTypeClaim = "claim_reward" - EventTypeRewardPeriod = "new_reward_period" - EventTypeClaimPeriod = "new_claim_period" - EventTypeClaimPeriodExpiry = "claim_period_expiry" - - AttributeValueCategory = ModuleName - AttributeKeyClaimedBy = "claimed_by" - AttributeKeyClaimAmount = "claim_amount" - AttributeKeyClaimType = "claim_type" - AttributeKeyRewardPeriod = "reward_period" - AttributeKeyClaimPeriod = "claim_period" -) diff --git a/x/incentive/types/expected_keepers.go b/x/incentive/types/expected_keepers.go deleted file mode 100644 index aa48a9a5..00000000 --- a/x/incentive/types/expected_keepers.go +++ /dev/null @@ -1,127 +0,0 @@ -package types - -import ( - sdkmath "cosmossdk.io/math" - cdptypes "github.com/0glabs/0g-chain/x/cdp/types" - earntypes "github.com/0glabs/0g-chain/x/earn/types" - hardtypes "github.com/0glabs/0g-chain/x/hard/types" - pricefeedtypes "github.com/0glabs/0g-chain/x/pricefeed/types" - savingstypes "github.com/0glabs/0g-chain/x/savings/types" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// ParamSubspace defines the expected Subspace interfacace -type ParamSubspace interface { - GetParamSet(sdk.Context, paramtypes.ParamSet) - SetParamSet(sdk.Context, paramtypes.ParamSet) - WithKeyTable(paramtypes.KeyTable) paramtypes.Subspace - HasKeyTable() bool -} - -// BankKeeper defines the expected interface needed to send coins -type BankKeeper interface { - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - GetSupply(ctx sdk.Context, denom string) sdk.Coin -} - -// StakingKeeper defines the expected staking keeper for module accounts -type StakingKeeper interface { - GetDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddress, maxRetrieve uint16) (delegations []stakingtypes.Delegation) - GetValidatorDelegations(ctx sdk.Context, valAddr sdk.ValAddress) (delegations []stakingtypes.Delegation) - GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool) - TotalBondedTokens(ctx sdk.Context) sdkmath.Int -} - -// CdpKeeper defines the expected cdp keeper for interacting with cdps -type CdpKeeper interface { - GetInterestFactor(ctx sdk.Context, collateralType string) (sdk.Dec, bool) - GetTotalPrincipal(ctx sdk.Context, collateralType string, principalDenom string) (total sdkmath.Int) - GetCdpByOwnerAndCollateralType(ctx sdk.Context, owner sdk.AccAddress, collateralType string) (cdptypes.CDP, bool) - GetCollateral(ctx sdk.Context, collateralType string) (cdptypes.CollateralParam, bool) -} - -// HardKeeper defines the expected hard keeper for interacting with Hard protocol -type HardKeeper interface { - GetDeposit(ctx sdk.Context, depositor sdk.AccAddress) (hardtypes.Deposit, bool) - GetBorrow(ctx sdk.Context, borrower sdk.AccAddress) (hardtypes.Borrow, bool) - - GetSupplyInterestFactor(ctx sdk.Context, denom string) (sdk.Dec, bool) - GetBorrowInterestFactor(ctx sdk.Context, denom string) (sdk.Dec, bool) - GetBorrowedCoins(ctx sdk.Context) (coins sdk.Coins, found bool) - GetSuppliedCoins(ctx sdk.Context) (coins sdk.Coins, found bool) -} - -// SwapKeeper defines the required methods needed by this modules keeper -type SwapKeeper interface { - GetPoolShares(ctx sdk.Context, poolID string) (shares sdkmath.Int, found bool) - GetDepositorSharesAmount(ctx sdk.Context, depositor sdk.AccAddress, poolID string) (shares sdkmath.Int, found bool) -} - -// SavingsKeeper defines the required methods needed by this module's keeper -type SavingsKeeper interface { - GetDeposit(ctx sdk.Context, depositor sdk.AccAddress) (savingstypes.Deposit, bool) - GetSavingsModuleAccountBalances(ctx sdk.Context) sdk.Coins -} - -// EarnKeeper defines the required methods needed by this modules keeper -type EarnKeeper interface { - GetVaultTotalShares(ctx sdk.Context, denom string) (shares earntypes.VaultShare, found bool) - GetVaultTotalValue(ctx sdk.Context, denom string) (sdk.Coin, error) - GetVaultAccountShares(ctx sdk.Context, acc sdk.AccAddress) (shares earntypes.VaultShares, found bool) - IterateVaultRecords(ctx sdk.Context, cb func(record earntypes.VaultRecord) (stop bool)) -} - -// LiquidKeeper defines the required methods needed by this modules keeper -type LiquidKeeper interface { - IsDerivativeDenom(ctx sdk.Context, denom string) bool - GetTotalDerivativeValue(ctx sdk.Context) (sdk.Coin, error) - GetDerivativeValue(ctx sdk.Context, denom string) (sdk.Coin, error) - CollectStakingRewardsByDenom( - ctx sdk.Context, - derivativeDenom string, - destinationModAccount string, - ) (sdk.Coins, error) -} - -// AccountKeeper expected interface for the account keeper (noalias) -type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI - SetAccount(ctx sdk.Context, acc authtypes.AccountI) - GetModuleAccount(ctx sdk.Context, name string) authtypes.ModuleAccountI -} - -// MintKeeper defines the required methods needed by this modules keeper -type MintKeeper interface { - GetMinter(ctx sdk.Context) (minter minttypes.Minter) -} - -// DistrKeeper defines the required methods needed by this modules keeper -type DistrKeeper interface { - GetCommunityTax(ctx sdk.Context) (percent sdk.Dec) -} - -// PricefeedKeeper defines the required methods needed by this modules keeper -type PricefeedKeeper interface { - GetCurrentPrice(ctx sdk.Context, marketID string) (pricefeedtypes.CurrentPrice, error) -} - -// CDPHooks event hooks for other keepers to run code in response to CDP modifications -type CDPHooks interface { - AfterCDPCreated(ctx sdk.Context, cdp cdptypes.CDP) - BeforeCDPModified(ctx sdk.Context, cdp cdptypes.CDP) -} - -// HARDHooks event hooks for other keepers to run code in response to HARD modifications -type HARDHooks interface { - AfterDepositCreated(ctx sdk.Context, deposit hardtypes.Deposit) - BeforeDepositModified(ctx sdk.Context, deposit hardtypes.Deposit) - AfterDepositModified(ctx sdk.Context, deposit hardtypes.Deposit) - AfterBorrowCreated(ctx sdk.Context, borrow hardtypes.Borrow) - BeforeBorrowModified(ctx sdk.Context, borrow hardtypes.Borrow) - AfterBorrowModified(ctx sdk.Context, deposit hardtypes.Deposit) -} diff --git a/x/incentive/types/genesis.go b/x/incentive/types/genesis.go deleted file mode 100644 index 1955617b..00000000 --- a/x/incentive/types/genesis.go +++ /dev/null @@ -1,160 +0,0 @@ -package types - -import ( - "fmt" - "time" -) - -var ( - DefaultUSDXClaims = USDXMintingClaims{} - DefaultHardClaims = HardLiquidityProviderClaims{} - DefaultDelegatorClaims = DelegatorClaims{} - DefaultSwapClaims = SwapClaims{} - DefaultSavingsClaims = SavingsClaims{} - DefaultGenesisRewardState = NewGenesisRewardState( - AccumulationTimes{}, - MultiRewardIndexes{}, - ) - DefaultEarnClaims = EarnClaims{} -) - -// NewGenesisState returns a new genesis state -func NewGenesisState( - params Params, - usdxState, hardSupplyState, hardBorrowState, delegatorState, swapState, savingsState, earnState GenesisRewardState, - c USDXMintingClaims, hc HardLiquidityProviderClaims, dc DelegatorClaims, sc SwapClaims, savingsc SavingsClaims, - earnc EarnClaims, -) GenesisState { - return GenesisState{ - Params: params, - - USDXRewardState: usdxState, - HardSupplyRewardState: hardSupplyState, - HardBorrowRewardState: hardBorrowState, - DelegatorRewardState: delegatorState, - SwapRewardState: swapState, - SavingsRewardState: savingsState, - EarnRewardState: earnState, - - USDXMintingClaims: c, - HardLiquidityProviderClaims: hc, - DelegatorClaims: dc, - SwapClaims: sc, - SavingsClaims: savingsc, - EarnClaims: earnc, - } -} - -// DefaultGenesisState returns a default genesis state -func DefaultGenesisState() GenesisState { - return GenesisState{ - Params: DefaultParams(), - USDXRewardState: DefaultGenesisRewardState, - HardSupplyRewardState: DefaultGenesisRewardState, - HardBorrowRewardState: DefaultGenesisRewardState, - DelegatorRewardState: DefaultGenesisRewardState, - SwapRewardState: DefaultGenesisRewardState, - SavingsRewardState: DefaultGenesisRewardState, - EarnRewardState: DefaultGenesisRewardState, - USDXMintingClaims: DefaultUSDXClaims, - HardLiquidityProviderClaims: DefaultHardClaims, - DelegatorClaims: DefaultDelegatorClaims, - SwapClaims: DefaultSwapClaims, - SavingsClaims: DefaultSavingsClaims, - EarnClaims: DefaultEarnClaims, - } -} - -// Validate performs basic validation of genesis data returning an -// error for any failed validation criteria. -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - - if err := gs.USDXRewardState.Validate(); err != nil { - return err - } - if err := gs.HardSupplyRewardState.Validate(); err != nil { - return err - } - if err := gs.HardBorrowRewardState.Validate(); err != nil { - return err - } - if err := gs.DelegatorRewardState.Validate(); err != nil { - return err - } - if err := gs.SwapRewardState.Validate(); err != nil { - return err - } - if err := gs.SavingsRewardState.Validate(); err != nil { - return err - } - if err := gs.EarnRewardState.Validate(); err != nil { - return err - } - - if err := gs.USDXMintingClaims.Validate(); err != nil { - return err - } - if err := gs.HardLiquidityProviderClaims.Validate(); err != nil { - return err - } - if err := gs.DelegatorClaims.Validate(); err != nil { - return err - } - if err := gs.SwapClaims.Validate(); err != nil { - return err - } - - if err := gs.SavingsClaims.Validate(); err != nil { - return err - } - - return gs.EarnClaims.Validate() -} - -// NewGenesisRewardState returns a new GenesisRewardState -func NewGenesisRewardState(accumTimes AccumulationTimes, indexes MultiRewardIndexes) GenesisRewardState { - return GenesisRewardState{ - AccumulationTimes: accumTimes, - MultiRewardIndexes: indexes, - } -} - -// Validate performs validation of a GenesisRewardState -func (grs GenesisRewardState) Validate() error { - if err := grs.AccumulationTimes.Validate(); err != nil { - return err - } - return grs.MultiRewardIndexes.Validate() -} - -// NewAccumulationTime returns a new GenesisAccumulationTime -func NewAccumulationTime(ctype string, prevTime time.Time) AccumulationTime { - return AccumulationTime{ - CollateralType: ctype, - PreviousAccumulationTime: prevTime, - } -} - -// Validate performs validation of GenesisAccumulationTime -func (gat AccumulationTime) Validate() error { - if len(gat.CollateralType) == 0 { - return fmt.Errorf("genesis accumulation time's collateral type must be defined") - } - return nil -} - -// AccumulationTimes slice of GenesisAccumulationTime -type AccumulationTimes []AccumulationTime - -// Validate performs validation of GenesisAccumulationTimes -func (gats AccumulationTimes) Validate() error { - for _, gat := range gats { - if err := gat.Validate(); err != nil { - return err - } - } - return nil -} diff --git a/x/incentive/types/genesis.pb.go b/x/incentive/types/genesis.pb.go deleted file mode 100644 index 67e22dec..00000000 --- a/x/incentive/types/genesis.pb.go +++ /dev/null @@ -1,1447 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/incentive/v1beta1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// AccumulationTime stores the previous reward distribution time and its corresponding collateral type -type AccumulationTime struct { - CollateralType string `protobuf:"bytes,1,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - PreviousAccumulationTime time.Time `protobuf:"bytes,2,opt,name=previous_accumulation_time,json=previousAccumulationTime,proto3,stdtime" json:"previous_accumulation_time"` -} - -func (m *AccumulationTime) Reset() { *m = AccumulationTime{} } -func (m *AccumulationTime) String() string { return proto.CompactTextString(m) } -func (*AccumulationTime) ProtoMessage() {} -func (*AccumulationTime) Descriptor() ([]byte, []int) { - return fileDescriptor_8b76737885d05afd, []int{0} -} -func (m *AccumulationTime) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AccumulationTime) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AccumulationTime.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *AccumulationTime) XXX_Merge(src proto.Message) { - xxx_messageInfo_AccumulationTime.Merge(m, src) -} -func (m *AccumulationTime) XXX_Size() int { - return m.Size() -} -func (m *AccumulationTime) XXX_DiscardUnknown() { - xxx_messageInfo_AccumulationTime.DiscardUnknown(m) -} - -var xxx_messageInfo_AccumulationTime proto.InternalMessageInfo - -// GenesisRewardState groups together the global state for a particular reward so it can be exported in genesis. -type GenesisRewardState struct { - AccumulationTimes AccumulationTimes `protobuf:"bytes,1,rep,name=accumulation_times,json=accumulationTimes,proto3,castrepeated=AccumulationTimes" json:"accumulation_times"` - MultiRewardIndexes MultiRewardIndexes `protobuf:"bytes,2,rep,name=multi_reward_indexes,json=multiRewardIndexes,proto3,castrepeated=MultiRewardIndexes" json:"multi_reward_indexes"` -} - -func (m *GenesisRewardState) Reset() { *m = GenesisRewardState{} } -func (m *GenesisRewardState) String() string { return proto.CompactTextString(m) } -func (*GenesisRewardState) ProtoMessage() {} -func (*GenesisRewardState) Descriptor() ([]byte, []int) { - return fileDescriptor_8b76737885d05afd, []int{1} -} -func (m *GenesisRewardState) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisRewardState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisRewardState.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisRewardState) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisRewardState.Merge(m, src) -} -func (m *GenesisRewardState) XXX_Size() int { - return m.Size() -} -func (m *GenesisRewardState) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisRewardState.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisRewardState proto.InternalMessageInfo - -// GenesisState is the state that must be provided at genesis. -type GenesisState struct { - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - USDXRewardState GenesisRewardState `protobuf:"bytes,2,opt,name=usdx_reward_state,json=usdxRewardState,proto3" json:"usdx_reward_state"` - HardSupplyRewardState GenesisRewardState `protobuf:"bytes,3,opt,name=hard_supply_reward_state,json=hardSupplyRewardState,proto3" json:"hard_supply_reward_state"` - HardBorrowRewardState GenesisRewardState `protobuf:"bytes,4,opt,name=hard_borrow_reward_state,json=hardBorrowRewardState,proto3" json:"hard_borrow_reward_state"` - DelegatorRewardState GenesisRewardState `protobuf:"bytes,5,opt,name=delegator_reward_state,json=delegatorRewardState,proto3" json:"delegator_reward_state"` - SwapRewardState GenesisRewardState `protobuf:"bytes,6,opt,name=swap_reward_state,json=swapRewardState,proto3" json:"swap_reward_state"` - USDXMintingClaims USDXMintingClaims `protobuf:"bytes,7,rep,name=usdx_minting_claims,json=usdxMintingClaims,proto3,castrepeated=USDXMintingClaims" json:"usdx_minting_claims"` - HardLiquidityProviderClaims HardLiquidityProviderClaims `protobuf:"bytes,8,rep,name=hard_liquidity_provider_claims,json=hardLiquidityProviderClaims,proto3,castrepeated=HardLiquidityProviderClaims" json:"hard_liquidity_provider_claims"` - DelegatorClaims DelegatorClaims `protobuf:"bytes,9,rep,name=delegator_claims,json=delegatorClaims,proto3,castrepeated=DelegatorClaims" json:"delegator_claims"` - SwapClaims SwapClaims `protobuf:"bytes,10,rep,name=swap_claims,json=swapClaims,proto3,castrepeated=SwapClaims" json:"swap_claims"` - SavingsRewardState GenesisRewardState `protobuf:"bytes,11,opt,name=savings_reward_state,json=savingsRewardState,proto3" json:"savings_reward_state"` - SavingsClaims SavingsClaims `protobuf:"bytes,12,rep,name=savings_claims,json=savingsClaims,proto3,castrepeated=SavingsClaims" json:"savings_claims"` - EarnRewardState GenesisRewardState `protobuf:"bytes,13,opt,name=earn_reward_state,json=earnRewardState,proto3" json:"earn_reward_state"` - EarnClaims EarnClaims `protobuf:"bytes,14,rep,name=earn_claims,json=earnClaims,proto3,castrepeated=EarnClaims" json:"earn_claims"` -} - -func (m *GenesisState) Reset() { *m = GenesisState{} } -func (m *GenesisState) String() string { return proto.CompactTextString(m) } -func (*GenesisState) ProtoMessage() {} -func (*GenesisState) Descriptor() ([]byte, []int) { - return fileDescriptor_8b76737885d05afd, []int{2} -} -func (m *GenesisState) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisState) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisState.Merge(m, src) -} -func (m *GenesisState) XXX_Size() int { - return m.Size() -} -func (m *GenesisState) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisState.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisState proto.InternalMessageInfo - -func init() { - proto.RegisterType((*AccumulationTime)(nil), "kava.incentive.v1beta1.AccumulationTime") - proto.RegisterType((*GenesisRewardState)(nil), "kava.incentive.v1beta1.GenesisRewardState") - proto.RegisterType((*GenesisState)(nil), "kava.incentive.v1beta1.GenesisState") -} - -func init() { - proto.RegisterFile("kava/incentive/v1beta1/genesis.proto", fileDescriptor_8b76737885d05afd) -} - -var fileDescriptor_8b76737885d05afd = []byte{ - // 791 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x55, 0xcf, 0x4f, 0xdb, 0x48, - 0x14, 0x8e, 0x81, 0x65, 0x61, 0x02, 0x84, 0xcc, 0x06, 0xc8, 0x06, 0xc9, 0x61, 0x01, 0xed, 0x46, - 0xab, 0x5d, 0x1b, 0xb2, 0xd7, 0xbd, 0xac, 0x97, 0xd5, 0xb6, 0x55, 0x91, 0x90, 0x43, 0x51, 0x55, - 0x55, 0x8a, 0xc6, 0xf1, 0xe0, 0x4c, 0xeb, 0x5f, 0xf5, 0xd8, 0x09, 0xb9, 0xf5, 0xd8, 0x23, 0x7f, - 0x40, 0xa5, 0xde, 0xfb, 0x7f, 0x54, 0xe2, 0xc8, 0xb1, 0x27, 0x68, 0xc3, 0x3f, 0x52, 0xcd, 0x78, - 0x1c, 0xec, 0x04, 0x53, 0x35, 0xbd, 0x8d, 0xdf, 0x7c, 0xef, 0xfb, 0xbe, 0x37, 0xef, 0x8d, 0x07, - 0xec, 0xbe, 0x44, 0x3d, 0xa4, 0x12, 0xb7, 0x83, 0xdd, 0x90, 0xf4, 0xb0, 0xda, 0xdb, 0x37, 0x70, - 0x88, 0xf6, 0x55, 0x0b, 0xbb, 0x98, 0x12, 0xaa, 0xf8, 0x81, 0x17, 0x7a, 0x70, 0x9d, 0xa1, 0x94, - 0x11, 0x4a, 0x11, 0xa8, 0x5a, 0xc5, 0xf2, 0x2c, 0x8f, 0x43, 0x54, 0xb6, 0x8a, 0xd1, 0xb5, 0xba, - 0xe5, 0x79, 0x96, 0x8d, 0x55, 0xfe, 0x65, 0x44, 0xa7, 0x6a, 0x48, 0x1c, 0x4c, 0x43, 0xe4, 0xf8, - 0x02, 0xb0, 0x93, 0x23, 0xda, 0xb1, 0x11, 0x71, 0xe8, 0x57, 0x40, 0x3e, 0x0a, 0x50, 0x02, 0xda, - 0x7e, 0x27, 0x81, 0xd5, 0x7f, 0x3a, 0x9d, 0xc8, 0x89, 0x6c, 0x14, 0x12, 0xcf, 0x3d, 0x26, 0x0e, - 0x86, 0xbf, 0x81, 0x52, 0xc7, 0xb3, 0x6d, 0x14, 0xe2, 0x00, 0xd9, 0xed, 0x70, 0xe0, 0xe3, 0xaa, - 0xb4, 0x25, 0x35, 0x16, 0xf5, 0x95, 0xdb, 0xf0, 0xf1, 0xc0, 0xc7, 0xd0, 0x00, 0x35, 0x3f, 0xc0, - 0x3d, 0xe2, 0x45, 0xb4, 0x8d, 0x52, 0x2c, 0x6d, 0x66, 0xb8, 0x3a, 0xb3, 0x25, 0x35, 0x8a, 0xcd, - 0x9a, 0x12, 0x57, 0xa3, 0x24, 0xd5, 0x28, 0xc7, 0x49, 0x35, 0xda, 0xc2, 0xc5, 0x55, 0xbd, 0x70, - 0x7e, 0x5d, 0x97, 0xf4, 0x6a, 0xc2, 0x33, 0x6e, 0x66, 0xfb, 0xf5, 0x0c, 0x80, 0xff, 0xc7, 0x87, - 0xa9, 0xe3, 0x3e, 0x0a, 0xcc, 0x56, 0x88, 0x42, 0x0c, 0x03, 0x00, 0x27, 0x14, 0x69, 0x55, 0xda, - 0x9a, 0x6d, 0x14, 0x9b, 0x0d, 0xe5, 0xee, 0xe3, 0x56, 0xc6, 0xc9, 0xb5, 0x9f, 0x99, 0x81, 0xf7, - 0xd7, 0xf5, 0xf2, 0xf8, 0x0e, 0xd5, 0xcb, 0x68, 0x3c, 0x04, 0x7b, 0xa0, 0xe2, 0x44, 0x76, 0x48, - 0xda, 0x01, 0x37, 0xd2, 0x26, 0xae, 0x89, 0xcf, 0x30, 0xad, 0xce, 0xdc, 0xaf, 0x7a, 0xc8, 0x72, - 0x62, 0xef, 0x0f, 0x59, 0x86, 0x56, 0x13, 0xaa, 0x70, 0x7c, 0x07, 0x53, 0x1d, 0x3a, 0x13, 0xb1, - 0xed, 0x0f, 0x45, 0xb0, 0x24, 0x8e, 0x20, 0x2e, 0xfe, 0x6f, 0x30, 0x1f, 0x77, 0x91, 0xf7, 0xa5, - 0xd8, 0x94, 0xf3, 0xa4, 0x8f, 0x38, 0x4a, 0x9b, 0x63, 0x82, 0xba, 0xc8, 0x81, 0x1e, 0x28, 0x47, - 0xd4, 0x3c, 0x4b, 0xaa, 0xa0, 0x8c, 0x52, 0x34, 0xeb, 0xf7, 0x3c, 0xa2, 0xc9, 0x0e, 0x68, 0x1b, - 0x8c, 0x74, 0x78, 0x55, 0x2f, 0x3d, 0x69, 0x1d, 0x3c, 0x4d, 0x6d, 0xe8, 0x25, 0xc6, 0x9e, 0xee, - 0x15, 0x01, 0xd5, 0x2e, 0x57, 0x8a, 0x7c, 0xdf, 0x1e, 0x64, 0x75, 0x67, 0xbf, 0x59, 0x37, 0x2e, - 0x66, 0x8d, 0x31, 0xb6, 0x38, 0xe1, 0x5d, 0x52, 0x86, 0x17, 0x04, 0x5e, 0x3f, 0x2b, 0x35, 0xf7, - 0x3d, 0x52, 0x1a, 0x27, 0x4c, 0x4b, 0x9d, 0x82, 0x75, 0x13, 0xdb, 0xd8, 0x42, 0xa1, 0x17, 0x64, - 0x85, 0x7e, 0x98, 0x52, 0xa8, 0x32, 0xe2, 0x4b, 0xeb, 0x3c, 0x07, 0x65, 0xda, 0x47, 0x7e, 0x56, - 0x62, 0x7e, 0x4a, 0x89, 0x12, 0xa3, 0x4a, 0xb3, 0xbf, 0x91, 0xc0, 0x4f, 0x7c, 0x1a, 0x1c, 0xe2, - 0x86, 0xc4, 0xb5, 0xda, 0xf1, 0x3f, 0xa4, 0xfa, 0xe3, 0xfd, 0x33, 0xcd, 0x7a, 0x7e, 0x18, 0x67, - 0xfc, 0xcb, 0x12, 0x34, 0x45, 0x4c, 0x43, 0x79, 0x7c, 0x87, 0xb2, 0xeb, 0x35, 0x11, 0xd4, 0xf9, - 0x08, 0x66, 0x42, 0xf0, 0xad, 0x04, 0x64, 0xde, 0x3c, 0x9b, 0xbc, 0x8a, 0x88, 0x49, 0xc2, 0x41, - 0xdb, 0x0f, 0xbc, 0x1e, 0x31, 0x71, 0x90, 0xb8, 0x5a, 0xe0, 0xae, 0x9a, 0x79, 0xae, 0x1e, 0xa0, - 0xc0, 0x7c, 0x9c, 0x24, 0x1f, 0x89, 0xdc, 0xd8, 0xdf, 0x8e, 0xb8, 0x73, 0x9b, 0xf9, 0x18, 0xaa, - 0x6f, 0x76, 0xf3, 0x37, 0xe1, 0x0b, 0xb0, 0x7a, 0xdb, 0x6f, 0xe1, 0x67, 0x91, 0xfb, 0xf9, 0x35, - 0xcf, 0xcf, 0x41, 0x82, 0x8f, 0x3d, 0x6c, 0x08, 0x0f, 0xa5, 0x6c, 0x9c, 0xea, 0x25, 0x33, 0x1b, - 0x80, 0x27, 0xa0, 0xc8, 0x7b, 0x2e, 0x64, 0x00, 0x97, 0xf9, 0x25, 0x4f, 0xa6, 0xd5, 0x47, 0x7e, - 0xac, 0x00, 0x85, 0x02, 0x18, 0x85, 0xa8, 0x0e, 0xe8, 0x68, 0x0d, 0x0d, 0x50, 0xa1, 0xa8, 0x47, - 0x5c, 0x8b, 0x66, 0xc7, 0xa9, 0x38, 0xe5, 0x38, 0x41, 0xc1, 0x96, 0x9e, 0x28, 0x03, 0xac, 0x24, - 0x1a, 0xc2, 0xfe, 0x12, 0xb7, 0xbf, 0x9b, 0x6b, 0x3f, 0x46, 0xc7, 0x15, 0xac, 0x89, 0x0a, 0x96, - 0xd3, 0x51, 0xaa, 0x2f, 0xd3, 0xf4, 0x27, 0xbb, 0x13, 0x18, 0x05, 0x6e, 0xb6, 0x88, 0xe5, 0x69, - 0xef, 0x04, 0xa3, 0x4a, 0x57, 0x70, 0x02, 0x8a, 0x9c, 0x5d, 0xd8, 0x5f, 0xb9, 0xff, 0xf4, 0xff, - 0x43, 0x81, 0x3b, 0x76, 0xfa, 0xa3, 0x10, 0xd5, 0x01, 0x1e, 0xad, 0xb5, 0x47, 0x17, 0x9f, 0xe5, - 0xc2, 0xc5, 0x50, 0x96, 0x2e, 0x87, 0xb2, 0xf4, 0x69, 0x28, 0x4b, 0xe7, 0x37, 0x72, 0xe1, 0xf2, - 0x46, 0x2e, 0x7c, 0xbc, 0x91, 0x0b, 0xcf, 0xfe, 0xb0, 0x48, 0xd8, 0x8d, 0x0c, 0xa5, 0xe3, 0x39, - 0xea, 0x9e, 0x65, 0x23, 0x83, 0xaa, 0x7b, 0xd6, 0x9f, 0x9d, 0x2e, 0x22, 0xae, 0x7a, 0x96, 0x7a, - 0xc7, 0xd9, 0x7b, 0x4c, 0x8d, 0x79, 0xfe, 0x9c, 0xfe, 0xf5, 0x25, 0x00, 0x00, 0xff, 0xff, 0x00, - 0xb8, 0x69, 0x6c, 0x80, 0x08, 0x00, 0x00, -} - -func (m *AccumulationTime) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AccumulationTime) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AccumulationTime) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - n1, err1 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.PreviousAccumulationTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.PreviousAccumulationTime):]) - if err1 != nil { - return 0, err1 - } - i -= n1 - i = encodeVarintGenesis(dAtA, i, uint64(n1)) - i-- - dAtA[i] = 0x12 - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *GenesisRewardState) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisRewardState) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisRewardState) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.MultiRewardIndexes) > 0 { - for iNdEx := len(m.MultiRewardIndexes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.MultiRewardIndexes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.AccumulationTimes) > 0 { - for iNdEx := len(m.AccumulationTimes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.AccumulationTimes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *GenesisState) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.EarnClaims) > 0 { - for iNdEx := len(m.EarnClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.EarnClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x72 - } - } - { - size, err := m.EarnRewardState.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x6a - if len(m.SavingsClaims) > 0 { - for iNdEx := len(m.SavingsClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SavingsClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x62 - } - } - { - size, err := m.SavingsRewardState.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x5a - if len(m.SwapClaims) > 0 { - for iNdEx := len(m.SwapClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SwapClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x52 - } - } - if len(m.DelegatorClaims) > 0 { - for iNdEx := len(m.DelegatorClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DelegatorClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x4a - } - } - if len(m.HardLiquidityProviderClaims) > 0 { - for iNdEx := len(m.HardLiquidityProviderClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.HardLiquidityProviderClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - } - } - if len(m.USDXMintingClaims) > 0 { - for iNdEx := len(m.USDXMintingClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.USDXMintingClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - } - { - size, err := m.SwapRewardState.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size, err := m.DelegatorRewardState.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.HardBorrowRewardState.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.HardSupplyRewardState.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.USDXRewardState.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *AccumulationTime) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.PreviousAccumulationTime) - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *GenesisRewardState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.AccumulationTimes) > 0 { - for _, e := range m.AccumulationTimes { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.MultiRewardIndexes) > 0 { - for _, e := range m.MultiRewardIndexes { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func (m *GenesisState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.USDXRewardState.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.HardSupplyRewardState.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.HardBorrowRewardState.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.DelegatorRewardState.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.SwapRewardState.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.USDXMintingClaims) > 0 { - for _, e := range m.USDXMintingClaims { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.HardLiquidityProviderClaims) > 0 { - for _, e := range m.HardLiquidityProviderClaims { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.DelegatorClaims) > 0 { - for _, e := range m.DelegatorClaims { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.SwapClaims) > 0 { - for _, e := range m.SwapClaims { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - l = m.SavingsRewardState.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.SavingsClaims) > 0 { - for _, e := range m.SavingsClaims { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - l = m.EarnRewardState.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.EarnClaims) > 0 { - for _, e := range m.EarnClaims { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *AccumulationTime) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AccumulationTime: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AccumulationTime: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PreviousAccumulationTime", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.PreviousAccumulationTime, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *GenesisRewardState) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisRewardState: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisRewardState: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AccumulationTimes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.AccumulationTimes = append(m.AccumulationTimes, AccumulationTime{}) - if err := m.AccumulationTimes[len(m.AccumulationTimes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MultiRewardIndexes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MultiRewardIndexes = append(m.MultiRewardIndexes, MultiRewardIndex{}) - if err := m.MultiRewardIndexes[len(m.MultiRewardIndexes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *GenesisState) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field USDXRewardState", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.USDXRewardState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HardSupplyRewardState", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.HardSupplyRewardState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HardBorrowRewardState", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.HardBorrowRewardState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DelegatorRewardState", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.DelegatorRewardState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SwapRewardState", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.SwapRewardState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field USDXMintingClaims", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.USDXMintingClaims = append(m.USDXMintingClaims, USDXMintingClaim{}) - if err := m.USDXMintingClaims[len(m.USDXMintingClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HardLiquidityProviderClaims", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.HardLiquidityProviderClaims = append(m.HardLiquidityProviderClaims, HardLiquidityProviderClaim{}) - if err := m.HardLiquidityProviderClaims[len(m.HardLiquidityProviderClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DelegatorClaims", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DelegatorClaims = append(m.DelegatorClaims, DelegatorClaim{}) - if err := m.DelegatorClaims[len(m.DelegatorClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SwapClaims", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SwapClaims = append(m.SwapClaims, SwapClaim{}) - if err := m.SwapClaims[len(m.SwapClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 11: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SavingsRewardState", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.SavingsRewardState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 12: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SavingsClaims", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SavingsClaims = append(m.SavingsClaims, SavingsClaim{}) - if err := m.SavingsClaims[len(m.SavingsClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 13: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field EarnRewardState", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.EarnRewardState.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 14: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field EarnClaims", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.EarnClaims = append(m.EarnClaims, EarnClaim{}) - if err := m.EarnClaims[len(m.EarnClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/incentive/types/genesis_test.go b/x/incentive/types/genesis_test.go deleted file mode 100644 index 4cf95d2a..00000000 --- a/x/incentive/types/genesis_test.go +++ /dev/null @@ -1,191 +0,0 @@ -package types - -import ( - "strings" - "testing" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestGenesisState_Validate(t *testing.T) { - type errArgs struct { - expectPass bool - contains string - } - - testCases := []struct { - name string - genesis GenesisState - errArgs errArgs - }{ - { - name: "default", - genesis: DefaultGenesisState(), - errArgs: errArgs{ - expectPass: true, - }, - }, - { - name: "valid", - genesis: GenesisState{ - Params: NewParams( - RewardPeriods{ - NewRewardPeriod( - true, - "bnb-a", - time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - time.Date(2024, 10, 15, 14, 0, 0, 0, time.UTC), - sdk.NewCoin("ukava", sdkmath.NewInt(25000)), - ), - }, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - MultipliersPerDenoms{ - { - Denom: "ukava", - Multipliers: Multipliers{ - NewMultiplier("small", 1, sdk.MustNewDecFromStr("0.33")), - NewMultiplier("large", 12, sdk.MustNewDecFromStr("1.00")), - }, - }, - }, - time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - ), - USDXRewardState: GenesisRewardState{ - AccumulationTimes: AccumulationTimes{{ - CollateralType: "bnb-a", - PreviousAccumulationTime: time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - }}, - MultiRewardIndexes: MultiRewardIndexes{{ - CollateralType: "bnb-a", - RewardIndexes: normalRewardIndexes, - }}, - }, - USDXMintingClaims: USDXMintingClaims{ - { - BaseClaim: BaseClaim{ - Owner: sdk.AccAddress(crypto.AddressHash([]byte("KavaTestUser1"))), - Reward: sdk.NewCoin("ukava", sdkmath.NewInt(100000000)), - }, - RewardIndexes: []RewardIndex{ - { - CollateralType: "bnb-a", - RewardFactor: sdk.ZeroDec(), - }, - }, - }, - }, - }, - errArgs: errArgs{ - expectPass: true, - }, - }, - { - name: "invalid genesis accumulation time", - genesis: GenesisState{ - Params: DefaultParams(), - USDXRewardState: GenesisRewardState{ - AccumulationTimes: AccumulationTimes{{ - CollateralType: "", - PreviousAccumulationTime: time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - }}, - MultiRewardIndexes: MultiRewardIndexes{{ - CollateralType: "bnb-a", - RewardIndexes: normalRewardIndexes, - }}, - }, - USDXMintingClaims: DefaultUSDXClaims, - }, - errArgs: errArgs{ - expectPass: false, - contains: "collateral type must be defined", - }, - }, - { - name: "invalid claim", - genesis: GenesisState{ - Params: DefaultParams(), - USDXRewardState: DefaultGenesisRewardState, - USDXMintingClaims: USDXMintingClaims{ - { - BaseClaim: BaseClaim{ - Owner: nil, // invalid address - Reward: sdk.NewCoin("ukava", sdkmath.NewInt(100000000)), - }, - RewardIndexes: []RewardIndex{ - { - CollateralType: "bnb-a", - RewardFactor: sdk.ZeroDec(), - }, - }, - }, - }, - }, - errArgs: errArgs{ - expectPass: false, - contains: "claim owner cannot be empty", - }, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.genesis.Validate() - if tc.errArgs.expectPass { - require.NoError(t, err, tc.name) - } else { - require.Error(t, err, tc.name) - require.True(t, strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func TestGenesisAccumulationTimes_Validate(t *testing.T) { - testCases := []struct { - name string - gats AccumulationTimes - wantErr bool - }{ - { - name: "normal", - gats: AccumulationTimes{ - {CollateralType: "btcb", PreviousAccumulationTime: normalAccumulationtime}, - {CollateralType: "bnb", PreviousAccumulationTime: normalAccumulationtime}, - }, - wantErr: false, - }, - { - name: "empty", - gats: nil, - wantErr: false, - }, - { - name: "empty collateral type", - gats: AccumulationTimes{ - {PreviousAccumulationTime: normalAccumulationtime}, - }, - wantErr: true, - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.gats.Validate() - if tc.wantErr { - require.NotNil(t, err) - } else { - require.Nil(t, err) - } - }) - } -} - -var normalAccumulationtime = time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) diff --git a/x/incentive/types/keys.go b/x/incentive/types/keys.go deleted file mode 100644 index 803a8e18..00000000 --- a/x/incentive/types/keys.go +++ /dev/null @@ -1,39 +0,0 @@ -package types - -const ( - // ModuleName The name that will be used throughout the module - ModuleName = "incentive" - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey Top level router key - RouterKey = ModuleName - - // DefaultParamspace default name for parameter store - DefaultParamspace = ModuleName -) - -// Key Prefixes -var ( - USDXMintingClaimKeyPrefix = []byte{0x01} // prefix for keys that store USDX minting claims - USDXMintingRewardFactorKeyPrefix = []byte{0x02} // prefix for key that stores USDX minting reward factors - PreviousUSDXMintingRewardAccrualTimeKeyPrefix = []byte{0x03} // prefix for key that stores the blocktime - HardLiquidityClaimKeyPrefix = []byte{0x04} // prefix for keys that store Hard liquidity claims - HardSupplyRewardIndexesKeyPrefix = []byte{0x05} // prefix for key that stores Hard supply reward indexes - PreviousHardSupplyRewardAccrualTimeKeyPrefix = []byte{0x06} // prefix for key that stores the previous time Hard supply rewards accrued - HardBorrowRewardIndexesKeyPrefix = []byte{0x07} // prefix for key that stores Hard borrow reward indexes - PreviousHardBorrowRewardAccrualTimeKeyPrefix = []byte{0x08} // prefix for key that stores the previous time Hard borrow rewards accrued - DelegatorClaimKeyPrefix = []byte{0x09} // prefix for keys that store delegator claims - DelegatorRewardIndexesKeyPrefix = []byte{0x10} // prefix for key that stores delegator reward indexes - PreviousDelegatorRewardAccrualTimeKeyPrefix = []byte{0x11} // prefix for key that stores the previous time delegator rewards accrued - SwapClaimKeyPrefix = []byte{0x12} // prefix for keys that store swap claims - SwapRewardIndexesKeyPrefix = []byte{0x13} // prefix for key that stores swap reward indexes - PreviousSwapRewardAccrualTimeKeyPrefix = []byte{0x14} // prefix for key that stores the previous time swap rewards accrued - SavingsClaimKeyPrefix = []byte{0x15} // prefix for keys that store savings claims - SavingsRewardIndexesKeyPrefix = []byte{0x16} // prefix for key that stores savings reward indexes - PreviousSavingsRewardAccrualTimeKeyPrefix = []byte{0x17} // prefix for key that stores the previous time savings rewards accrued - EarnClaimKeyPrefix = []byte{0x18} // prefix for keys that store earn claims - EarnRewardIndexesKeyPrefix = []byte{0x19} // prefix for key that stores earn reward indexes - PreviousEarnRewardAccrualTimeKeyPrefix = []byte{0x20} // prefix for key that stores the previous time earn rewards accrued -) diff --git a/x/incentive/types/msg.go b/x/incentive/types/msg.go deleted file mode 100644 index c4ef901f..00000000 --- a/x/incentive/types/msg.go +++ /dev/null @@ -1,292 +0,0 @@ -package types - -import ( - 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/auth/migrations/legacytx" -) - -const MaxDenomsToClaim = 1000 - -// ensure Msg interface compliance at compile time -var ( - _ sdk.Msg = &MsgClaimUSDXMintingReward{} - _ sdk.Msg = &MsgClaimHardReward{} - _ sdk.Msg = &MsgClaimDelegatorReward{} - _ sdk.Msg = &MsgClaimSwapReward{} - _ sdk.Msg = &MsgClaimSavingsReward{} - _ sdk.Msg = &MsgClaimEarnReward{} - - _ legacytx.LegacyMsg = &MsgClaimUSDXMintingReward{} - _ legacytx.LegacyMsg = &MsgClaimHardReward{} - _ legacytx.LegacyMsg = &MsgClaimDelegatorReward{} - _ legacytx.LegacyMsg = &MsgClaimSwapReward{} - _ legacytx.LegacyMsg = &MsgClaimSavingsReward{} - _ legacytx.LegacyMsg = &MsgClaimEarnReward{} -) - -const ( - TypeMsgClaimUSDXMintingReward = "claim_usdx_minting_reward" - TypeMsgClaimHardReward = "claim_hard_reward" - TypeMsgClaimDelegatorReward = "claim_delegator_reward" - TypeMsgClaimSwapReward = "claim_swap_reward" - TypeMsgClaimSavingsReward = "claim_savings_reward" - TypeMsgClaimEarnReward = "claim_earn_reward" -) - -// NewMsgClaimUSDXMintingReward returns a new MsgClaimUSDXMintingReward. -func NewMsgClaimUSDXMintingReward(sender string, multiplierName string) MsgClaimUSDXMintingReward { - return MsgClaimUSDXMintingReward{ - Sender: sender, - MultiplierName: multiplierName, - } -} - -// Route return the message type used for routing the message. -func (msg MsgClaimUSDXMintingReward) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgClaimUSDXMintingReward) Type() string { return TypeMsgClaimUSDXMintingReward } - -// ValidateBasic does a simple validation check that doesn't require access to state. -func (msg MsgClaimUSDXMintingReward) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty or invalid") - } - if msg.MultiplierName == "" { - return errorsmod.Wrap(ErrInvalidMultiplier, "multiplier name cannot be empty") - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgClaimUSDXMintingReward) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgClaimUSDXMintingReward) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgClaimHardReward returns a new MsgClaimHardReward. -func NewMsgClaimHardReward(sender string, denomsToClaim Selections) MsgClaimHardReward { - return MsgClaimHardReward{ - Sender: sender, - DenomsToClaim: denomsToClaim, - } -} - -// Route return the message type used for routing the message. -func (msg MsgClaimHardReward) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgClaimHardReward) Type() string { - return TypeMsgClaimHardReward -} - -// ValidateBasic does a simple validation check that doesn't require access to state. -func (msg MsgClaimHardReward) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty or invalid") - } - if err := msg.DenomsToClaim.Validate(); err != nil { - return err - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgClaimHardReward) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgClaimHardReward) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgClaimDelegatorReward returns a new MsgClaimDelegatorReward. -func NewMsgClaimDelegatorReward(sender string, denomsToClaim Selections) MsgClaimDelegatorReward { - return MsgClaimDelegatorReward{ - Sender: sender, - DenomsToClaim: denomsToClaim, - } -} - -// Route return the message type used for routing the message. -func (msg MsgClaimDelegatorReward) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgClaimDelegatorReward) Type() string { - return TypeMsgClaimDelegatorReward -} - -// ValidateBasic does a simple validation check that doesn't require access to state. -func (msg MsgClaimDelegatorReward) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty or invalid") - } - if err := msg.DenomsToClaim.Validate(); err != nil { - return err - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgClaimDelegatorReward) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgClaimDelegatorReward) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgClaimSwapReward returns a new MsgClaimSwapReward. -func NewMsgClaimSwapReward(sender string, denomsToClaim Selections) MsgClaimSwapReward { - return MsgClaimSwapReward{ - Sender: sender, - DenomsToClaim: denomsToClaim, - } -} - -// Route return the message type used for routing the message. -func (msg MsgClaimSwapReward) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgClaimSwapReward) Type() string { - return TypeMsgClaimSwapReward -} - -// ValidateBasic does a simple validation check that doesn't require access to state. -func (msg MsgClaimSwapReward) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty or invalid") - } - if err := msg.DenomsToClaim.Validate(); err != nil { - return err - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgClaimSwapReward) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgClaimSwapReward) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgClaimSavingsReward returns a new MsgClaimSavingsReward. -func NewMsgClaimSavingsReward(sender string, denomsToClaim Selections) MsgClaimSavingsReward { - return MsgClaimSavingsReward{ - Sender: sender, - DenomsToClaim: denomsToClaim, - } -} - -// Route return the message type used for routing the message. -func (msg MsgClaimSavingsReward) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgClaimSavingsReward) Type() string { - return TypeMsgClaimSavingsReward -} - -// ValidateBasic does a simple validation check that doesn't require access to state. -func (msg MsgClaimSavingsReward) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty or invalid") - } - if err := msg.DenomsToClaim.Validate(); err != nil { - return err - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgClaimSavingsReward) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgClaimSavingsReward) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgClaimEarnReward returns a new MsgClaimEarnReward. -func NewMsgClaimEarnReward(sender string, denomsToClaim Selections) MsgClaimEarnReward { - return MsgClaimEarnReward{ - Sender: sender, - DenomsToClaim: denomsToClaim, - } -} - -// Route return the message type used for routing the message. -func (msg MsgClaimEarnReward) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgClaimEarnReward) Type() string { - return TypeMsgClaimEarnReward -} - -// ValidateBasic does a simple validation check that doesn't require access to state. -func (msg MsgClaimEarnReward) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty or invalid") - } - if err := msg.DenomsToClaim.Validate(); err != nil { - return err - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgClaimEarnReward) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgClaimEarnReward) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} diff --git a/x/incentive/types/msg_test.go b/x/incentive/types/msg_test.go deleted file mode 100644 index 2b15c921..00000000 --- a/x/incentive/types/msg_test.go +++ /dev/null @@ -1,233 +0,0 @@ -package types_test - -import ( - "errors" - "fmt" - "testing" - - "github.com/cometbft/cometbft/crypto" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/require" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -func TestMsgClaim_Validate(t *testing.T) { - validAddress := sdk.AccAddress(crypto.AddressHash([]byte("KavaTest1"))).String() - - type expectedErr struct { - wraps error - pass bool - } - type msgArgs struct { - sender string - denomsToClaim types.Selections - } - tests := []struct { - name string - msgArgs msgArgs - expect expectedErr - }{ - { - name: "normal multiplier is valid", - msgArgs: msgArgs{ - sender: validAddress, - denomsToClaim: types.Selections{ - { - Denom: "hard", - MultiplierName: "large", - }, - }, - }, - expect: expectedErr{ - pass: true, - }, - }, - { - name: "empty multiplier name is invalid", - msgArgs: msgArgs{ - sender: validAddress, - denomsToClaim: types.Selections{ - { - Denom: "hard", - MultiplierName: "", - }, - }, - }, - expect: expectedErr{ - wraps: types.ErrInvalidMultiplier, - }, - }, - { - name: "empty denoms to claim is not valid", - msgArgs: msgArgs{ - sender: validAddress, - denomsToClaim: types.Selections{}, - }, - expect: expectedErr{ - wraps: types.ErrInvalidClaimDenoms, - }, - }, - { - name: "nil denoms to claim is not valid", - msgArgs: msgArgs{ - sender: validAddress, - denomsToClaim: nil, - }, - expect: expectedErr{ - wraps: types.ErrInvalidClaimDenoms, - }, - }, - { - name: "invalid sender", - msgArgs: msgArgs{ - sender: "", - denomsToClaim: types.Selections{ - { - Denom: "hard", - MultiplierName: "medium", - }, - }, - }, - expect: expectedErr{ - wraps: sdkerrors.ErrInvalidAddress, - }, - }, - { - name: "invalid claim denom", - msgArgs: msgArgs{ - sender: validAddress, - denomsToClaim: types.Selections{ - { - Denom: "a denom string that is invalid because it is much too long", - MultiplierName: "medium", - }, - }, - }, - expect: expectedErr{ - wraps: types.ErrInvalidClaimDenoms, - }, - }, - { - name: "too many claim denoms", - msgArgs: msgArgs{ - sender: validAddress, - denomsToClaim: tooManySelections(), - }, - expect: expectedErr{ - wraps: types.ErrInvalidClaimDenoms, - }, - }, - { - name: "duplicated claim denoms", - msgArgs: msgArgs{ - sender: validAddress, - denomsToClaim: types.Selections{ - { - Denom: "hard", - MultiplierName: "medium", - }, - { - Denom: "hard", - MultiplierName: "large", - }, - }, - }, - expect: expectedErr{ - wraps: types.ErrInvalidClaimDenoms, - }, - }, - } - - for _, tc := range tests { - msgClaimHardReward := types.NewMsgClaimHardReward(tc.msgArgs.sender, tc.msgArgs.denomsToClaim) - msgClaimDelegatorReward := types.NewMsgClaimDelegatorReward(tc.msgArgs.sender, tc.msgArgs.denomsToClaim) - msgClaimSwapReward := types.NewMsgClaimSwapReward(tc.msgArgs.sender, tc.msgArgs.denomsToClaim) - msgClaimSavingsReward := types.NewMsgClaimSavingsReward(tc.msgArgs.sender, tc.msgArgs.denomsToClaim) - msgs := []sdk.Msg{&msgClaimHardReward, &msgClaimDelegatorReward, &msgClaimSwapReward, &msgClaimSavingsReward} - for _, msg := range msgs { - t.Run(tc.name, func(t *testing.T) { - err := msg.ValidateBasic() - if tc.expect.pass { - require.NoError(t, err) - } else { - require.Truef(t, errors.Is(err, tc.expect.wraps), "expected error '%s' was not actual '%s'", tc.expect.wraps, err) - } - }) - } - } -} - -func TestMsgClaimUSDXMintingReward_Validate(t *testing.T) { - validAddress := sdk.AccAddress(crypto.AddressHash([]byte("KavaTest1"))).String() - - type expectedErr struct { - wraps error - pass bool - } - type msgArgs struct { - sender string - multiplierName string - } - tests := []struct { - name string - msgArgs msgArgs - expect expectedErr - }{ - { - name: "normal multiplier is valid", - msgArgs: msgArgs{ - sender: validAddress, - multiplierName: "large", - }, - expect: expectedErr{ - pass: true, - }, - }, - { - name: "invalid sender", - msgArgs: msgArgs{ - sender: "", - multiplierName: "medium", - }, - expect: expectedErr{ - wraps: sdkerrors.ErrInvalidAddress, - }, - }, - { - name: "empty multiplier is invalid", - msgArgs: msgArgs{ - sender: validAddress, - multiplierName: "", - }, - expect: expectedErr{ - wraps: types.ErrInvalidMultiplier, - }, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - msg := types.NewMsgClaimUSDXMintingReward(tc.msgArgs.sender, tc.msgArgs.multiplierName) - - err := msg.ValidateBasic() - if tc.expect.pass { - require.NoError(t, err) - } else { - require.Truef(t, errors.Is(err, tc.expect.wraps), "expected error '%s' was not actual '%s'", tc.expect.wraps, err) - } - }) - } -} - -func tooManySelections() types.Selections { - selections := make(types.Selections, types.MaxDenomsToClaim+1) - for i := range selections { - selections[i] = types.Selection{ - Denom: fmt.Sprintf("denom%d", i), - MultiplierName: "large", - } - } - return selections -} diff --git a/x/incentive/types/multipliers.go b/x/incentive/types/multipliers.go deleted file mode 100644 index 689bea64..00000000 --- a/x/incentive/types/multipliers.go +++ /dev/null @@ -1,139 +0,0 @@ -package types - -import ( - "fmt" - "sort" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// NewMultiplier returns a new Multiplier -func NewMultiplier(name string, lockup int64, factor sdk.Dec) Multiplier { - return Multiplier{ - Name: name, - MonthsLockup: lockup, - Factor: factor, - } -} - -// Validate multiplier param -func (m Multiplier) Validate() error { - if m.Name == "" { - return fmt.Errorf("expected non empty name") - } - if m.MonthsLockup < 0 { - return fmt.Errorf("expected non-negative lockup, got %d", m.MonthsLockup) - } - if m.Factor.IsNegative() { - return fmt.Errorf("expected non-negative factor, got %s", m.Factor.String()) - } - - return nil -} - -// Multipliers is a slice of Multiplier -type Multipliers []Multiplier - -// Validate validates each multiplier -func (ms Multipliers) Validate() error { - for _, m := range ms { - if err := m.Validate(); err != nil { - return err - } - } - return nil -} - -// Get returns a multiplier with a matching name -func (ms Multipliers) Get(name string) (Multiplier, bool) { - for _, m := range ms { - if m.Name == name { - return m, true - } - } - return Multiplier{}, false -} - -// MultipliersPerDenoms is a slice of MultipliersPerDenom -type MultipliersPerDenoms []MultipliersPerDenom - -// Validate checks each denom and multipliers for invalid values. -func (mpd MultipliersPerDenoms) Validate() error { - foundDenoms := map[string]bool{} - - for _, item := range mpd { - if err := sdk.ValidateDenom(item.Denom); err != nil { - return err - } - if err := item.Multipliers.Validate(); err != nil { - return err - } - - if foundDenoms[item.Denom] { - return fmt.Errorf("duplicate denom %s", item.Denom) - } - foundDenoms[item.Denom] = true - } - return nil -} - -// NewSelection returns a new Selection -func NewSelection(denom, multiplierName string) Selection { - return Selection{ - Denom: denom, - MultiplierName: multiplierName, - } -} - -// Validate performs basic validation checks -func (s Selection) Validate() error { - if err := sdk.ValidateDenom(s.Denom); err != nil { - return errorsmod.Wrap(ErrInvalidClaimDenoms, err.Error()) - } - if s.MultiplierName == "" { - return errorsmod.Wrap(ErrInvalidMultiplier, "multiplier name cannot be empty") - } - return nil -} - -// Selections are a list of denom - multiplier pairs that specify what rewards to claim and with what lockups. -type Selections []Selection - -// NewSelectionsFromMap creates a new set of selections from a string to string map. -// It sorts the output before returning. -func NewSelectionsFromMap(selectionMap map[string]string) Selections { - var selections Selections - for k, v := range selectionMap { - selections = append(selections, NewSelection(k, v)) - } - // deterministically sort the slice to protect against the random range order causing consensus failures - sort.Slice(selections, func(i, j int) bool { - if selections[i].Denom != selections[j].Denom { - return selections[i].Denom < selections[j].Denom - } - return selections[i].MultiplierName < selections[j].MultiplierName - }) - return selections -} - -// Valdate performs basic validaton checks -func (ss Selections) Validate() error { - if len(ss) == 0 { - return errorsmod.Wrap(ErrInvalidClaimDenoms, "cannot claim 0 denoms") - } - if len(ss) >= MaxDenomsToClaim { - return errorsmod.Wrapf(ErrInvalidClaimDenoms, "cannot claim more than %d denoms", MaxDenomsToClaim) - } - foundDenoms := map[string]bool{} - for _, s := range ss { - if err := s.Validate(); err != nil { - return err - } - if foundDenoms[s.Denom] { - return errorsmod.Wrapf(ErrInvalidClaimDenoms, "cannot claim denom '%s' more than once", s.Denom) - } - foundDenoms[s.Denom] = true - } - return nil -} diff --git a/x/incentive/types/params.go b/x/incentive/types/params.go deleted file mode 100644 index 396f3505..00000000 --- a/x/incentive/types/params.go +++ /dev/null @@ -1,315 +0,0 @@ -package types - -import ( - "errors" - "fmt" - "strings" - "time" - - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - - kavadistTypes "github.com/0glabs/0g-chain/x/kavadist/types" -) - -// Parameter keys and default values -var ( - KeyUSDXMintingRewardPeriods = []byte("USDXMintingRewardPeriods") - KeyHardSupplyRewardPeriods = []byte("HardSupplyRewardPeriods") - KeyHardBorrowRewardPeriods = []byte("HardBorrowRewardPeriods") - KeyDelegatorRewardPeriods = []byte("DelegatorRewardPeriods") - KeySwapRewardPeriods = []byte("SwapRewardPeriods") - KeySavingsRewardPeriods = []byte("SavingsRewardPeriods") - KeyEarnRewardPeriods = []byte("EarnRewardPeriods") - KeyClaimEnd = []byte("ClaimEnd") - KeyMultipliers = []byte("ClaimMultipliers") - - DefaultActive = false - DefaultRewardPeriods = RewardPeriods{} - DefaultMultiRewardPeriods = MultiRewardPeriods{} - DefaultMultipliers = MultipliersPerDenoms{} - DefaultClaimEnd = tmtime.Canonical(time.Unix(1, 0)) - - BondDenom = "ukava" - USDXMintingRewardDenom = "ukava" - - IncentiveMacc = kavadistTypes.ModuleName -) - -// NewParams returns a new params object -func NewParams( - usdxMinting RewardPeriods, - // MultiRewardPeriods - hardSupply, hardBorrow, delegator, swap, savings, earn MultiRewardPeriods, - multipliers MultipliersPerDenoms, - claimEnd time.Time, -) Params { - return Params{ - USDXMintingRewardPeriods: usdxMinting, - HardSupplyRewardPeriods: hardSupply, - HardBorrowRewardPeriods: hardBorrow, - DelegatorRewardPeriods: delegator, - SwapRewardPeriods: swap, - SavingsRewardPeriods: savings, - ClaimMultipliers: multipliers, - ClaimEnd: claimEnd, - } -} - -// DefaultParams returns default params for incentive module -func DefaultParams() Params { - return NewParams( - DefaultRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultiRewardPeriods, - DefaultMultipliers, - DefaultClaimEnd, - ) -} - -// ParamKeyTable Key declaration for parameters -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements the ParamSet interface and returns all the key/value pairs -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyUSDXMintingRewardPeriods, &p.USDXMintingRewardPeriods, validateRewardPeriodsParam), - paramtypes.NewParamSetPair(KeyHardSupplyRewardPeriods, &p.HardSupplyRewardPeriods, validateMultiRewardPeriodsParam), - paramtypes.NewParamSetPair(KeyHardBorrowRewardPeriods, &p.HardBorrowRewardPeriods, validateMultiRewardPeriodsParam), - paramtypes.NewParamSetPair(KeyDelegatorRewardPeriods, &p.DelegatorRewardPeriods, validateMultiRewardPeriodsParam), - paramtypes.NewParamSetPair(KeySwapRewardPeriods, &p.SwapRewardPeriods, validateMultiRewardPeriodsParam), - paramtypes.NewParamSetPair(KeySavingsRewardPeriods, &p.SavingsRewardPeriods, validateMultiRewardPeriodsParam), - paramtypes.NewParamSetPair(KeyEarnRewardPeriods, &p.EarnRewardPeriods, validateMultiRewardPeriodsParam), - paramtypes.NewParamSetPair(KeyMultipliers, &p.ClaimMultipliers, validateMultipliersPerDenomParam), - paramtypes.NewParamSetPair(KeyClaimEnd, &p.ClaimEnd, validateClaimEndParam), - } -} - -// Validate checks that the parameters have valid values. -func (p Params) Validate() error { - if err := validateMultipliersPerDenomParam(p.ClaimMultipliers); err != nil { - return err - } - - if err := validateRewardPeriodsParam(p.USDXMintingRewardPeriods); err != nil { - return err - } - - if err := validateMultiRewardPeriodsParam(p.HardSupplyRewardPeriods); err != nil { - return err - } - - if err := validateMultiRewardPeriodsParam(p.HardBorrowRewardPeriods); err != nil { - return err - } - - if err := validateMultiRewardPeriodsParam(p.DelegatorRewardPeriods); err != nil { - return err - } - - if err := validateMultiRewardPeriodsParam(p.SwapRewardPeriods); err != nil { - return err - } - - if err := validateMultiRewardPeriodsParam(p.SavingsRewardPeriods); err != nil { - return err - } - - if err := validateMultiRewardPeriodsParam(p.EarnRewardPeriods); err != nil { - return err - } - - return nil -} - -func validateRewardPeriodsParam(i interface{}) error { - rewards, ok := i.(RewardPeriods) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return rewards.Validate() -} - -func validateMultiRewardPeriodsParam(i interface{}) error { - rewards, ok := i.(MultiRewardPeriods) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return rewards.Validate() -} - -func validateMultipliersPerDenomParam(i interface{}) error { - multipliers, ok := i.(MultipliersPerDenoms) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - return multipliers.Validate() -} - -func validateClaimEndParam(i interface{}) error { - endTime, ok := i.(time.Time) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - if endTime.Unix() <= 0 { - return fmt.Errorf("end time should not be zero") - } - return nil -} - -// NewRewardPeriod returns a new RewardPeriod -func NewRewardPeriod(active bool, collateralType string, start time.Time, end time.Time, reward sdk.Coin) RewardPeriod { - return RewardPeriod{ - Active: active, - CollateralType: collateralType, - Start: start, - End: end, - RewardsPerSecond: reward, - } -} - -// NewMultiRewardPeriodFromRewardPeriod converts a RewardPeriod into a MultiRewardPeriod. -// It's useful for compatibility between single and multi denom rewards. -func NewMultiRewardPeriodFromRewardPeriod(period RewardPeriod) MultiRewardPeriod { - return NewMultiRewardPeriod( - period.Active, - period.CollateralType, - period.Start, - period.End, - sdk.NewCoins(period.RewardsPerSecond), - ) -} - -// Validate performs a basic check of a RewardPeriod fields. -func (rp RewardPeriod) Validate() error { - if rp.Start.Unix() <= 0 { - return errors.New("reward period start time cannot be 0") - } - if rp.End.Unix() <= 0 { - return errors.New("reward period end time cannot be 0") - } - if rp.Start.After(rp.End) { - // This is needed to ensure that the begin blocker accumulation does not panic. - return fmt.Errorf("end period time %s cannot be before start time %s", rp.End, rp.Start) - } - if rp.RewardsPerSecond.Denom != USDXMintingRewardDenom { - return fmt.Errorf("reward denom must be %s, got: %s", USDXMintingRewardDenom, rp.RewardsPerSecond.Denom) - } - if !rp.RewardsPerSecond.IsValid() { - return fmt.Errorf("invalid reward amount: %s", rp.RewardsPerSecond) - } - - if rp.RewardsPerSecond.Amount.IsZero() { - return fmt.Errorf("reward amount cannot be zero: %v", rp.RewardsPerSecond) - } - - if strings.TrimSpace(rp.CollateralType) == "" { - return fmt.Errorf("reward period collateral type cannot be blank: %v", rp) - } - return nil -} - -// RewardPeriods array of RewardPeriod -type RewardPeriods []RewardPeriod - -// Validate checks if all the RewardPeriods are valid and there are no duplicated -// entries. -func (rps RewardPeriods) Validate() error { - seenPeriods := make(map[string]bool) - for _, rp := range rps { - if seenPeriods[rp.CollateralType] { - return fmt.Errorf("duplicated reward period with collateral type %s", rp.CollateralType) - } - - if err := rp.Validate(); err != nil { - return err - } - seenPeriods[rp.CollateralType] = true - } - - return nil -} - -// NewMultiRewardPeriod returns a new MultiRewardPeriod -func NewMultiRewardPeriod(active bool, collateralType string, start time.Time, end time.Time, reward sdk.Coins) MultiRewardPeriod { - return MultiRewardPeriod{ - Active: active, - CollateralType: collateralType, - Start: start, - End: end, - RewardsPerSecond: reward, - } -} - -// Validate performs a basic check of a MultiRewardPeriod. -func (mrp MultiRewardPeriod) Validate() error { - if mrp.Start.IsZero() { - return errors.New("reward period start time cannot be 0") - } - if mrp.End.IsZero() { - return errors.New("reward period end time cannot be 0") - } - if mrp.Start.After(mrp.End) { - // This is needed to ensure that the begin blocker accumulation does not panic. - return fmt.Errorf("end period time %s cannot be before start time %s", mrp.End, mrp.Start) - } - - // This also ensures there are no 0 amount coins. - if !mrp.RewardsPerSecond.IsValid() { - return fmt.Errorf("invalid reward amount: %s", mrp.RewardsPerSecond) - } - if strings.TrimSpace(mrp.CollateralType) == "" { - return fmt.Errorf("reward period collateral type cannot be blank: %v", mrp) - } - return nil -} - -// MultiRewardPeriods array of MultiRewardPeriod -type MultiRewardPeriods []MultiRewardPeriod - -// GetMultiRewardPeriod fetches a MultiRewardPeriod from an array of MultiRewardPeriods by its denom -func (mrps MultiRewardPeriods) GetMultiRewardPeriod(denom string) (MultiRewardPeriod, bool) { - for _, rp := range mrps { - if rp.CollateralType == denom { - return rp, true - } - } - return MultiRewardPeriod{}, false -} - -// GetMultiRewardPeriodIndex returns the index of a MultiRewardPeriod inside array MultiRewardPeriods -func (mrps MultiRewardPeriods) GetMultiRewardPeriodIndex(denom string) (int, bool) { - for i, rp := range mrps { - if rp.CollateralType == denom { - return i, true - } - } - return -1, false -} - -// Validate checks if all the RewardPeriods are valid and there are no duplicated -// entries. -func (mrps MultiRewardPeriods) Validate() error { - seenPeriods := make(map[string]bool) - for _, rp := range mrps { - if seenPeriods[rp.CollateralType] { - return fmt.Errorf("duplicated reward period with collateral type %s", rp.CollateralType) - } - - if err := rp.Validate(); err != nil { - return err - } - seenPeriods[rp.CollateralType] = true - } - - return nil -} diff --git a/x/incentive/types/params.pb.go b/x/incentive/types/params.pb.go deleted file mode 100644 index 08b5c414..00000000 --- a/x/incentive/types/params.pb.go +++ /dev/null @@ -1,1926 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/incentive/v1beta1/params.proto - -package types - -import ( - fmt "fmt" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// RewardPeriod stores the state of an ongoing reward -type RewardPeriod struct { - Active bool `protobuf:"varint,1,opt,name=active,proto3" json:"active,omitempty"` - CollateralType string `protobuf:"bytes,2,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Start time.Time `protobuf:"bytes,3,opt,name=start,proto3,stdtime" json:"start"` - End time.Time `protobuf:"bytes,4,opt,name=end,proto3,stdtime" json:"end"` - RewardsPerSecond types.Coin `protobuf:"bytes,5,opt,name=rewards_per_second,json=rewardsPerSecond,proto3" json:"rewards_per_second"` -} - -func (m *RewardPeriod) Reset() { *m = RewardPeriod{} } -func (m *RewardPeriod) String() string { return proto.CompactTextString(m) } -func (*RewardPeriod) ProtoMessage() {} -func (*RewardPeriod) Descriptor() ([]byte, []int) { - return fileDescriptor_bb8833f5d745eac9, []int{0} -} -func (m *RewardPeriod) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *RewardPeriod) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_RewardPeriod.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *RewardPeriod) XXX_Merge(src proto.Message) { - xxx_messageInfo_RewardPeriod.Merge(m, src) -} -func (m *RewardPeriod) XXX_Size() int { - return m.Size() -} -func (m *RewardPeriod) XXX_DiscardUnknown() { - xxx_messageInfo_RewardPeriod.DiscardUnknown(m) -} - -var xxx_messageInfo_RewardPeriod proto.InternalMessageInfo - -// MultiRewardPeriod supports multiple reward types -type MultiRewardPeriod struct { - Active bool `protobuf:"varint,1,opt,name=active,proto3" json:"active,omitempty"` - CollateralType string `protobuf:"bytes,2,opt,name=collateral_type,json=collateralType,proto3" json:"collateral_type,omitempty"` - Start time.Time `protobuf:"bytes,3,opt,name=start,proto3,stdtime" json:"start"` - End time.Time `protobuf:"bytes,4,opt,name=end,proto3,stdtime" json:"end"` - RewardsPerSecond github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,5,rep,name=rewards_per_second,json=rewardsPerSecond,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"rewards_per_second"` -} - -func (m *MultiRewardPeriod) Reset() { *m = MultiRewardPeriod{} } -func (m *MultiRewardPeriod) String() string { return proto.CompactTextString(m) } -func (*MultiRewardPeriod) ProtoMessage() {} -func (*MultiRewardPeriod) Descriptor() ([]byte, []int) { - return fileDescriptor_bb8833f5d745eac9, []int{1} -} -func (m *MultiRewardPeriod) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MultiRewardPeriod) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MultiRewardPeriod.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MultiRewardPeriod) XXX_Merge(src proto.Message) { - xxx_messageInfo_MultiRewardPeriod.Merge(m, src) -} -func (m *MultiRewardPeriod) XXX_Size() int { - return m.Size() -} -func (m *MultiRewardPeriod) XXX_DiscardUnknown() { - xxx_messageInfo_MultiRewardPeriod.DiscardUnknown(m) -} - -var xxx_messageInfo_MultiRewardPeriod proto.InternalMessageInfo - -// Multiplier amount the claim rewards get increased by, along with how long the claim rewards are locked -type Multiplier struct { - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - MonthsLockup int64 `protobuf:"varint,2,opt,name=months_lockup,json=monthsLockup,proto3" json:"months_lockup,omitempty"` - Factor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=factor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"factor"` -} - -func (m *Multiplier) Reset() { *m = Multiplier{} } -func (m *Multiplier) String() string { return proto.CompactTextString(m) } -func (*Multiplier) ProtoMessage() {} -func (*Multiplier) Descriptor() ([]byte, []int) { - return fileDescriptor_bb8833f5d745eac9, []int{2} -} -func (m *Multiplier) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Multiplier) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Multiplier.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Multiplier) XXX_Merge(src proto.Message) { - xxx_messageInfo_Multiplier.Merge(m, src) -} -func (m *Multiplier) XXX_Size() int { - return m.Size() -} -func (m *Multiplier) XXX_DiscardUnknown() { - xxx_messageInfo_Multiplier.DiscardUnknown(m) -} - -var xxx_messageInfo_Multiplier proto.InternalMessageInfo - -// MultipliersPerDenom is a map of denoms to a set of multipliers -type MultipliersPerDenom struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Multipliers Multipliers `protobuf:"bytes,2,rep,name=multipliers,proto3,castrepeated=Multipliers" json:"multipliers"` -} - -func (m *MultipliersPerDenom) Reset() { *m = MultipliersPerDenom{} } -func (m *MultipliersPerDenom) String() string { return proto.CompactTextString(m) } -func (*MultipliersPerDenom) ProtoMessage() {} -func (*MultipliersPerDenom) Descriptor() ([]byte, []int) { - return fileDescriptor_bb8833f5d745eac9, []int{3} -} -func (m *MultipliersPerDenom) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MultipliersPerDenom) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MultipliersPerDenom.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MultipliersPerDenom) XXX_Merge(src proto.Message) { - xxx_messageInfo_MultipliersPerDenom.Merge(m, src) -} -func (m *MultipliersPerDenom) XXX_Size() int { - return m.Size() -} -func (m *MultipliersPerDenom) XXX_DiscardUnknown() { - xxx_messageInfo_MultipliersPerDenom.DiscardUnknown(m) -} - -var xxx_messageInfo_MultipliersPerDenom proto.InternalMessageInfo - -// Params -type Params struct { - USDXMintingRewardPeriods RewardPeriods `protobuf:"bytes,1,rep,name=usdx_minting_reward_periods,json=usdxMintingRewardPeriods,proto3,castrepeated=RewardPeriods" json:"usdx_minting_reward_periods"` - HardSupplyRewardPeriods MultiRewardPeriods `protobuf:"bytes,2,rep,name=hard_supply_reward_periods,json=hardSupplyRewardPeriods,proto3,castrepeated=MultiRewardPeriods" json:"hard_supply_reward_periods"` - HardBorrowRewardPeriods MultiRewardPeriods `protobuf:"bytes,3,rep,name=hard_borrow_reward_periods,json=hardBorrowRewardPeriods,proto3,castrepeated=MultiRewardPeriods" json:"hard_borrow_reward_periods"` - DelegatorRewardPeriods MultiRewardPeriods `protobuf:"bytes,4,rep,name=delegator_reward_periods,json=delegatorRewardPeriods,proto3,castrepeated=MultiRewardPeriods" json:"delegator_reward_periods"` - SwapRewardPeriods MultiRewardPeriods `protobuf:"bytes,5,rep,name=swap_reward_periods,json=swapRewardPeriods,proto3,castrepeated=MultiRewardPeriods" json:"swap_reward_periods"` - ClaimMultipliers MultipliersPerDenoms `protobuf:"bytes,6,rep,name=claim_multipliers,json=claimMultipliers,proto3,castrepeated=MultipliersPerDenoms" json:"claim_multipliers"` - ClaimEnd time.Time `protobuf:"bytes,7,opt,name=claim_end,json=claimEnd,proto3,stdtime" json:"claim_end"` - SavingsRewardPeriods MultiRewardPeriods `protobuf:"bytes,8,rep,name=savings_reward_periods,json=savingsRewardPeriods,proto3,castrepeated=MultiRewardPeriods" json:"savings_reward_periods"` - EarnRewardPeriods MultiRewardPeriods `protobuf:"bytes,9,rep,name=earn_reward_periods,json=earnRewardPeriods,proto3,castrepeated=MultiRewardPeriods" json:"earn_reward_periods"` -} - -func (m *Params) Reset() { *m = Params{} } -func (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_bb8833f5d745eac9, []int{4} -} -func (m *Params) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Params.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Params) XXX_Merge(src proto.Message) { - xxx_messageInfo_Params.Merge(m, src) -} -func (m *Params) XXX_Size() int { - return m.Size() -} -func (m *Params) XXX_DiscardUnknown() { - xxx_messageInfo_Params.DiscardUnknown(m) -} - -var xxx_messageInfo_Params proto.InternalMessageInfo - -func init() { - proto.RegisterType((*RewardPeriod)(nil), "kava.incentive.v1beta1.RewardPeriod") - proto.RegisterType((*MultiRewardPeriod)(nil), "kava.incentive.v1beta1.MultiRewardPeriod") - proto.RegisterType((*Multiplier)(nil), "kava.incentive.v1beta1.Multiplier") - proto.RegisterType((*MultipliersPerDenom)(nil), "kava.incentive.v1beta1.MultipliersPerDenom") - proto.RegisterType((*Params)(nil), "kava.incentive.v1beta1.Params") -} - -func init() { - proto.RegisterFile("kava/incentive/v1beta1/params.proto", fileDescriptor_bb8833f5d745eac9) -} - -var fileDescriptor_bb8833f5d745eac9 = []byte{ - // 781 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x96, 0xcf, 0x4f, 0xdb, 0x48, - 0x14, 0xc7, 0xe3, 0xfc, 0xda, 0x64, 0x80, 0x5d, 0x18, 0xa2, 0xac, 0x37, 0xbb, 0x72, 0x50, 0x58, - 0xed, 0x66, 0xb5, 0xc5, 0x86, 0x56, 0xea, 0xa1, 0xb7, 0xba, 0xb4, 0x87, 0xaa, 0x48, 0xc8, 0x50, - 0xa9, 0xed, 0x25, 0x9a, 0xd8, 0x83, 0x63, 0x61, 0x7b, 0xac, 0x99, 0x49, 0x20, 0xea, 0xa1, 0x52, - 0x0f, 0xbd, 0x55, 0x42, 0x3d, 0xf4, 0x8f, 0xe0, 0xdf, 0xe8, 0x85, 0x23, 0xea, 0xa9, 0xea, 0x01, - 0xda, 0xf0, 0x8f, 0x54, 0x33, 0x36, 0xc4, 0x09, 0x81, 0x16, 0x29, 0x97, 0x9e, 0x32, 0x7e, 0xf3, - 0xde, 0xfb, 0x7c, 0xfd, 0x1d, 0xbf, 0x51, 0xc0, 0xf2, 0x2e, 0xea, 0x21, 0xc3, 0x0b, 0x6d, 0x1c, - 0x72, 0xaf, 0x87, 0x8d, 0xde, 0x5a, 0x1b, 0x73, 0xb4, 0x66, 0x44, 0x88, 0xa2, 0x80, 0xe9, 0x11, - 0x25, 0x9c, 0xc0, 0xaa, 0x48, 0xd2, 0x2f, 0x92, 0xf4, 0x24, 0xa9, 0xa6, 0xd9, 0x84, 0x05, 0x84, - 0x19, 0x6d, 0xc4, 0x86, 0x95, 0x36, 0xf1, 0xc2, 0xb8, 0xae, 0x56, 0x71, 0x89, 0x4b, 0xe4, 0xd2, - 0x10, 0xab, 0x24, 0x5a, 0x77, 0x09, 0x71, 0x7d, 0x6c, 0xc8, 0xa7, 0x76, 0x77, 0xc7, 0xe0, 0x5e, - 0x80, 0x19, 0x47, 0x41, 0x14, 0x27, 0x34, 0xde, 0x65, 0xc1, 0xac, 0x85, 0xf7, 0x10, 0x75, 0x36, - 0x31, 0xf5, 0x88, 0x03, 0xab, 0xa0, 0x88, 0x6c, 0x41, 0x56, 0x95, 0x25, 0xa5, 0x59, 0xb2, 0x92, - 0x27, 0xf8, 0x2f, 0xf8, 0xcd, 0x26, 0xbe, 0x8f, 0x38, 0xa6, 0xc8, 0x6f, 0xf1, 0x7e, 0x84, 0xd5, - 0xec, 0x92, 0xd2, 0x2c, 0x5b, 0xbf, 0x0e, 0xc3, 0xdb, 0xfd, 0x08, 0xc3, 0x7b, 0xa0, 0xc0, 0x38, - 0xa2, 0x5c, 0xcd, 0x2d, 0x29, 0xcd, 0x99, 0xdb, 0x35, 0x3d, 0x96, 0xa0, 0x9f, 0x4b, 0xd0, 0xb7, - 0xcf, 0x25, 0x98, 0xa5, 0xa3, 0x93, 0x7a, 0xe6, 0xe0, 0xb4, 0xae, 0x58, 0x71, 0x09, 0xbc, 0x0b, - 0x72, 0x38, 0x74, 0xd4, 0xfc, 0x0d, 0x2a, 0x45, 0x01, 0xdc, 0x00, 0x90, 0xca, 0x97, 0x60, 0xad, - 0x08, 0xd3, 0x16, 0xc3, 0x36, 0x09, 0x1d, 0xb5, 0x20, 0xdb, 0xfc, 0xa1, 0xc7, 0xce, 0xe9, 0xc2, - 0xb9, 0x73, 0x3b, 0xf5, 0x07, 0xc4, 0x0b, 0xcd, 0xbc, 0xe8, 0x62, 0xcd, 0x27, 0xa5, 0x9b, 0x98, - 0x6e, 0xc9, 0xc2, 0xc6, 0x87, 0x2c, 0x58, 0xd8, 0xe8, 0xfa, 0xdc, 0xfb, 0xf9, 0x9d, 0xe9, 0x5f, - 0xe1, 0x4c, 0xee, 0x7a, 0x67, 0x56, 0x45, 0x97, 0xc3, 0xd3, 0x7a, 0xd3, 0xf5, 0x78, 0xa7, 0xdb, - 0xd6, 0x6d, 0x12, 0x18, 0xc9, 0x07, 0x18, 0xff, 0xac, 0x30, 0x67, 0xd7, 0x10, 0xef, 0xca, 0x64, - 0x01, 0x9b, 0xe0, 0xe2, 0x5b, 0x05, 0x00, 0xe9, 0x62, 0xe4, 0x7b, 0x98, 0x42, 0x08, 0xf2, 0x21, - 0x0a, 0x62, 0xf3, 0xca, 0x96, 0x5c, 0xc3, 0x65, 0x30, 0x17, 0x90, 0x90, 0x77, 0x58, 0xcb, 0x27, - 0xf6, 0x6e, 0x37, 0x92, 0xc6, 0xe5, 0xac, 0xd9, 0x38, 0xf8, 0x44, 0xc6, 0xe0, 0x23, 0x50, 0xdc, - 0x41, 0x36, 0x27, 0x54, 0xfa, 0x36, 0x6b, 0xea, 0x42, 0xdb, 0xe7, 0x93, 0xfa, 0x3f, 0x3f, 0xa0, - 0x6d, 0x1d, 0xdb, 0x56, 0x52, 0xdd, 0x78, 0xa3, 0x80, 0xc5, 0xa1, 0x1e, 0x21, 0x74, 0x1d, 0x87, - 0x24, 0x80, 0x15, 0x50, 0x70, 0xc4, 0x22, 0x51, 0x16, 0x3f, 0xc0, 0xe7, 0x60, 0x26, 0x18, 0x26, - 0xab, 0x59, 0xe9, 0x58, 0x43, 0x9f, 0x3c, 0x9d, 0xfa, 0xb0, 0xaf, 0xb9, 0x98, 0x58, 0x37, 0x93, - 0x62, 0x59, 0xe9, 0x5e, 0x8d, 0x8f, 0x25, 0x50, 0xdc, 0x94, 0x33, 0x0f, 0xdf, 0x2b, 0xe0, 0xcf, - 0x2e, 0x73, 0xf6, 0x5b, 0x81, 0x17, 0x72, 0x2f, 0x74, 0x5b, 0xb1, 0x8b, 0xe2, 0xac, 0x3c, 0xe2, - 0x30, 0x55, 0x91, 0xd8, 0xbf, 0xaf, 0xc2, 0xa6, 0xbf, 0x4f, 0x73, 0x4d, 0x80, 0x07, 0x27, 0x75, - 0xf5, 0xe9, 0xd6, 0xfa, 0xb3, 0x8d, 0xb8, 0x5f, 0x3a, 0x81, 0x1d, 0x9e, 0xd6, 0xe7, 0x46, 0x02, - 0x96, 0x2a, 0xd8, 0x93, 0x52, 0xe1, 0x6b, 0x05, 0xd4, 0x3a, 0x42, 0x09, 0xeb, 0x46, 0x91, 0xdf, - 0x1f, 0xd7, 0x15, 0xdb, 0xf1, 0xdf, 0xb5, 0x76, 0x8c, 0x88, 0xab, 0x25, 0xae, 0xc0, 0x4b, 0x5b, - 0xcc, 0xfa, 0x5d, 0x80, 0xb6, 0x24, 0xe7, 0x0a, 0x11, 0x6d, 0x42, 0x29, 0xd9, 0x1b, 0x17, 0x91, - 0x9b, 0xba, 0x08, 0x53, 0x72, 0x46, 0x45, 0xbc, 0x02, 0xaa, 0x83, 0x7d, 0xec, 0x22, 0x4e, 0xe8, - 0xb8, 0x82, 0xfc, 0x34, 0x15, 0x54, 0x2f, 0x30, 0xa3, 0x02, 0xba, 0x60, 0x91, 0xed, 0xa1, 0x68, - 0x9c, 0x5d, 0x98, 0x26, 0x7b, 0x41, 0x10, 0x46, 0xb1, 0x3d, 0xb0, 0x60, 0xfb, 0xc8, 0x0b, 0x5a, - 0xe9, 0x31, 0x28, 0x4a, 0xe8, 0xff, 0xdf, 0x1f, 0x83, 0x8b, 0xf1, 0x32, 0xff, 0x4a, 0xb0, 0x95, - 0x09, 0x9b, 0xcc, 0x9a, 0x97, 0x8c, 0xd4, 0x16, 0xbc, 0x0f, 0xca, 0x31, 0x57, 0xdc, 0x77, 0xbf, - 0xdc, 0xe0, 0xbe, 0x2b, 0xc9, 0xb2, 0x87, 0xa1, 0x03, 0x5f, 0x82, 0x2a, 0x43, 0x3d, 0x2f, 0x74, - 0xd9, 0xb8, 0x69, 0xa5, 0x69, 0x9a, 0x56, 0x49, 0x20, 0x97, 0x8e, 0x0b, 0x23, 0x1a, 0x8e, 0x93, - 0xcb, 0x53, 0x3d, 0x2e, 0x41, 0x18, 0x09, 0x99, 0x8f, 0x8f, 0xbe, 0x6a, 0x99, 0xa3, 0x81, 0xa6, - 0x1c, 0x0f, 0x34, 0xe5, 0xcb, 0x40, 0x53, 0x0e, 0xce, 0xb4, 0xcc, 0xf1, 0x99, 0x96, 0xf9, 0x74, - 0xa6, 0x65, 0x5e, 0xdc, 0x4a, 0xdd, 0x95, 0xab, 0xae, 0x8f, 0xda, 0xcc, 0x58, 0x75, 0x57, 0xec, - 0x0e, 0xf2, 0x42, 0x63, 0x3f, 0xf5, 0x97, 0x44, 0xde, 0x9a, 0xed, 0xa2, 0xf4, 0xf9, 0xce, 0xb7, - 0x00, 0x00, 0x00, 0xff, 0xff, 0xd6, 0x88, 0xb6, 0xd5, 0xb1, 0x08, 0x00, 0x00, -} - -func (m *RewardPeriod) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *RewardPeriod) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *RewardPeriod) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.RewardsPerSecond.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - n2, err2 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.End, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.End):]) - if err2 != nil { - return 0, err2 - } - i -= n2 - i = encodeVarintParams(dAtA, i, uint64(n2)) - i-- - dAtA[i] = 0x22 - n3, err3 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Start, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Start):]) - if err3 != nil { - return 0, err3 - } - i -= n3 - i = encodeVarintParams(dAtA, i, uint64(n3)) - i-- - dAtA[i] = 0x1a - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintParams(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x12 - } - if m.Active { - i-- - if m.Active { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *MultiRewardPeriod) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MultiRewardPeriod) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MultiRewardPeriod) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RewardsPerSecond) > 0 { - for iNdEx := len(m.RewardsPerSecond) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RewardsPerSecond[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - } - n4, err4 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.End, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.End):]) - if err4 != nil { - return 0, err4 - } - i -= n4 - i = encodeVarintParams(dAtA, i, uint64(n4)) - i-- - dAtA[i] = 0x22 - n5, err5 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Start, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Start):]) - if err5 != nil { - return 0, err5 - } - i -= n5 - i = encodeVarintParams(dAtA, i, uint64(n5)) - i-- - dAtA[i] = 0x1a - if len(m.CollateralType) > 0 { - i -= len(m.CollateralType) - copy(dAtA[i:], m.CollateralType) - i = encodeVarintParams(dAtA, i, uint64(len(m.CollateralType))) - i-- - dAtA[i] = 0x12 - } - if m.Active { - i-- - if m.Active { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *Multiplier) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Multiplier) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Multiplier) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Factor.Size() - i -= size - if _, err := m.Factor.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if m.MonthsLockup != 0 { - i = encodeVarintParams(dAtA, i, uint64(m.MonthsLockup)) - i-- - dAtA[i] = 0x10 - } - if len(m.Name) > 0 { - i -= len(m.Name) - copy(dAtA[i:], m.Name) - i = encodeVarintParams(dAtA, i, uint64(len(m.Name))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MultipliersPerDenom) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MultipliersPerDenom) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MultipliersPerDenom) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Multipliers) > 0 { - for iNdEx := len(m.Multipliers) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Multipliers[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintParams(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *Params) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Params) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.EarnRewardPeriods) > 0 { - for iNdEx := len(m.EarnRewardPeriods) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.EarnRewardPeriods[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x4a - } - } - if len(m.SavingsRewardPeriods) > 0 { - for iNdEx := len(m.SavingsRewardPeriods) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SavingsRewardPeriods[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - } - } - n6, err6 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.ClaimEnd, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.ClaimEnd):]) - if err6 != nil { - return 0, err6 - } - i -= n6 - i = encodeVarintParams(dAtA, i, uint64(n6)) - i-- - dAtA[i] = 0x3a - if len(m.ClaimMultipliers) > 0 { - for iNdEx := len(m.ClaimMultipliers) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ClaimMultipliers[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - } - } - if len(m.SwapRewardPeriods) > 0 { - for iNdEx := len(m.SwapRewardPeriods) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SwapRewardPeriods[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - } - if len(m.DelegatorRewardPeriods) > 0 { - for iNdEx := len(m.DelegatorRewardPeriods) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DelegatorRewardPeriods[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.HardBorrowRewardPeriods) > 0 { - for iNdEx := len(m.HardBorrowRewardPeriods) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.HardBorrowRewardPeriods[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.HardSupplyRewardPeriods) > 0 { - for iNdEx := len(m.HardSupplyRewardPeriods) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.HardSupplyRewardPeriods[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.USDXMintingRewardPeriods) > 0 { - for iNdEx := len(m.USDXMintingRewardPeriods) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.USDXMintingRewardPeriods[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintParams(dAtA []byte, offset int, v uint64) int { - offset -= sovParams(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *RewardPeriod) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Active { - n += 2 - } - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovParams(uint64(l)) - } - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Start) - n += 1 + l + sovParams(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.End) - n += 1 + l + sovParams(uint64(l)) - l = m.RewardsPerSecond.Size() - n += 1 + l + sovParams(uint64(l)) - return n -} - -func (m *MultiRewardPeriod) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Active { - n += 2 - } - l = len(m.CollateralType) - if l > 0 { - n += 1 + l + sovParams(uint64(l)) - } - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Start) - n += 1 + l + sovParams(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.End) - n += 1 + l + sovParams(uint64(l)) - if len(m.RewardsPerSecond) > 0 { - for _, e := range m.RewardsPerSecond { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - return n -} - -func (m *Multiplier) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Name) - if l > 0 { - n += 1 + l + sovParams(uint64(l)) - } - if m.MonthsLockup != 0 { - n += 1 + sovParams(uint64(m.MonthsLockup)) - } - l = m.Factor.Size() - n += 1 + l + sovParams(uint64(l)) - return n -} - -func (m *MultipliersPerDenom) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovParams(uint64(l)) - } - if len(m.Multipliers) > 0 { - for _, e := range m.Multipliers { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - return n -} - -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.USDXMintingRewardPeriods) > 0 { - for _, e := range m.USDXMintingRewardPeriods { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - if len(m.HardSupplyRewardPeriods) > 0 { - for _, e := range m.HardSupplyRewardPeriods { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - if len(m.HardBorrowRewardPeriods) > 0 { - for _, e := range m.HardBorrowRewardPeriods { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - if len(m.DelegatorRewardPeriods) > 0 { - for _, e := range m.DelegatorRewardPeriods { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - if len(m.SwapRewardPeriods) > 0 { - for _, e := range m.SwapRewardPeriods { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - if len(m.ClaimMultipliers) > 0 { - for _, e := range m.ClaimMultipliers { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.ClaimEnd) - n += 1 + l + sovParams(uint64(l)) - if len(m.SavingsRewardPeriods) > 0 { - for _, e := range m.SavingsRewardPeriods { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - if len(m.EarnRewardPeriods) > 0 { - for _, e := range m.EarnRewardPeriods { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - return n -} - -func sovParams(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozParams(x uint64) (n int) { - return sovParams(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *RewardPeriod) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: RewardPeriod: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: RewardPeriod: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Active", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Active = bool(v != 0) - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Start", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Start, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field End", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.End, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardsPerSecond", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.RewardsPerSecond.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParams(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParams - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MultiRewardPeriod) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MultiRewardPeriod: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MultiRewardPeriod: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Active", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Active = bool(v != 0) - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Start", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Start, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field End", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.End, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardsPerSecond", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RewardsPerSecond = append(m.RewardsPerSecond, types.Coin{}) - if err := m.RewardsPerSecond[len(m.RewardsPerSecond)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParams(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParams - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Multiplier) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Multiplier: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Multiplier: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Name = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field MonthsLockup", wireType) - } - m.MonthsLockup = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.MonthsLockup |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Factor", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Factor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParams(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParams - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MultipliersPerDenom) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MultipliersPerDenom: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MultipliersPerDenom: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Multipliers", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Multipliers = append(m.Multipliers, Multiplier{}) - if err := m.Multipliers[len(m.Multipliers)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParams(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParams - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Params) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Params: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field USDXMintingRewardPeriods", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.USDXMintingRewardPeriods = append(m.USDXMintingRewardPeriods, RewardPeriod{}) - if err := m.USDXMintingRewardPeriods[len(m.USDXMintingRewardPeriods)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HardSupplyRewardPeriods", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.HardSupplyRewardPeriods = append(m.HardSupplyRewardPeriods, MultiRewardPeriod{}) - if err := m.HardSupplyRewardPeriods[len(m.HardSupplyRewardPeriods)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HardBorrowRewardPeriods", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.HardBorrowRewardPeriods = append(m.HardBorrowRewardPeriods, MultiRewardPeriod{}) - if err := m.HardBorrowRewardPeriods[len(m.HardBorrowRewardPeriods)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DelegatorRewardPeriods", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DelegatorRewardPeriods = append(m.DelegatorRewardPeriods, MultiRewardPeriod{}) - if err := m.DelegatorRewardPeriods[len(m.DelegatorRewardPeriods)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SwapRewardPeriods", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SwapRewardPeriods = append(m.SwapRewardPeriods, MultiRewardPeriod{}) - if err := m.SwapRewardPeriods[len(m.SwapRewardPeriods)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClaimMultipliers", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ClaimMultipliers = append(m.ClaimMultipliers, MultipliersPerDenom{}) - if err := m.ClaimMultipliers[len(m.ClaimMultipliers)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClaimEnd", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.ClaimEnd, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SavingsRewardPeriods", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SavingsRewardPeriods = append(m.SavingsRewardPeriods, MultiRewardPeriod{}) - if err := m.SavingsRewardPeriods[len(m.SavingsRewardPeriods)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field EarnRewardPeriods", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.EarnRewardPeriods = append(m.EarnRewardPeriods, MultiRewardPeriod{}) - if err := m.EarnRewardPeriods[len(m.EarnRewardPeriods)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParams(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParams - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipParams(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParams - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParams - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParams - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthParams - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupParams - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthParams - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthParams = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowParams = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupParams = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/incentive/types/params_test.go b/x/incentive/types/params_test.go deleted file mode 100644 index bc783e80..00000000 --- a/x/incentive/types/params_test.go +++ /dev/null @@ -1,407 +0,0 @@ -package types_test - -import ( - "fmt" - "testing" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -type ParamTestSuite struct { - suite.Suite -} - -func (suite *ParamTestSuite) SetupTest() {} - -var rewardPeriodWithInvalidRewardsPerSecond = types.NewRewardPeriod( - true, - "bnb", - time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - time.Date(2024, 10, 15, 14, 0, 0, 0, time.UTC), - sdk.Coin{Denom: "INVALID!@#😫", Amount: sdk.ZeroInt()}, -) - -var rewardPeriodWithZeroRewardsPerSecond = types.NewRewardPeriod( - true, - "bnb", - time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - time.Date(2024, 10, 15, 14, 0, 0, 0, time.UTC), - sdk.Coin{Denom: "ukava", Amount: sdk.ZeroInt()}, -) - -var rewardMultiPeriodWithInvalidRewardsPerSecond = types.NewMultiRewardPeriod( - true, - "bnb", - time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - time.Date(2024, 10, 15, 14, 0, 0, 0, time.UTC), - sdk.Coins{sdk.Coin{Denom: "INVALID!@#😫", Amount: sdk.ZeroInt()}}, -) - -var rewardMultiPeriodWithZeroRewardsPerSecond = types.NewMultiRewardPeriod( - true, - "bnb", - time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - time.Date(2024, 10, 15, 14, 0, 0, 0, time.UTC), - sdk.Coins{sdk.Coin{Denom: "zero", Amount: sdk.ZeroInt()}}, -) - -var validMultiRewardPeriod = types.NewMultiRewardPeriod( - true, - "bnb", - time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - time.Date(2024, 10, 15, 14, 0, 0, 0, time.UTC), - sdk.NewCoins(sdk.NewInt64Coin("swap", 1e9)), -) - -var validRewardPeriod = types.NewRewardPeriod( - true, - "bnb-a", - time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - time.Date(2024, 10, 15, 14, 0, 0, 0, time.UTC), - sdk.NewInt64Coin(types.USDXMintingRewardDenom, 1e9), -) - -func (suite *ParamTestSuite) TestParamValidation() { - type errArgs struct { - expectPass bool - contains string - } - type test struct { - name string - params types.Params - errArgs errArgs - } - - testCases := []test{ - { - "default is valid", - types.DefaultParams(), - errArgs{ - expectPass: true, - }, - }, - { - "valid", - types.Params{ - USDXMintingRewardPeriods: types.RewardPeriods{ - types.NewRewardPeriod( - true, - "bnb-a", - time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - time.Date(2024, 10, 15, 14, 0, 0, 0, time.UTC), - sdk.NewCoin(types.USDXMintingRewardDenom, sdkmath.NewInt(122354)), - ), - }, - HardSupplyRewardPeriods: types.DefaultMultiRewardPeriods, - HardBorrowRewardPeriods: types.DefaultMultiRewardPeriods, - DelegatorRewardPeriods: types.DefaultMultiRewardPeriods, - SwapRewardPeriods: types.DefaultMultiRewardPeriods, - SavingsRewardPeriods: types.DefaultMultiRewardPeriods, - ClaimMultipliers: types.MultipliersPerDenoms{ - { - Denom: "hard", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, sdk.MustNewDecFromStr("0.25")), - types.NewMultiplier("large", 12, sdk.MustNewDecFromStr("1.0")), - }, - }, - { - Denom: "ukava", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", 1, sdk.MustNewDecFromStr("0.2")), - types.NewMultiplier("large", 12, sdk.MustNewDecFromStr("1.0")), - }, - }, - }, - ClaimEnd: time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - }, - errArgs{ - expectPass: true, - }, - }, - { - "invalid usdx minting period makes params invalid", - types.Params{ - USDXMintingRewardPeriods: types.RewardPeriods{rewardPeriodWithInvalidRewardsPerSecond}, - HardSupplyRewardPeriods: types.DefaultMultiRewardPeriods, - HardBorrowRewardPeriods: types.DefaultMultiRewardPeriods, - DelegatorRewardPeriods: types.DefaultMultiRewardPeriods, - SwapRewardPeriods: types.DefaultMultiRewardPeriods, - SavingsRewardPeriods: types.DefaultMultiRewardPeriods, - ClaimMultipliers: types.DefaultMultipliers, - ClaimEnd: time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - }, - errArgs{ - expectPass: false, - contains: fmt.Sprintf("reward denom must be %s", types.USDXMintingRewardDenom), - }, - }, - { - "invalid hard supply periods makes params invalid", - types.Params{ - USDXMintingRewardPeriods: types.DefaultRewardPeriods, - HardSupplyRewardPeriods: types.MultiRewardPeriods{rewardMultiPeriodWithInvalidRewardsPerSecond}, - HardBorrowRewardPeriods: types.DefaultMultiRewardPeriods, - DelegatorRewardPeriods: types.DefaultMultiRewardPeriods, - SwapRewardPeriods: types.DefaultMultiRewardPeriods, - SavingsRewardPeriods: types.DefaultMultiRewardPeriods, - ClaimMultipliers: types.DefaultMultipliers, - ClaimEnd: time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - }, - errArgs{ - expectPass: false, - contains: "invalid reward amount", - }, - }, - { - "invalid hard borrow periods makes params invalid", - types.Params{ - USDXMintingRewardPeriods: types.DefaultRewardPeriods, - HardSupplyRewardPeriods: types.DefaultMultiRewardPeriods, - HardBorrowRewardPeriods: types.MultiRewardPeriods{rewardMultiPeriodWithInvalidRewardsPerSecond}, - DelegatorRewardPeriods: types.DefaultMultiRewardPeriods, - SwapRewardPeriods: types.DefaultMultiRewardPeriods, - SavingsRewardPeriods: types.DefaultMultiRewardPeriods, - ClaimMultipliers: types.DefaultMultipliers, - ClaimEnd: time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - }, - errArgs{ - expectPass: false, - contains: "invalid reward amount", - }, - }, - { - "invalid delegator periods makes params invalid", - types.Params{ - USDXMintingRewardPeriods: types.DefaultRewardPeriods, - HardSupplyRewardPeriods: types.DefaultMultiRewardPeriods, - HardBorrowRewardPeriods: types.DefaultMultiRewardPeriods, - DelegatorRewardPeriods: types.MultiRewardPeriods{rewardMultiPeriodWithInvalidRewardsPerSecond}, - SwapRewardPeriods: types.DefaultMultiRewardPeriods, - SavingsRewardPeriods: types.DefaultMultiRewardPeriods, - ClaimMultipliers: types.DefaultMultipliers, - ClaimEnd: time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - }, - errArgs{ - expectPass: false, - contains: "invalid reward amount", - }, - }, - { - "invalid swap periods makes params invalid", - types.Params{ - USDXMintingRewardPeriods: types.DefaultRewardPeriods, - HardSupplyRewardPeriods: types.DefaultMultiRewardPeriods, - HardBorrowRewardPeriods: types.DefaultMultiRewardPeriods, - DelegatorRewardPeriods: types.DefaultMultiRewardPeriods, - SwapRewardPeriods: types.MultiRewardPeriods{rewardMultiPeriodWithInvalidRewardsPerSecond}, - SavingsRewardPeriods: types.DefaultMultiRewardPeriods, - ClaimMultipliers: types.DefaultMultipliers, - ClaimEnd: time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - }, - errArgs{ - expectPass: false, - contains: "invalid reward amount", - }, - }, - { - "invalid multipliers makes params invalid", - types.Params{ - USDXMintingRewardPeriods: types.DefaultRewardPeriods, - HardSupplyRewardPeriods: types.DefaultMultiRewardPeriods, - HardBorrowRewardPeriods: types.DefaultMultiRewardPeriods, - DelegatorRewardPeriods: types.DefaultMultiRewardPeriods, - SwapRewardPeriods: types.DefaultMultiRewardPeriods, - SavingsRewardPeriods: types.DefaultMultiRewardPeriods, - ClaimMultipliers: types.MultipliersPerDenoms{ - { - Denom: "hard", - Multipliers: types.Multipliers{ - types.NewMultiplier("small", -9999, sdk.MustNewDecFromStr("0.25")), - }, - }, - }, - ClaimEnd: time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - }, - errArgs{ - expectPass: false, - contains: "expected non-negative lockup", - }, - }, - { - "invalid zero amount multi rewards per second", - types.Params{ - USDXMintingRewardPeriods: types.DefaultRewardPeriods, - HardSupplyRewardPeriods: types.MultiRewardPeriods{ - rewardMultiPeriodWithZeroRewardsPerSecond, - }, - HardBorrowRewardPeriods: types.DefaultMultiRewardPeriods, - DelegatorRewardPeriods: types.DefaultMultiRewardPeriods, - SwapRewardPeriods: types.DefaultMultiRewardPeriods, - SavingsRewardPeriods: types.DefaultMultiRewardPeriods, - ClaimMultipliers: types.DefaultMultipliers, - ClaimEnd: time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - }, - errArgs{ - expectPass: false, - contains: "invalid reward amount: 0zero", - }, - }, - { - "invalid zero amount single rewards per second", - types.Params{ - USDXMintingRewardPeriods: types.RewardPeriods{ - rewardPeriodWithZeroRewardsPerSecond, - }, - HardSupplyRewardPeriods: types.DefaultMultiRewardPeriods, - HardBorrowRewardPeriods: types.DefaultMultiRewardPeriods, - DelegatorRewardPeriods: types.DefaultMultiRewardPeriods, - SwapRewardPeriods: types.DefaultMultiRewardPeriods, - SavingsRewardPeriods: types.DefaultMultiRewardPeriods, - ClaimMultipliers: types.DefaultMultipliers, - ClaimEnd: time.Date(2025, 10, 15, 14, 0, 0, 0, time.UTC), - }, - errArgs{ - expectPass: false, - contains: "reward amount cannot be zero: 0ukava", - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - err := tc.params.Validate() - - if tc.errArgs.expectPass { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - suite.Require().Contains(err.Error(), tc.errArgs.contains) - } - }) - } -} - -func (suite *ParamTestSuite) TestRewardPeriods() { - suite.Run("Validate", func() { - type err struct { - pass bool - contains string - } - testCases := []struct { - name string - periods types.RewardPeriods - expect err - }{ - { - name: "single period is valid", - periods: types.RewardPeriods{ - validRewardPeriod, - }, - expect: err{ - pass: true, - }, - }, - { - name: "duplicated reward period is invalid", - periods: types.RewardPeriods{ - validRewardPeriod, - validRewardPeriod, - }, - expect: err{ - contains: "duplicated reward period", - }, - }, - { - name: "invalid reward denom is invalid", - periods: types.RewardPeriods{ - types.NewRewardPeriod( - true, - "bnb-a", - time.Date(2020, 10, 15, 14, 0, 0, 0, time.UTC), - time.Date(2024, 10, 15, 14, 0, 0, 0, time.UTC), - sdk.NewInt64Coin("hard", 1e9), - ), - }, - expect: err{ - contains: fmt.Sprintf("reward denom must be %s", types.USDXMintingRewardDenom), - }, - }, - } - for _, tc := range testCases { - - err := tc.periods.Validate() - - if tc.expect.pass { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - suite.Contains(err.Error(), tc.expect.contains) - } - } - }) -} - -func (suite *ParamTestSuite) TestMultiRewardPeriods() { - suite.Run("Validate", func() { - type err struct { - pass bool - contains string - } - testCases := []struct { - name string - periods types.MultiRewardPeriods - expect err - }{ - { - name: "single period is valid", - periods: types.MultiRewardPeriods{ - validMultiRewardPeriod, - }, - expect: err{ - pass: true, - }, - }, - { - name: "duplicated reward period is invalid", - periods: types.MultiRewardPeriods{ - validMultiRewardPeriod, - validMultiRewardPeriod, - }, - expect: err{ - contains: "duplicated reward period", - }, - }, - { - name: "invalid reward period is invalid", - periods: types.MultiRewardPeriods{ - rewardMultiPeriodWithInvalidRewardsPerSecond, - }, - expect: err{ - contains: "invalid reward amount", - }, - }, - } - for _, tc := range testCases { - - err := tc.periods.Validate() - - if tc.expect.pass { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - suite.Contains(err.Error(), tc.expect.contains) - } - } - }) -} - -func TestParamTestSuite(t *testing.T) { - suite.Run(t, new(ParamTestSuite)) -} diff --git a/x/incentive/types/query.pb.go b/x/incentive/types/query.pb.go deleted file mode 100644 index dc0cb0ca..00000000 --- a/x/incentive/types/query.pb.go +++ /dev/null @@ -1,2425 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/incentive/v1beta1/query.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// QueryParamsRequest is the request type for the Query/Params RPC method. -type QueryParamsRequest struct { -} - -func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } -func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryParamsRequest) ProtoMessage() {} -func (*QueryParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_a78d71d0cbe5e95a, []int{0} -} -func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsRequest.Merge(m, src) -} -func (m *QueryParamsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo - -// QueryParamsResponse is the response type for the Query/Params RPC method. -type QueryParamsResponse struct { - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` -} - -func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } -func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryParamsResponse) ProtoMessage() {} -func (*QueryParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_a78d71d0cbe5e95a, []int{1} -} -func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsResponse.Merge(m, src) -} -func (m *QueryParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo - -func (m *QueryParamsResponse) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -// QueryRewardsRequest is the request type for the Query/Rewards RPC method. -type QueryRewardsRequest struct { - // owner is the address of the user to query rewards for. - Owner string `protobuf:"bytes,1,opt,name=owner,proto3" json:"owner,omitempty"` - // reward_type is the type of reward to query rewards for, e.g. hard, earn, - // swap. - RewardType string `protobuf:"bytes,2,opt,name=reward_type,json=rewardType,proto3" json:"reward_type,omitempty"` - // unsynchronized is a flag to query rewards that are not simulated for reward - // synchronized for the current block. - Unsynchronized bool `protobuf:"varint,3,opt,name=unsynchronized,proto3" json:"unsynchronized,omitempty"` -} - -func (m *QueryRewardsRequest) Reset() { *m = QueryRewardsRequest{} } -func (m *QueryRewardsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryRewardsRequest) ProtoMessage() {} -func (*QueryRewardsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_a78d71d0cbe5e95a, []int{2} -} -func (m *QueryRewardsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRewardsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRewardsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryRewardsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRewardsRequest.Merge(m, src) -} -func (m *QueryRewardsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryRewardsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRewardsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRewardsRequest proto.InternalMessageInfo - -func (m *QueryRewardsRequest) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *QueryRewardsRequest) GetRewardType() string { - if m != nil { - return m.RewardType - } - return "" -} - -func (m *QueryRewardsRequest) GetUnsynchronized() bool { - if m != nil { - return m.Unsynchronized - } - return false -} - -// QueryRewardsResponse is the response type for the Query/Rewards RPC method. -type QueryRewardsResponse struct { - USDXMintingClaims USDXMintingClaims `protobuf:"bytes,1,rep,name=usdx_minting_claims,json=usdxMintingClaims,proto3,castrepeated=USDXMintingClaims" json:"usdx_minting_claims"` - HardLiquidityProviderClaims HardLiquidityProviderClaims `protobuf:"bytes,2,rep,name=hard_liquidity_provider_claims,json=hardLiquidityProviderClaims,proto3,castrepeated=HardLiquidityProviderClaims" json:"hard_liquidity_provider_claims"` - DelegatorClaims DelegatorClaims `protobuf:"bytes,3,rep,name=delegator_claims,json=delegatorClaims,proto3,castrepeated=DelegatorClaims" json:"delegator_claims"` - SwapClaims SwapClaims `protobuf:"bytes,4,rep,name=swap_claims,json=swapClaims,proto3,castrepeated=SwapClaims" json:"swap_claims"` - SavingsClaims SavingsClaims `protobuf:"bytes,5,rep,name=savings_claims,json=savingsClaims,proto3,castrepeated=SavingsClaims" json:"savings_claims"` - EarnClaims EarnClaims `protobuf:"bytes,6,rep,name=earn_claims,json=earnClaims,proto3,castrepeated=EarnClaims" json:"earn_claims"` -} - -func (m *QueryRewardsResponse) Reset() { *m = QueryRewardsResponse{} } -func (m *QueryRewardsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryRewardsResponse) ProtoMessage() {} -func (*QueryRewardsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_a78d71d0cbe5e95a, []int{3} -} -func (m *QueryRewardsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRewardsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRewardsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryRewardsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRewardsResponse.Merge(m, src) -} -func (m *QueryRewardsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryRewardsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRewardsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRewardsResponse proto.InternalMessageInfo - -func (m *QueryRewardsResponse) GetUSDXMintingClaims() USDXMintingClaims { - if m != nil { - return m.USDXMintingClaims - } - return nil -} - -func (m *QueryRewardsResponse) GetHardLiquidityProviderClaims() HardLiquidityProviderClaims { - if m != nil { - return m.HardLiquidityProviderClaims - } - return nil -} - -func (m *QueryRewardsResponse) GetDelegatorClaims() DelegatorClaims { - if m != nil { - return m.DelegatorClaims - } - return nil -} - -func (m *QueryRewardsResponse) GetSwapClaims() SwapClaims { - if m != nil { - return m.SwapClaims - } - return nil -} - -func (m *QueryRewardsResponse) GetSavingsClaims() SavingsClaims { - if m != nil { - return m.SavingsClaims - } - return nil -} - -func (m *QueryRewardsResponse) GetEarnClaims() EarnClaims { - if m != nil { - return m.EarnClaims - } - return nil -} - -// QueryRewardFactorsRequest is the request type for the Query/RewardFactors RPC method. -type QueryRewardFactorsRequest struct { -} - -func (m *QueryRewardFactorsRequest) Reset() { *m = QueryRewardFactorsRequest{} } -func (m *QueryRewardFactorsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryRewardFactorsRequest) ProtoMessage() {} -func (*QueryRewardFactorsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_a78d71d0cbe5e95a, []int{4} -} -func (m *QueryRewardFactorsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRewardFactorsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRewardFactorsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryRewardFactorsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRewardFactorsRequest.Merge(m, src) -} -func (m *QueryRewardFactorsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryRewardFactorsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRewardFactorsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRewardFactorsRequest proto.InternalMessageInfo - -// QueryRewardFactorsResponse is the response type for the Query/RewardFactors RPC method. -type QueryRewardFactorsResponse struct { - UsdxMintingRewardFactors RewardIndexes `protobuf:"bytes,1,rep,name=usdx_minting_reward_factors,json=usdxMintingRewardFactors,proto3,castrepeated=RewardIndexes" json:"usdx_minting_reward_factors"` - HardSupplyRewardFactors MultiRewardIndexes `protobuf:"bytes,2,rep,name=hard_supply_reward_factors,json=hardSupplyRewardFactors,proto3,castrepeated=MultiRewardIndexes" json:"hard_supply_reward_factors"` - HardBorrowRewardFactors MultiRewardIndexes `protobuf:"bytes,3,rep,name=hard_borrow_reward_factors,json=hardBorrowRewardFactors,proto3,castrepeated=MultiRewardIndexes" json:"hard_borrow_reward_factors"` - DelegatorRewardFactors MultiRewardIndexes `protobuf:"bytes,4,rep,name=delegator_reward_factors,json=delegatorRewardFactors,proto3,castrepeated=MultiRewardIndexes" json:"delegator_reward_factors"` - SwapRewardFactors MultiRewardIndexes `protobuf:"bytes,5,rep,name=swap_reward_factors,json=swapRewardFactors,proto3,castrepeated=MultiRewardIndexes" json:"swap_reward_factors"` - SavingsRewardFactors MultiRewardIndexes `protobuf:"bytes,6,rep,name=savings_reward_factors,json=savingsRewardFactors,proto3,castrepeated=MultiRewardIndexes" json:"savings_reward_factors"` - EarnRewardFactors MultiRewardIndexes `protobuf:"bytes,7,rep,name=earn_reward_factors,json=earnRewardFactors,proto3,castrepeated=MultiRewardIndexes" json:"earn_reward_factors"` -} - -func (m *QueryRewardFactorsResponse) Reset() { *m = QueryRewardFactorsResponse{} } -func (m *QueryRewardFactorsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryRewardFactorsResponse) ProtoMessage() {} -func (*QueryRewardFactorsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_a78d71d0cbe5e95a, []int{5} -} -func (m *QueryRewardFactorsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRewardFactorsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRewardFactorsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryRewardFactorsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRewardFactorsResponse.Merge(m, src) -} -func (m *QueryRewardFactorsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryRewardFactorsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRewardFactorsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRewardFactorsResponse proto.InternalMessageInfo - -func (m *QueryRewardFactorsResponse) GetUsdxMintingRewardFactors() RewardIndexes { - if m != nil { - return m.UsdxMintingRewardFactors - } - return nil -} - -func (m *QueryRewardFactorsResponse) GetHardSupplyRewardFactors() MultiRewardIndexes { - if m != nil { - return m.HardSupplyRewardFactors - } - return nil -} - -func (m *QueryRewardFactorsResponse) GetHardBorrowRewardFactors() MultiRewardIndexes { - if m != nil { - return m.HardBorrowRewardFactors - } - return nil -} - -func (m *QueryRewardFactorsResponse) GetDelegatorRewardFactors() MultiRewardIndexes { - if m != nil { - return m.DelegatorRewardFactors - } - return nil -} - -func (m *QueryRewardFactorsResponse) GetSwapRewardFactors() MultiRewardIndexes { - if m != nil { - return m.SwapRewardFactors - } - return nil -} - -func (m *QueryRewardFactorsResponse) GetSavingsRewardFactors() MultiRewardIndexes { - if m != nil { - return m.SavingsRewardFactors - } - return nil -} - -func (m *QueryRewardFactorsResponse) GetEarnRewardFactors() MultiRewardIndexes { - if m != nil { - return m.EarnRewardFactors - } - return nil -} - -// QueryApysRequest is the request type for the Query/Apys RPC method. -type QueryApyRequest struct { -} - -func (m *QueryApyRequest) Reset() { *m = QueryApyRequest{} } -func (m *QueryApyRequest) String() string { return proto.CompactTextString(m) } -func (*QueryApyRequest) ProtoMessage() {} -func (*QueryApyRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_a78d71d0cbe5e95a, []int{6} -} -func (m *QueryApyRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryApyRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryApyRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryApyRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryApyRequest.Merge(m, src) -} -func (m *QueryApyRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryApyRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryApyRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryApyRequest proto.InternalMessageInfo - -// QueryApysResponse is the response type for the Query/Apys RPC method. -type QueryApyResponse struct { - Earn []Apy `protobuf:"bytes,1,rep,name=earn,proto3" json:"earn"` -} - -func (m *QueryApyResponse) Reset() { *m = QueryApyResponse{} } -func (m *QueryApyResponse) String() string { return proto.CompactTextString(m) } -func (*QueryApyResponse) ProtoMessage() {} -func (*QueryApyResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_a78d71d0cbe5e95a, []int{7} -} -func (m *QueryApyResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryApyResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryApyResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryApyResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryApyResponse.Merge(m, src) -} -func (m *QueryApyResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryApyResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryApyResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryApyResponse proto.InternalMessageInfo - -func (m *QueryApyResponse) GetEarn() []Apy { - if m != nil { - return m.Earn - } - return nil -} - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.incentive.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.incentive.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryRewardsRequest)(nil), "kava.incentive.v1beta1.QueryRewardsRequest") - proto.RegisterType((*QueryRewardsResponse)(nil), "kava.incentive.v1beta1.QueryRewardsResponse") - proto.RegisterType((*QueryRewardFactorsRequest)(nil), "kava.incentive.v1beta1.QueryRewardFactorsRequest") - proto.RegisterType((*QueryRewardFactorsResponse)(nil), "kava.incentive.v1beta1.QueryRewardFactorsResponse") - proto.RegisterType((*QueryApyRequest)(nil), "kava.incentive.v1beta1.QueryApyRequest") - proto.RegisterType((*QueryApyResponse)(nil), "kava.incentive.v1beta1.QueryApyResponse") -} - -func init() { - proto.RegisterFile("kava/incentive/v1beta1/query.proto", fileDescriptor_a78d71d0cbe5e95a) -} - -var fileDescriptor_a78d71d0cbe5e95a = []byte{ - // 911 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x96, 0xcf, 0x6f, 0xe3, 0x44, - 0x14, 0xc7, 0xeb, 0xe6, 0x47, 0xe1, 0x55, 0xdd, 0x6e, 0xa7, 0xa1, 0x1b, 0x1c, 0x70, 0xb2, 0x29, - 0xea, 0x46, 0xb0, 0xc4, 0xdb, 0x20, 0x6e, 0x5c, 0x5a, 0x96, 0x15, 0x2b, 0xb1, 0xd2, 0xe2, 0x02, - 0x42, 0x5c, 0xaa, 0x49, 0x3c, 0x38, 0x86, 0x74, 0xc6, 0x9d, 0x71, 0x92, 0x7a, 0x25, 0x90, 0xe0, - 0x02, 0x1c, 0x90, 0x90, 0xb8, 0x72, 0xe6, 0xb0, 0x7f, 0x05, 0xc7, 0x95, 0xb8, 0xac, 0xc4, 0x85, - 0xd3, 0x2e, 0x6a, 0xf9, 0x43, 0x90, 0x67, 0xc6, 0x6e, 0xec, 0xad, 0xd3, 0x22, 0xe5, 0xe6, 0xbc, - 0xf9, 0xbe, 0xf7, 0xfd, 0x3c, 0xeb, 0xbd, 0x8c, 0xa1, 0xfd, 0x35, 0x9e, 0x60, 0xdb, 0xa7, 0x03, - 0x42, 0x43, 0x7f, 0x42, 0xec, 0xc9, 0x6e, 0x9f, 0x84, 0x78, 0xd7, 0x3e, 0x1e, 0x13, 0x1e, 0x75, - 0x03, 0xce, 0x42, 0x86, 0xb6, 0x62, 0x4d, 0x37, 0xd5, 0x74, 0xb5, 0xc6, 0xac, 0x79, 0xcc, 0x63, - 0x52, 0x62, 0xc7, 0x4f, 0x4a, 0x6d, 0xbe, 0xe6, 0x31, 0xe6, 0x8d, 0x88, 0x8d, 0x03, 0xdf, 0xc6, - 0x94, 0xb2, 0x10, 0x87, 0x3e, 0xa3, 0x42, 0x9f, 0xb6, 0x0a, 0xfc, 0x70, 0xa0, 0xdd, 0xcc, 0xed, - 0x02, 0xc5, 0x60, 0x84, 0xfd, 0x23, 0x71, 0x89, 0x28, 0xc0, 0x1c, 0x27, 0xa2, 0x76, 0x0d, 0xd0, - 0xc7, 0x71, 0x1b, 0x0f, 0x65, 0xd0, 0x21, 0xc7, 0x63, 0x22, 0xc2, 0xf6, 0x01, 0x6c, 0x66, 0xa2, - 0x22, 0x60, 0x54, 0x10, 0xf4, 0x1e, 0x54, 0x55, 0x72, 0xdd, 0x68, 0x19, 0x9d, 0xd5, 0x9e, 0xd5, - 0xbd, 0xb8, 0xeb, 0xae, 0xca, 0xdb, 0x2f, 0x3f, 0x79, 0xd6, 0x5c, 0x72, 0x74, 0x4e, 0x3b, 0xd4, - 0x45, 0x1d, 0x32, 0xc5, 0xdc, 0x4d, 0xbc, 0x50, 0x0d, 0x2a, 0x6c, 0x4a, 0x09, 0x97, 0x35, 0x5f, - 0x76, 0xd4, 0x0f, 0xd4, 0x84, 0x55, 0x2e, 0x75, 0x87, 0x61, 0x14, 0x90, 0xfa, 0xb2, 0x3c, 0x03, - 0x15, 0xfa, 0x24, 0x0a, 0x08, 0xda, 0x81, 0x6b, 0x63, 0x2a, 0x22, 0x3a, 0x18, 0x72, 0x46, 0xfd, - 0x47, 0xc4, 0xad, 0x97, 0x5a, 0x46, 0xe7, 0x25, 0x27, 0x17, 0x6d, 0xff, 0x51, 0x81, 0x5a, 0xd6, - 0x56, 0x37, 0xf3, 0xa3, 0x01, 0x9b, 0x63, 0xe1, 0x9e, 0x1c, 0x1e, 0xf9, 0x34, 0xf4, 0xa9, 0x77, - 0xa8, 0x5e, 0x5e, 0xdd, 0x68, 0x95, 0x3a, 0xab, 0xbd, 0x4e, 0x51, 0x6b, 0x9f, 0x1e, 0xdc, 0xfd, - 0xfc, 0x81, 0xca, 0x78, 0x3f, 0x4e, 0xd8, 0xef, 0xc6, 0x4d, 0x9e, 0x3e, 0x6b, 0x6e, 0xe4, 0x4f, - 0xc4, 0xe3, 0xe7, 0x17, 0x04, 0x9d, 0x8d, 0xd8, 0x34, 0x13, 0x42, 0xbf, 0x19, 0x60, 0x0d, 0xe3, - 0x5e, 0x47, 0xfe, 0xf1, 0xd8, 0x77, 0xfd, 0x30, 0x3a, 0x0c, 0x38, 0x9b, 0xf8, 0x2e, 0xe1, 0x09, - 0xd5, 0xb2, 0xa4, 0xea, 0x15, 0x51, 0x7d, 0x88, 0xb9, 0xfb, 0x51, 0x92, 0xfc, 0x50, 0xe7, 0x2a, - 0xbe, 0xed, 0x98, 0xef, 0xf1, 0xf3, 0x66, 0xa3, 0x58, 0x23, 0x9c, 0xc6, 0xb0, 0xf8, 0x10, 0x7d, - 0x05, 0xd7, 0x5d, 0x32, 0x22, 0x1e, 0x0e, 0x59, 0xca, 0x53, 0x92, 0x3c, 0x3b, 0x45, 0x3c, 0x77, - 0x13, 0xbd, 0x62, 0xb8, 0xa1, 0x19, 0xd6, 0xb3, 0x71, 0xe1, 0xac, 0xbb, 0xd9, 0x00, 0xfa, 0x0c, - 0x56, 0xc5, 0x14, 0x07, 0x89, 0x4d, 0x59, 0xda, 0xdc, 0x2c, 0xb2, 0x39, 0x98, 0xe2, 0x40, 0x39, - 0x20, 0xed, 0x00, 0x69, 0x48, 0x38, 0x20, 0xd2, 0x67, 0xd4, 0x87, 0x6b, 0x02, 0x4f, 0x7c, 0xea, - 0x89, 0xa4, 0x74, 0x45, 0x96, 0x7e, 0xa3, 0xb0, 0xb4, 0x52, 0xab, 0xea, 0xaf, 0xe8, 0xea, 0x6b, - 0xb3, 0x51, 0xe1, 0xac, 0x89, 0xd9, 0x9f, 0x31, 0x3b, 0xc1, 0x9c, 0x26, 0x06, 0xd5, 0xf9, 0xec, - 0x1f, 0x60, 0x4e, 0x73, 0xec, 0x69, 0x48, 0x38, 0x40, 0xd2, 0xe7, 0x76, 0x03, 0x5e, 0x9d, 0x99, - 0xe0, 0x7b, 0x78, 0x10, 0x32, 0x9e, 0xae, 0xea, 0x0f, 0x2b, 0x60, 0x5e, 0x74, 0xaa, 0xa7, 0x3c, - 0x82, 0x46, 0x66, 0xc8, 0xf5, 0x52, 0x7d, 0xa9, 0x64, 0x7a, 0xd8, 0xb7, 0x8b, 0x18, 0x55, 0xcd, - 0xfb, 0xd4, 0x25, 0x27, 0xe7, 0xef, 0x60, 0x26, 0x48, 0x84, 0x53, 0x9f, 0x19, 0xe7, 0x0c, 0x02, - 0xfa, 0xce, 0x00, 0x53, 0x4e, 0xb5, 0x18, 0x07, 0xc1, 0x28, 0xca, 0x5b, 0x2f, 0xcf, 0xdf, 0xb3, - 0x07, 0xe3, 0x51, 0xe8, 0xcf, 0xfa, 0x9b, 0xda, 0x1f, 0xe5, 0x4f, 0x88, 0x70, 0x6e, 0xc4, 0x3e, - 0x07, 0xd2, 0xa6, 0x80, 0xa1, 0xcf, 0x38, 0x67, 0xd3, 0x3c, 0x43, 0x69, 0xd1, 0x0c, 0xfb, 0xd2, - 0x26, 0xcb, 0xf0, 0x2d, 0xd4, 0xcf, 0xd7, 0x27, 0x07, 0x50, 0x5e, 0x20, 0xc0, 0x56, 0xea, 0x92, - 0xf5, 0x0f, 0x61, 0x53, 0xae, 0x54, 0xce, 0xba, 0xb2, 0x40, 0xeb, 0x8d, 0xd8, 0x20, 0xeb, 0xfa, - 0x08, 0xb6, 0x92, 0x85, 0xcb, 0x19, 0x57, 0x17, 0x68, 0x5c, 0xd3, 0x1e, 0x2f, 0x74, 0x2c, 0x17, - 0x31, 0x67, 0xbc, 0xb2, 0xc8, 0x8e, 0x63, 0x83, 0x8c, 0x6b, 0x7b, 0x03, 0xd6, 0xe5, 0x22, 0xee, - 0x05, 0x51, 0xb2, 0x9c, 0xf7, 0xe1, 0xfa, 0x79, 0x48, 0x6f, 0xe4, 0xbb, 0x50, 0x8e, 0x73, 0xf5, - 0xea, 0x35, 0x8a, 0x68, 0xf6, 0x82, 0x48, 0xdf, 0x9f, 0x52, 0xde, 0xfb, 0xb3, 0x0c, 0x15, 0x59, - 0x0b, 0xfd, 0x64, 0x40, 0x55, 0x5d, 0xb0, 0xe8, 0xcd, 0xa2, 0xec, 0x17, 0xef, 0x74, 0xf3, 0xad, - 0x2b, 0x69, 0x15, 0x64, 0x7b, 0xe7, 0xfb, 0xbf, 0xfe, 0xfd, 0x75, 0xb9, 0x85, 0x2c, 0x7b, 0xee, - 0x47, 0x04, 0xfa, 0xd9, 0x80, 0x15, 0x7d, 0xb1, 0xa2, 0xf9, 0x06, 0xd9, 0x5b, 0xdf, 0xbc, 0x7d, - 0x35, 0xb1, 0xc6, 0xb9, 0x25, 0x71, 0x6e, 0xa2, 0x66, 0x11, 0x0e, 0xd7, 0x0c, 0xbf, 0x1b, 0xb0, - 0x96, 0x9d, 0x85, 0xdd, 0x2b, 0x18, 0x65, 0xff, 0x52, 0xcd, 0xde, 0xff, 0x49, 0xd1, 0x84, 0x5d, - 0x49, 0xd8, 0x41, 0x3b, 0xf3, 0x09, 0x93, 0x59, 0x44, 0xdf, 0x40, 0x69, 0x2f, 0x88, 0xd0, 0xad, - 0xb9, 0x56, 0xe7, 0x93, 0x64, 0x76, 0x2e, 0x17, 0x6a, 0x92, 0x6d, 0x49, 0xf2, 0x3a, 0x6a, 0xd8, - 0xc5, 0x9f, 0x91, 0xfb, 0xf7, 0x9e, 0x9c, 0x5a, 0xc6, 0xd3, 0x53, 0xcb, 0xf8, 0xe7, 0xd4, 0x32, - 0x7e, 0x39, 0xb3, 0x96, 0x9e, 0x9e, 0x59, 0x4b, 0x7f, 0x9f, 0x59, 0x4b, 0x5f, 0xdc, 0xf6, 0xfc, - 0x70, 0x38, 0xee, 0x77, 0x07, 0xec, 0xc8, 0xbe, 0xe3, 0x8d, 0x70, 0x5f, 0xd8, 0x77, 0xbc, 0xb7, - 0x07, 0x43, 0xec, 0x53, 0xfb, 0x64, 0xa6, 0x5a, 0xfc, 0x59, 0x26, 0xfa, 0x55, 0xf9, 0x15, 0xf9, - 0xce, 0x7f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x17, 0x9d, 0xa6, 0x72, 0x23, 0x0b, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - // Params queries module params. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Rewards queries reward information for a given user. - Rewards(ctx context.Context, in *QueryRewardsRequest, opts ...grpc.CallOption) (*QueryRewardsResponse, error) - // Rewards queries the reward factors. - RewardFactors(ctx context.Context, in *QueryRewardFactorsRequest, opts ...grpc.CallOption) (*QueryRewardFactorsResponse, error) - // Apy queries incentive reward apy for a reward. - Apy(ctx context.Context, in *QueryApyRequest, opts ...grpc.CallOption) (*QueryApyResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { - out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, "/kava.incentive.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Rewards(ctx context.Context, in *QueryRewardsRequest, opts ...grpc.CallOption) (*QueryRewardsResponse, error) { - out := new(QueryRewardsResponse) - err := c.cc.Invoke(ctx, "/kava.incentive.v1beta1.Query/Rewards", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) RewardFactors(ctx context.Context, in *QueryRewardFactorsRequest, opts ...grpc.CallOption) (*QueryRewardFactorsResponse, error) { - out := new(QueryRewardFactorsResponse) - err := c.cc.Invoke(ctx, "/kava.incentive.v1beta1.Query/RewardFactors", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Apy(ctx context.Context, in *QueryApyRequest, opts ...grpc.CallOption) (*QueryApyResponse, error) { - out := new(QueryApyResponse) - err := c.cc.Invoke(ctx, "/kava.incentive.v1beta1.Query/Apy", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries module params. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Rewards queries reward information for a given user. - Rewards(context.Context, *QueryRewardsRequest) (*QueryRewardsResponse, error) - // Rewards queries the reward factors. - RewardFactors(context.Context, *QueryRewardFactorsRequest) (*QueryRewardFactorsResponse, error) - // Apy queries incentive reward apy for a reward. - Apy(context.Context, *QueryApyRequest) (*QueryApyResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") -} -func (*UnimplementedQueryServer) Rewards(ctx context.Context, req *QueryRewardsRequest) (*QueryRewardsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Rewards not implemented") -} -func (*UnimplementedQueryServer) RewardFactors(ctx context.Context, req *QueryRewardFactorsRequest) (*QueryRewardFactorsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method RewardFactors not implemented") -} -func (*UnimplementedQueryServer) Apy(ctx context.Context, req *QueryApyRequest) (*QueryApyResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Apy not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryParamsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Params(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.incentive.v1beta1.Query/Params", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Rewards_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRewardsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Rewards(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.incentive.v1beta1.Query/Rewards", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Rewards(ctx, req.(*QueryRewardsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_RewardFactors_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRewardFactorsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).RewardFactors(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.incentive.v1beta1.Query/RewardFactors", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).RewardFactors(ctx, req.(*QueryRewardFactorsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Apy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryApyRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Apy(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.incentive.v1beta1.Query/Apy", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Apy(ctx, req.(*QueryApyRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.incentive.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Rewards", - Handler: _Query_Rewards_Handler, - }, - { - MethodName: "RewardFactors", - Handler: _Query_RewardFactors_Handler, - }, - { - MethodName: "Apy", - Handler: _Query_Apy_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/incentive/v1beta1/query.proto", -} - -func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryRewardsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryRewardsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRewardsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Unsynchronized { - i-- - if m.Unsynchronized { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x18 - } - if len(m.RewardType) > 0 { - i -= len(m.RewardType) - copy(dAtA[i:], m.RewardType) - i = encodeVarintQuery(dAtA, i, uint64(len(m.RewardType))) - i-- - dAtA[i] = 0x12 - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryRewardsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryRewardsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRewardsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.EarnClaims) > 0 { - for iNdEx := len(m.EarnClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.EarnClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - } - } - if len(m.SavingsClaims) > 0 { - for iNdEx := len(m.SavingsClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SavingsClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - } - if len(m.SwapClaims) > 0 { - for iNdEx := len(m.SwapClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SwapClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.DelegatorClaims) > 0 { - for iNdEx := len(m.DelegatorClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DelegatorClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.HardLiquidityProviderClaims) > 0 { - for iNdEx := len(m.HardLiquidityProviderClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.HardLiquidityProviderClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.USDXMintingClaims) > 0 { - for iNdEx := len(m.USDXMintingClaims) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.USDXMintingClaims[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryRewardFactorsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryRewardFactorsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRewardFactorsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryRewardFactorsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryRewardFactorsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRewardFactorsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.EarnRewardFactors) > 0 { - for iNdEx := len(m.EarnRewardFactors) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.EarnRewardFactors[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - } - if len(m.SavingsRewardFactors) > 0 { - for iNdEx := len(m.SavingsRewardFactors) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SavingsRewardFactors[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - } - } - if len(m.SwapRewardFactors) > 0 { - for iNdEx := len(m.SwapRewardFactors) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SwapRewardFactors[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - } - if len(m.DelegatorRewardFactors) > 0 { - for iNdEx := len(m.DelegatorRewardFactors) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DelegatorRewardFactors[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.HardBorrowRewardFactors) > 0 { - for iNdEx := len(m.HardBorrowRewardFactors) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.HardBorrowRewardFactors[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.HardSupplyRewardFactors) > 0 { - for iNdEx := len(m.HardSupplyRewardFactors) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.HardSupplyRewardFactors[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.UsdxMintingRewardFactors) > 0 { - for iNdEx := len(m.UsdxMintingRewardFactors) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.UsdxMintingRewardFactors[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryApyRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryApyRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryApyRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryApyResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryApyResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryApyResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Earn) > 0 { - for iNdEx := len(m.Earn) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Earn[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryParamsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryRewardsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.RewardType) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Unsynchronized { - n += 2 - } - return n -} - -func (m *QueryRewardsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.USDXMintingClaims) > 0 { - for _, e := range m.USDXMintingClaims { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.HardLiquidityProviderClaims) > 0 { - for _, e := range m.HardLiquidityProviderClaims { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.DelegatorClaims) > 0 { - for _, e := range m.DelegatorClaims { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.SwapClaims) > 0 { - for _, e := range m.SwapClaims { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.SavingsClaims) > 0 { - for _, e := range m.SavingsClaims { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.EarnClaims) > 0 { - for _, e := range m.EarnClaims { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryRewardFactorsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryRewardFactorsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.UsdxMintingRewardFactors) > 0 { - for _, e := range m.UsdxMintingRewardFactors { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.HardSupplyRewardFactors) > 0 { - for _, e := range m.HardSupplyRewardFactors { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.HardBorrowRewardFactors) > 0 { - for _, e := range m.HardBorrowRewardFactors { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.DelegatorRewardFactors) > 0 { - for _, e := range m.DelegatorRewardFactors { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.SwapRewardFactors) > 0 { - for _, e := range m.SwapRewardFactors { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.SavingsRewardFactors) > 0 { - for _, e := range m.SavingsRewardFactors { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.EarnRewardFactors) > 0 { - for _, e := range m.EarnRewardFactors { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryApyRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryApyResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Earn) > 0 { - for _, e := range m.Earn { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryRewardsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryRewardsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRewardsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RewardType = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Unsynchronized", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Unsynchronized = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryRewardsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryRewardsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRewardsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field USDXMintingClaims", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.USDXMintingClaims = append(m.USDXMintingClaims, USDXMintingClaim{}) - if err := m.USDXMintingClaims[len(m.USDXMintingClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HardLiquidityProviderClaims", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.HardLiquidityProviderClaims = append(m.HardLiquidityProviderClaims, HardLiquidityProviderClaim{}) - if err := m.HardLiquidityProviderClaims[len(m.HardLiquidityProviderClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DelegatorClaims", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DelegatorClaims = append(m.DelegatorClaims, DelegatorClaim{}) - if err := m.DelegatorClaims[len(m.DelegatorClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SwapClaims", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SwapClaims = append(m.SwapClaims, SwapClaim{}) - if err := m.SwapClaims[len(m.SwapClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SavingsClaims", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SavingsClaims = append(m.SavingsClaims, SavingsClaim{}) - if err := m.SavingsClaims[len(m.SavingsClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field EarnClaims", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.EarnClaims = append(m.EarnClaims, EarnClaim{}) - if err := m.EarnClaims[len(m.EarnClaims)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryRewardFactorsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryRewardFactorsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRewardFactorsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryRewardFactorsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryRewardFactorsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRewardFactorsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field UsdxMintingRewardFactors", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.UsdxMintingRewardFactors = append(m.UsdxMintingRewardFactors, RewardIndex{}) - if err := m.UsdxMintingRewardFactors[len(m.UsdxMintingRewardFactors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HardSupplyRewardFactors", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.HardSupplyRewardFactors = append(m.HardSupplyRewardFactors, MultiRewardIndex{}) - if err := m.HardSupplyRewardFactors[len(m.HardSupplyRewardFactors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HardBorrowRewardFactors", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.HardBorrowRewardFactors = append(m.HardBorrowRewardFactors, MultiRewardIndex{}) - if err := m.HardBorrowRewardFactors[len(m.HardBorrowRewardFactors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DelegatorRewardFactors", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DelegatorRewardFactors = append(m.DelegatorRewardFactors, MultiRewardIndex{}) - if err := m.DelegatorRewardFactors[len(m.DelegatorRewardFactors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SwapRewardFactors", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SwapRewardFactors = append(m.SwapRewardFactors, MultiRewardIndex{}) - if err := m.SwapRewardFactors[len(m.SwapRewardFactors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SavingsRewardFactors", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SavingsRewardFactors = append(m.SavingsRewardFactors, MultiRewardIndex{}) - if err := m.SavingsRewardFactors[len(m.SavingsRewardFactors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field EarnRewardFactors", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.EarnRewardFactors = append(m.EarnRewardFactors, MultiRewardIndex{}) - if err := m.EarnRewardFactors[len(m.EarnRewardFactors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryApyRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryApyRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryApyRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryApyResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryApyResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryApyResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Earn", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Earn = append(m.Earn, Apy{}) - if err := m.Earn[len(m.Earn)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/incentive/types/query.pb.gw.go b/x/incentive/types/query.pb.gw.go deleted file mode 100644 index ffc69a87..00000000 --- a/x/incentive/types/query.pb.gw.go +++ /dev/null @@ -1,366 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/incentive/v1beta1/query.proto - -/* -Package types is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package types - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join - -func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Params(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Rewards_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Rewards_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRewardsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Rewards_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Rewards(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Rewards_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRewardsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Rewards_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Rewards(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_RewardFactors_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRewardFactorsRequest - var metadata runtime.ServerMetadata - - msg, err := client.RewardFactors(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_RewardFactors_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRewardFactorsRequest - var metadata runtime.ServerMetadata - - msg, err := server.RewardFactors(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Apy_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryApyRequest - var metadata runtime.ServerMetadata - - msg, err := client.Apy(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Apy_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryApyRequest - var metadata runtime.ServerMetadata - - msg, err := server.Apy(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Rewards_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Rewards_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Rewards_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_RewardFactors_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_RewardFactors_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_RewardFactors_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Apy_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Apy_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Apy_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Rewards_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Rewards_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Rewards_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_RewardFactors_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_RewardFactors_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_RewardFactors_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Apy_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Apy_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Apy_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "incentive", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Rewards_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "incentive", "v1beta1", "rewards"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_RewardFactors_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "incentive", "v1beta1", "reward_factors"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Apy_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "incentive", "v1beta1", "apy"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Rewards_0 = runtime.ForwardResponseMessage - - forward_Query_RewardFactors_0 = runtime.ForwardResponseMessage - - forward_Query_Apy_0 = runtime.ForwardResponseMessage -) diff --git a/x/incentive/types/sdk.go b/x/incentive/types/sdk.go deleted file mode 100644 index 10787a99..00000000 --- a/x/incentive/types/sdk.go +++ /dev/null @@ -1,20 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" -) - -// NewPeriod returns a new vesting period -func NewPeriod(amount sdk.Coins, length int64) vestingtypes.Period { - return vestingtypes.Period{Amount: amount, Length: length} -} - -// GetTotalVestingPeriodLength returns the summed length of all vesting periods -func GetTotalVestingPeriodLength(periods vestingtypes.Periods) int64 { - length := int64(0) - for _, period := range periods { - length += period.Length - } - return length -} diff --git a/x/incentive/types/sdk_test.go b/x/incentive/types/sdk_test.go deleted file mode 100644 index 95d7ac43..00000000 --- a/x/incentive/types/sdk_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - - "github.com/0glabs/0g-chain/x/incentive/types" -) - -func TestGetTotalVestingPeriodLength(t *testing.T) { - testCases := []struct { - name string - periods vestingtypes.Periods - expectedVal int64 - }{ - { - name: "two period lengths are added together", - periods: vestingtypes.Periods{ - { - Length: 100, - }, - { - Length: 200, - }, - }, - expectedVal: 300, - }, - { - name: "no periods returns zero", - periods: nil, - expectedVal: 0, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - length := types.GetTotalVestingPeriodLength(tc.periods) - require.Equal(t, tc.expectedVal, length) - }) - } -} diff --git a/x/incentive/types/tx.pb.go b/x/incentive/types/tx.pb.go deleted file mode 100644 index 70a98731..00000000 --- a/x/incentive/types/tx.pb.go +++ /dev/null @@ -1,2678 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/incentive/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// Selection is a pair of denom and multiplier name. It holds the choice of multiplier a user makes when they claim a -// denom. -type Selection struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - MultiplierName string `protobuf:"bytes,2,opt,name=multiplier_name,json=multiplierName,proto3" json:"multiplier_name,omitempty"` -} - -func (m *Selection) Reset() { *m = Selection{} } -func (m *Selection) String() string { return proto.CompactTextString(m) } -func (*Selection) ProtoMessage() {} -func (*Selection) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{0} -} -func (m *Selection) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Selection) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Selection.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Selection) XXX_Merge(src proto.Message) { - xxx_messageInfo_Selection.Merge(m, src) -} -func (m *Selection) XXX_Size() int { - return m.Size() -} -func (m *Selection) XXX_DiscardUnknown() { - xxx_messageInfo_Selection.DiscardUnknown(m) -} - -var xxx_messageInfo_Selection proto.InternalMessageInfo - -// MsgClaimUSDXMintingReward message type used to claim USDX minting rewards -type MsgClaimUSDXMintingReward struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - MultiplierName string `protobuf:"bytes,2,opt,name=multiplier_name,json=multiplierName,proto3" json:"multiplier_name,omitempty"` -} - -func (m *MsgClaimUSDXMintingReward) Reset() { *m = MsgClaimUSDXMintingReward{} } -func (m *MsgClaimUSDXMintingReward) String() string { return proto.CompactTextString(m) } -func (*MsgClaimUSDXMintingReward) ProtoMessage() {} -func (*MsgClaimUSDXMintingReward) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{1} -} -func (m *MsgClaimUSDXMintingReward) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimUSDXMintingReward) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimUSDXMintingReward.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgClaimUSDXMintingReward) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimUSDXMintingReward.Merge(m, src) -} -func (m *MsgClaimUSDXMintingReward) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimUSDXMintingReward) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimUSDXMintingReward.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimUSDXMintingReward proto.InternalMessageInfo - -// MsgClaimUSDXMintingRewardResponse defines the Msg/ClaimUSDXMintingReward response type. -type MsgClaimUSDXMintingRewardResponse struct { -} - -func (m *MsgClaimUSDXMintingRewardResponse) Reset() { *m = MsgClaimUSDXMintingRewardResponse{} } -func (m *MsgClaimUSDXMintingRewardResponse) String() string { return proto.CompactTextString(m) } -func (*MsgClaimUSDXMintingRewardResponse) ProtoMessage() {} -func (*MsgClaimUSDXMintingRewardResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{2} -} -func (m *MsgClaimUSDXMintingRewardResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimUSDXMintingRewardResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimUSDXMintingRewardResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgClaimUSDXMintingRewardResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimUSDXMintingRewardResponse.Merge(m, src) -} -func (m *MsgClaimUSDXMintingRewardResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimUSDXMintingRewardResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimUSDXMintingRewardResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimUSDXMintingRewardResponse proto.InternalMessageInfo - -// MsgClaimHardReward message type used to claim Hard liquidity provider rewards -type MsgClaimHardReward struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - DenomsToClaim Selections `protobuf:"bytes,2,rep,name=denoms_to_claim,json=denomsToClaim,proto3,castrepeated=Selections" json:"denoms_to_claim"` -} - -func (m *MsgClaimHardReward) Reset() { *m = MsgClaimHardReward{} } -func (m *MsgClaimHardReward) String() string { return proto.CompactTextString(m) } -func (*MsgClaimHardReward) ProtoMessage() {} -func (*MsgClaimHardReward) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{3} -} -func (m *MsgClaimHardReward) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimHardReward) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimHardReward.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgClaimHardReward) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimHardReward.Merge(m, src) -} -func (m *MsgClaimHardReward) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimHardReward) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimHardReward.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimHardReward proto.InternalMessageInfo - -// MsgClaimHardRewardResponse defines the Msg/ClaimHardReward response type. -type MsgClaimHardRewardResponse struct { -} - -func (m *MsgClaimHardRewardResponse) Reset() { *m = MsgClaimHardRewardResponse{} } -func (m *MsgClaimHardRewardResponse) String() string { return proto.CompactTextString(m) } -func (*MsgClaimHardRewardResponse) ProtoMessage() {} -func (*MsgClaimHardRewardResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{4} -} -func (m *MsgClaimHardRewardResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimHardRewardResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimHardRewardResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgClaimHardRewardResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimHardRewardResponse.Merge(m, src) -} -func (m *MsgClaimHardRewardResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimHardRewardResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimHardRewardResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimHardRewardResponse proto.InternalMessageInfo - -// MsgClaimDelegatorReward message type used to claim delegator rewards -type MsgClaimDelegatorReward struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - DenomsToClaim Selections `protobuf:"bytes,2,rep,name=denoms_to_claim,json=denomsToClaim,proto3,castrepeated=Selections" json:"denoms_to_claim"` -} - -func (m *MsgClaimDelegatorReward) Reset() { *m = MsgClaimDelegatorReward{} } -func (m *MsgClaimDelegatorReward) String() string { return proto.CompactTextString(m) } -func (*MsgClaimDelegatorReward) ProtoMessage() {} -func (*MsgClaimDelegatorReward) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{5} -} -func (m *MsgClaimDelegatorReward) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimDelegatorReward) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimDelegatorReward.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgClaimDelegatorReward) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimDelegatorReward.Merge(m, src) -} -func (m *MsgClaimDelegatorReward) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimDelegatorReward) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimDelegatorReward.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimDelegatorReward proto.InternalMessageInfo - -// MsgClaimDelegatorRewardResponse defines the Msg/ClaimDelegatorReward response type. -type MsgClaimDelegatorRewardResponse struct { -} - -func (m *MsgClaimDelegatorRewardResponse) Reset() { *m = MsgClaimDelegatorRewardResponse{} } -func (m *MsgClaimDelegatorRewardResponse) String() string { return proto.CompactTextString(m) } -func (*MsgClaimDelegatorRewardResponse) ProtoMessage() {} -func (*MsgClaimDelegatorRewardResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{6} -} -func (m *MsgClaimDelegatorRewardResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimDelegatorRewardResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimDelegatorRewardResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgClaimDelegatorRewardResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimDelegatorRewardResponse.Merge(m, src) -} -func (m *MsgClaimDelegatorRewardResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimDelegatorRewardResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimDelegatorRewardResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimDelegatorRewardResponse proto.InternalMessageInfo - -// MsgClaimSwapReward message type used to claim delegator rewards -type MsgClaimSwapReward struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - DenomsToClaim Selections `protobuf:"bytes,2,rep,name=denoms_to_claim,json=denomsToClaim,proto3,castrepeated=Selections" json:"denoms_to_claim"` -} - -func (m *MsgClaimSwapReward) Reset() { *m = MsgClaimSwapReward{} } -func (m *MsgClaimSwapReward) String() string { return proto.CompactTextString(m) } -func (*MsgClaimSwapReward) ProtoMessage() {} -func (*MsgClaimSwapReward) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{7} -} -func (m *MsgClaimSwapReward) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimSwapReward) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimSwapReward.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgClaimSwapReward) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimSwapReward.Merge(m, src) -} -func (m *MsgClaimSwapReward) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimSwapReward) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimSwapReward.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimSwapReward proto.InternalMessageInfo - -// MsgClaimSwapRewardResponse defines the Msg/ClaimSwapReward response type. -type MsgClaimSwapRewardResponse struct { -} - -func (m *MsgClaimSwapRewardResponse) Reset() { *m = MsgClaimSwapRewardResponse{} } -func (m *MsgClaimSwapRewardResponse) String() string { return proto.CompactTextString(m) } -func (*MsgClaimSwapRewardResponse) ProtoMessage() {} -func (*MsgClaimSwapRewardResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{8} -} -func (m *MsgClaimSwapRewardResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimSwapRewardResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimSwapRewardResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgClaimSwapRewardResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimSwapRewardResponse.Merge(m, src) -} -func (m *MsgClaimSwapRewardResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimSwapRewardResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimSwapRewardResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimSwapRewardResponse proto.InternalMessageInfo - -// MsgClaimSavingsReward message type used to claim savings rewards -type MsgClaimSavingsReward struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - DenomsToClaim Selections `protobuf:"bytes,2,rep,name=denoms_to_claim,json=denomsToClaim,proto3,castrepeated=Selections" json:"denoms_to_claim"` -} - -func (m *MsgClaimSavingsReward) Reset() { *m = MsgClaimSavingsReward{} } -func (m *MsgClaimSavingsReward) String() string { return proto.CompactTextString(m) } -func (*MsgClaimSavingsReward) ProtoMessage() {} -func (*MsgClaimSavingsReward) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{9} -} -func (m *MsgClaimSavingsReward) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimSavingsReward) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimSavingsReward.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgClaimSavingsReward) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimSavingsReward.Merge(m, src) -} -func (m *MsgClaimSavingsReward) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimSavingsReward) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimSavingsReward.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimSavingsReward proto.InternalMessageInfo - -// MsgClaimSavingsRewardResponse defines the Msg/ClaimSavingsReward response type. -type MsgClaimSavingsRewardResponse struct { -} - -func (m *MsgClaimSavingsRewardResponse) Reset() { *m = MsgClaimSavingsRewardResponse{} } -func (m *MsgClaimSavingsRewardResponse) String() string { return proto.CompactTextString(m) } -func (*MsgClaimSavingsRewardResponse) ProtoMessage() {} -func (*MsgClaimSavingsRewardResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{10} -} -func (m *MsgClaimSavingsRewardResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimSavingsRewardResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimSavingsRewardResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgClaimSavingsRewardResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimSavingsRewardResponse.Merge(m, src) -} -func (m *MsgClaimSavingsRewardResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimSavingsRewardResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimSavingsRewardResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimSavingsRewardResponse proto.InternalMessageInfo - -// MsgClaimEarnReward message type used to claim earn rewards -type MsgClaimEarnReward struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - DenomsToClaim Selections `protobuf:"bytes,2,rep,name=denoms_to_claim,json=denomsToClaim,proto3,castrepeated=Selections" json:"denoms_to_claim"` -} - -func (m *MsgClaimEarnReward) Reset() { *m = MsgClaimEarnReward{} } -func (m *MsgClaimEarnReward) String() string { return proto.CompactTextString(m) } -func (*MsgClaimEarnReward) ProtoMessage() {} -func (*MsgClaimEarnReward) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{11} -} -func (m *MsgClaimEarnReward) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimEarnReward) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimEarnReward.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgClaimEarnReward) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimEarnReward.Merge(m, src) -} -func (m *MsgClaimEarnReward) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimEarnReward) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimEarnReward.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimEarnReward proto.InternalMessageInfo - -// MsgClaimEarnRewardResponse defines the Msg/ClaimEarnReward response type. -type MsgClaimEarnRewardResponse struct { -} - -func (m *MsgClaimEarnRewardResponse) Reset() { *m = MsgClaimEarnRewardResponse{} } -func (m *MsgClaimEarnRewardResponse) String() string { return proto.CompactTextString(m) } -func (*MsgClaimEarnRewardResponse) ProtoMessage() {} -func (*MsgClaimEarnRewardResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b1cec058e3ff75d5, []int{12} -} -func (m *MsgClaimEarnRewardResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClaimEarnRewardResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClaimEarnRewardResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgClaimEarnRewardResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClaimEarnRewardResponse.Merge(m, src) -} -func (m *MsgClaimEarnRewardResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgClaimEarnRewardResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClaimEarnRewardResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClaimEarnRewardResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Selection)(nil), "kava.incentive.v1beta1.Selection") - proto.RegisterType((*MsgClaimUSDXMintingReward)(nil), "kava.incentive.v1beta1.MsgClaimUSDXMintingReward") - proto.RegisterType((*MsgClaimUSDXMintingRewardResponse)(nil), "kava.incentive.v1beta1.MsgClaimUSDXMintingRewardResponse") - proto.RegisterType((*MsgClaimHardReward)(nil), "kava.incentive.v1beta1.MsgClaimHardReward") - proto.RegisterType((*MsgClaimHardRewardResponse)(nil), "kava.incentive.v1beta1.MsgClaimHardRewardResponse") - proto.RegisterType((*MsgClaimDelegatorReward)(nil), "kava.incentive.v1beta1.MsgClaimDelegatorReward") - proto.RegisterType((*MsgClaimDelegatorRewardResponse)(nil), "kava.incentive.v1beta1.MsgClaimDelegatorRewardResponse") - proto.RegisterType((*MsgClaimSwapReward)(nil), "kava.incentive.v1beta1.MsgClaimSwapReward") - proto.RegisterType((*MsgClaimSwapRewardResponse)(nil), "kava.incentive.v1beta1.MsgClaimSwapRewardResponse") - proto.RegisterType((*MsgClaimSavingsReward)(nil), "kava.incentive.v1beta1.MsgClaimSavingsReward") - proto.RegisterType((*MsgClaimSavingsRewardResponse)(nil), "kava.incentive.v1beta1.MsgClaimSavingsRewardResponse") - proto.RegisterType((*MsgClaimEarnReward)(nil), "kava.incentive.v1beta1.MsgClaimEarnReward") - proto.RegisterType((*MsgClaimEarnRewardResponse)(nil), "kava.incentive.v1beta1.MsgClaimEarnRewardResponse") -} - -func init() { proto.RegisterFile("kava/incentive/v1beta1/tx.proto", fileDescriptor_b1cec058e3ff75d5) } - -var fileDescriptor_b1cec058e3ff75d5 = []byte{ - // 530 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x95, 0x41, 0x6b, 0x13, 0x41, - 0x14, 0xc7, 0x77, 0x5a, 0x5a, 0xec, 0x13, 0x2d, 0x0c, 0x31, 0xc6, 0x45, 0x77, 0x9b, 0x78, 0xb0, - 0x88, 0xdd, 0x6d, 0x22, 0x22, 0x7a, 0xac, 0x55, 0xbc, 0xc4, 0x43, 0x52, 0x41, 0x04, 0x09, 0x93, - 0x64, 0x9c, 0x0e, 0xee, 0xce, 0xc4, 0x9d, 0x69, 0x5a, 0x3d, 0x79, 0x12, 0x8f, 0x5e, 0x04, 0xf1, - 0xd4, 0xb3, 0x9f, 0xa4, 0xc7, 0x1e, 0x3d, 0xa9, 0x24, 0x20, 0x7e, 0x0c, 0xc9, 0x26, 0xd9, 0x0d, - 0xdd, 0x5d, 0xd7, 0x78, 0xca, 0x2d, 0x3b, 0xef, 0xff, 0xde, 0xfb, 0xfd, 0x1f, 0x79, 0x33, 0x60, - 0xbf, 0x22, 0x7d, 0xe2, 0x72, 0xd1, 0xa1, 0x42, 0xf3, 0x3e, 0x75, 0xfb, 0xd5, 0x36, 0xd5, 0xa4, - 0xea, 0xea, 0x23, 0xa7, 0x17, 0x48, 0x2d, 0x71, 0x71, 0x24, 0x70, 0x22, 0x81, 0x33, 0x11, 0x98, - 0x05, 0x26, 0x99, 0x0c, 0x25, 0xee, 0xe8, 0xd7, 0x58, 0x5d, 0xd9, 0x83, 0xb5, 0x26, 0xf5, 0x68, - 0x47, 0x73, 0x29, 0x70, 0x01, 0x56, 0xba, 0x54, 0x48, 0xbf, 0x84, 0x36, 0xd0, 0xe6, 0x5a, 0x63, - 0xfc, 0x81, 0x6f, 0xc0, 0xba, 0x7f, 0xe0, 0x69, 0xde, 0xf3, 0x38, 0x0d, 0x5a, 0x82, 0xf8, 0xb4, - 0xb4, 0x14, 0xc6, 0x2f, 0xc6, 0xc7, 0x4f, 0x88, 0x4f, 0xef, 0x9f, 0xfb, 0x70, 0x6c, 0x1b, 0xbf, - 0x8f, 0x6d, 0xa3, 0xf2, 0x12, 0xae, 0xd4, 0x15, 0x7b, 0xe0, 0x11, 0xee, 0x3f, 0x6d, 0xee, 0x3e, - 0xab, 0x73, 0xa1, 0xb9, 0x60, 0x0d, 0x7a, 0x48, 0x82, 0x2e, 0x2e, 0xc2, 0xaa, 0xa2, 0xa2, 0x4b, - 0x83, 0x49, 0x9b, 0xc9, 0xd7, 0xff, 0xf4, 0xb9, 0x0e, 0xe5, 0xcc, 0x3e, 0x0d, 0xaa, 0x7a, 0x52, - 0x28, 0x5a, 0xf9, 0x84, 0x00, 0x4f, 0x55, 0x8f, 0xc3, 0xc0, 0x5f, 0x31, 0x5e, 0xc0, 0x7a, 0xe8, - 0x5b, 0xb5, 0xb4, 0x6c, 0x75, 0x46, 0x49, 0xa5, 0xa5, 0x8d, 0xe5, 0xcd, 0xf3, 0xb5, 0xb2, 0x93, - 0x3e, 0x59, 0x27, 0x1a, 0xe0, 0x0e, 0x3e, 0xf9, 0x6e, 0x1b, 0x5f, 0x7f, 0xd8, 0x10, 0x1d, 0xa9, - 0xc6, 0x85, 0x71, 0xb5, 0x3d, 0x19, 0x02, 0xcc, 0xc0, 0x5f, 0x05, 0x33, 0x89, 0x15, 0x51, 0x7f, - 0x41, 0x70, 0x79, 0x1a, 0xde, 0xa5, 0x1e, 0x65, 0x44, 0xcb, 0x60, 0x51, 0xd0, 0xcb, 0x60, 0x67, - 0xb0, 0xa5, 0x4e, 0xbd, 0x79, 0x48, 0x7a, 0x0b, 0x38, 0xf5, 0x18, 0x2b, 0xa2, 0xfe, 0x8c, 0xe0, - 0x52, 0x14, 0x26, 0x7d, 0x2e, 0x98, 0x5a, 0x14, 0x70, 0x1b, 0xae, 0xa5, 0x92, 0xa5, 0x4e, 0xfc, - 0x21, 0x09, 0xc4, 0x02, 0x4e, 0x3c, 0xc6, 0x9a, 0x52, 0xd7, 0x7e, 0xad, 0xc0, 0x72, 0x5d, 0x31, - 0xfc, 0x1e, 0x41, 0x31, 0xe3, 0xc2, 0xa8, 0x66, 0x01, 0x65, 0xee, 0xbe, 0x79, 0x6f, 0xee, 0x94, - 0x29, 0x10, 0x7e, 0x0d, 0xeb, 0x67, 0xaf, 0x8a, 0x9b, 0x79, 0xd5, 0x62, 0xad, 0x59, 0xfb, 0x77, - 0x6d, 0xd4, 0xf2, 0x1d, 0x82, 0x42, 0xea, 0xa2, 0xbb, 0x79, 0xc5, 0xce, 0x24, 0x98, 0x77, 0xe7, - 0x4c, 0x48, 0xb8, 0x9e, 0x59, 0xd5, 0x5c, 0xd7, 0xb1, 0x36, 0xdf, 0x75, 0x72, 0xd7, 0xf0, 0x5b, - 0xc0, 0x29, 0x7b, 0xb6, 0x95, 0x5b, 0x69, 0x56, 0x6e, 0xde, 0x99, 0x4b, 0x9e, 0xb0, 0x3b, 0xb3, - 0x27, 0xb9, 0x76, 0x63, 0x6d, 0xbe, 0xdd, 0xe4, 0x1f, 0x7d, 0xe7, 0xd1, 0xc9, 0xc0, 0x42, 0xa7, - 0x03, 0x0b, 0xfd, 0x1c, 0x58, 0xe8, 0xe3, 0xd0, 0x32, 0x4e, 0x87, 0x96, 0xf1, 0x6d, 0x68, 0x19, - 0xcf, 0x6f, 0x31, 0xae, 0xf7, 0x0f, 0xda, 0x4e, 0x47, 0xfa, 0xee, 0x36, 0xf3, 0x48, 0x5b, 0xb9, - 0xdb, 0x6c, 0xab, 0xb3, 0x4f, 0xb8, 0x70, 0x8f, 0x66, 0x9e, 0x7a, 0xfd, 0xa6, 0x47, 0x55, 0x7b, - 0x35, 0x7c, 0xb8, 0x6f, 0xff, 0x09, 0x00, 0x00, 0xff, 0xff, 0x8f, 0x67, 0xde, 0x4d, 0x09, 0x08, - 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - // ClaimUSDXMintingReward is a message type used to claim USDX minting rewards - ClaimUSDXMintingReward(ctx context.Context, in *MsgClaimUSDXMintingReward, opts ...grpc.CallOption) (*MsgClaimUSDXMintingRewardResponse, error) - // ClaimHardReward is a message type used to claim Hard liquidity provider rewards - ClaimHardReward(ctx context.Context, in *MsgClaimHardReward, opts ...grpc.CallOption) (*MsgClaimHardRewardResponse, error) - // ClaimDelegatorReward is a message type used to claim delegator rewards - ClaimDelegatorReward(ctx context.Context, in *MsgClaimDelegatorReward, opts ...grpc.CallOption) (*MsgClaimDelegatorRewardResponse, error) - // ClaimSwapReward is a message type used to claim swap rewards - ClaimSwapReward(ctx context.Context, in *MsgClaimSwapReward, opts ...grpc.CallOption) (*MsgClaimSwapRewardResponse, error) - // ClaimSavingsReward is a message type used to claim savings rewards - ClaimSavingsReward(ctx context.Context, in *MsgClaimSavingsReward, opts ...grpc.CallOption) (*MsgClaimSavingsRewardResponse, error) - // ClaimEarnReward is a message type used to claim earn rewards - ClaimEarnReward(ctx context.Context, in *MsgClaimEarnReward, opts ...grpc.CallOption) (*MsgClaimEarnRewardResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) ClaimUSDXMintingReward(ctx context.Context, in *MsgClaimUSDXMintingReward, opts ...grpc.CallOption) (*MsgClaimUSDXMintingRewardResponse, error) { - out := new(MsgClaimUSDXMintingRewardResponse) - err := c.cc.Invoke(ctx, "/kava.incentive.v1beta1.Msg/ClaimUSDXMintingReward", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ClaimHardReward(ctx context.Context, in *MsgClaimHardReward, opts ...grpc.CallOption) (*MsgClaimHardRewardResponse, error) { - out := new(MsgClaimHardRewardResponse) - err := c.cc.Invoke(ctx, "/kava.incentive.v1beta1.Msg/ClaimHardReward", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ClaimDelegatorReward(ctx context.Context, in *MsgClaimDelegatorReward, opts ...grpc.CallOption) (*MsgClaimDelegatorRewardResponse, error) { - out := new(MsgClaimDelegatorRewardResponse) - err := c.cc.Invoke(ctx, "/kava.incentive.v1beta1.Msg/ClaimDelegatorReward", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ClaimSwapReward(ctx context.Context, in *MsgClaimSwapReward, opts ...grpc.CallOption) (*MsgClaimSwapRewardResponse, error) { - out := new(MsgClaimSwapRewardResponse) - err := c.cc.Invoke(ctx, "/kava.incentive.v1beta1.Msg/ClaimSwapReward", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ClaimSavingsReward(ctx context.Context, in *MsgClaimSavingsReward, opts ...grpc.CallOption) (*MsgClaimSavingsRewardResponse, error) { - out := new(MsgClaimSavingsRewardResponse) - err := c.cc.Invoke(ctx, "/kava.incentive.v1beta1.Msg/ClaimSavingsReward", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ClaimEarnReward(ctx context.Context, in *MsgClaimEarnReward, opts ...grpc.CallOption) (*MsgClaimEarnRewardResponse, error) { - out := new(MsgClaimEarnRewardResponse) - err := c.cc.Invoke(ctx, "/kava.incentive.v1beta1.Msg/ClaimEarnReward", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // ClaimUSDXMintingReward is a message type used to claim USDX minting rewards - ClaimUSDXMintingReward(context.Context, *MsgClaimUSDXMintingReward) (*MsgClaimUSDXMintingRewardResponse, error) - // ClaimHardReward is a message type used to claim Hard liquidity provider rewards - ClaimHardReward(context.Context, *MsgClaimHardReward) (*MsgClaimHardRewardResponse, error) - // ClaimDelegatorReward is a message type used to claim delegator rewards - ClaimDelegatorReward(context.Context, *MsgClaimDelegatorReward) (*MsgClaimDelegatorRewardResponse, error) - // ClaimSwapReward is a message type used to claim swap rewards - ClaimSwapReward(context.Context, *MsgClaimSwapReward) (*MsgClaimSwapRewardResponse, error) - // ClaimSavingsReward is a message type used to claim savings rewards - ClaimSavingsReward(context.Context, *MsgClaimSavingsReward) (*MsgClaimSavingsRewardResponse, error) - // ClaimEarnReward is a message type used to claim earn rewards - ClaimEarnReward(context.Context, *MsgClaimEarnReward) (*MsgClaimEarnRewardResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) ClaimUSDXMintingReward(ctx context.Context, req *MsgClaimUSDXMintingReward) (*MsgClaimUSDXMintingRewardResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ClaimUSDXMintingReward not implemented") -} -func (*UnimplementedMsgServer) ClaimHardReward(ctx context.Context, req *MsgClaimHardReward) (*MsgClaimHardRewardResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ClaimHardReward not implemented") -} -func (*UnimplementedMsgServer) ClaimDelegatorReward(ctx context.Context, req *MsgClaimDelegatorReward) (*MsgClaimDelegatorRewardResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ClaimDelegatorReward not implemented") -} -func (*UnimplementedMsgServer) ClaimSwapReward(ctx context.Context, req *MsgClaimSwapReward) (*MsgClaimSwapRewardResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ClaimSwapReward not implemented") -} -func (*UnimplementedMsgServer) ClaimSavingsReward(ctx context.Context, req *MsgClaimSavingsReward) (*MsgClaimSavingsRewardResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ClaimSavingsReward not implemented") -} -func (*UnimplementedMsgServer) ClaimEarnReward(ctx context.Context, req *MsgClaimEarnReward) (*MsgClaimEarnRewardResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ClaimEarnReward not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_ClaimUSDXMintingReward_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgClaimUSDXMintingReward) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ClaimUSDXMintingReward(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.incentive.v1beta1.Msg/ClaimUSDXMintingReward", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ClaimUSDXMintingReward(ctx, req.(*MsgClaimUSDXMintingReward)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ClaimHardReward_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgClaimHardReward) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ClaimHardReward(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.incentive.v1beta1.Msg/ClaimHardReward", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ClaimHardReward(ctx, req.(*MsgClaimHardReward)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ClaimDelegatorReward_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgClaimDelegatorReward) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ClaimDelegatorReward(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.incentive.v1beta1.Msg/ClaimDelegatorReward", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ClaimDelegatorReward(ctx, req.(*MsgClaimDelegatorReward)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ClaimSwapReward_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgClaimSwapReward) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ClaimSwapReward(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.incentive.v1beta1.Msg/ClaimSwapReward", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ClaimSwapReward(ctx, req.(*MsgClaimSwapReward)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ClaimSavingsReward_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgClaimSavingsReward) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ClaimSavingsReward(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.incentive.v1beta1.Msg/ClaimSavingsReward", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ClaimSavingsReward(ctx, req.(*MsgClaimSavingsReward)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ClaimEarnReward_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgClaimEarnReward) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ClaimEarnReward(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.incentive.v1beta1.Msg/ClaimEarnReward", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ClaimEarnReward(ctx, req.(*MsgClaimEarnReward)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.incentive.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "ClaimUSDXMintingReward", - Handler: _Msg_ClaimUSDXMintingReward_Handler, - }, - { - MethodName: "ClaimHardReward", - Handler: _Msg_ClaimHardReward_Handler, - }, - { - MethodName: "ClaimDelegatorReward", - Handler: _Msg_ClaimDelegatorReward_Handler, - }, - { - MethodName: "ClaimSwapReward", - Handler: _Msg_ClaimSwapReward_Handler, - }, - { - MethodName: "ClaimSavingsReward", - Handler: _Msg_ClaimSavingsReward_Handler, - }, - { - MethodName: "ClaimEarnReward", - Handler: _Msg_ClaimEarnReward_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/incentive/v1beta1/tx.proto", -} - -func (m *Selection) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Selection) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Selection) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.MultiplierName) > 0 { - i -= len(m.MultiplierName) - copy(dAtA[i:], m.MultiplierName) - i = encodeVarintTx(dAtA, i, uint64(len(m.MultiplierName))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintTx(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgClaimUSDXMintingReward) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgClaimUSDXMintingReward) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimUSDXMintingReward) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.MultiplierName) > 0 { - i -= len(m.MultiplierName) - copy(dAtA[i:], m.MultiplierName) - i = encodeVarintTx(dAtA, i, uint64(len(m.MultiplierName))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgClaimUSDXMintingRewardResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgClaimUSDXMintingRewardResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimUSDXMintingRewardResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgClaimHardReward) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgClaimHardReward) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimHardReward) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.DenomsToClaim) > 0 { - for iNdEx := len(m.DenomsToClaim) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DenomsToClaim[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgClaimHardRewardResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgClaimHardRewardResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimHardRewardResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgClaimDelegatorReward) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgClaimDelegatorReward) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimDelegatorReward) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.DenomsToClaim) > 0 { - for iNdEx := len(m.DenomsToClaim) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DenomsToClaim[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgClaimDelegatorRewardResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgClaimDelegatorRewardResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimDelegatorRewardResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgClaimSwapReward) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgClaimSwapReward) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimSwapReward) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.DenomsToClaim) > 0 { - for iNdEx := len(m.DenomsToClaim) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DenomsToClaim[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgClaimSwapRewardResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgClaimSwapRewardResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimSwapRewardResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgClaimSavingsReward) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgClaimSavingsReward) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimSavingsReward) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.DenomsToClaim) > 0 { - for iNdEx := len(m.DenomsToClaim) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DenomsToClaim[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgClaimSavingsRewardResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgClaimSavingsRewardResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimSavingsRewardResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgClaimEarnReward) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgClaimEarnReward) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimEarnReward) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.DenomsToClaim) > 0 { - for iNdEx := len(m.DenomsToClaim) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DenomsToClaim[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgClaimEarnRewardResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgClaimEarnRewardResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClaimEarnRewardResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Selection) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.MultiplierName) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgClaimUSDXMintingReward) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.MultiplierName) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgClaimUSDXMintingRewardResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgClaimHardReward) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.DenomsToClaim) > 0 { - for _, e := range m.DenomsToClaim { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgClaimHardRewardResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgClaimDelegatorReward) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.DenomsToClaim) > 0 { - for _, e := range m.DenomsToClaim { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgClaimDelegatorRewardResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgClaimSwapReward) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.DenomsToClaim) > 0 { - for _, e := range m.DenomsToClaim { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgClaimSwapRewardResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgClaimSavingsReward) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.DenomsToClaim) > 0 { - for _, e := range m.DenomsToClaim { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgClaimSavingsRewardResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgClaimEarnReward) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.DenomsToClaim) > 0 { - for _, e := range m.DenomsToClaim { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgClaimEarnRewardResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Selection) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Selection: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Selection: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MultiplierName", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MultiplierName = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimUSDXMintingReward) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimUSDXMintingReward: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimUSDXMintingReward: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MultiplierName", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MultiplierName = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimUSDXMintingRewardResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimUSDXMintingRewardResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimUSDXMintingRewardResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimHardReward) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimHardReward: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimHardReward: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DenomsToClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DenomsToClaim = append(m.DenomsToClaim, Selection{}) - if err := m.DenomsToClaim[len(m.DenomsToClaim)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimHardRewardResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimHardRewardResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimHardRewardResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimDelegatorReward) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimDelegatorReward: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimDelegatorReward: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DenomsToClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DenomsToClaim = append(m.DenomsToClaim, Selection{}) - if err := m.DenomsToClaim[len(m.DenomsToClaim)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimDelegatorRewardResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimDelegatorRewardResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimDelegatorRewardResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimSwapReward) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimSwapReward: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimSwapReward: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DenomsToClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DenomsToClaim = append(m.DenomsToClaim, Selection{}) - if err := m.DenomsToClaim[len(m.DenomsToClaim)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimSwapRewardResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimSwapRewardResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimSwapRewardResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimSavingsReward) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimSavingsReward: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimSavingsReward: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DenomsToClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DenomsToClaim = append(m.DenomsToClaim, Selection{}) - if err := m.DenomsToClaim[len(m.DenomsToClaim)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimSavingsRewardResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimSavingsRewardResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimSavingsRewardResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimEarnReward) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimEarnReward: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimEarnReward: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DenomsToClaim", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DenomsToClaim = append(m.DenomsToClaim, Selection{}) - if err := m.DenomsToClaim[len(m.DenomsToClaim)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClaimEarnRewardResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClaimEarnRewardResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClaimEarnRewardResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/kavadist/abci.go b/x/kavadist/abci.go deleted file mode 100644 index 65c249d0..00000000 --- a/x/kavadist/abci.go +++ /dev/null @@ -1,20 +0,0 @@ -package kavadist - -import ( - "time" - - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/kavadist/keeper" - "github.com/0glabs/0g-chain/x/kavadist/types" -) - -func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { - defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker) - - err := k.MintPeriodInflation(ctx) - if err != nil { - panic(err) - } -} diff --git a/x/kavadist/client/cli/query.go b/x/kavadist/client/cli/query.go deleted file mode 100644 index cfad1103..00000000 --- a/x/kavadist/client/cli/query.go +++ /dev/null @@ -1,81 +0,0 @@ -package cli - -import ( - "context" - "fmt" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - - "github.com/0glabs/0g-chain/x/kavadist/types" -) - -// GetQueryCmd returns the cli query commands for this module -func GetQueryCmd() *cobra.Command { - // Group kavadist queries under a subcommand - cmd := &cobra.Command{ - Use: types.ModuleName, - Short: fmt.Sprintf("Querying commands for the %s module", types.ModuleName), - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmd.AddCommand( - queryParamsCmd(), - queryBalanceCmd(), - ) - - return cmd -} - -func queryParamsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "params", - Short: "get the kavadist module parameters", - Long: "Get the current global kavadist module parameters.", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(cliCtx) - res, err := queryClient.Params(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - return cliCtx.PrintProto(&res.Params) - }, - } - flags.AddQueryFlagsToCmd(cmd) - return cmd -} - -func queryBalanceCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "balance", - Short: "get the kavadist module balance", - Long: "Get the current kavadist module account balance.", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(cliCtx) - res, err := queryClient.Balance(context.Background(), &types.QueryBalanceRequest{}) - if err != nil { - return err - } - return cliCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - return cmd -} diff --git a/x/kavadist/client/cli/tx.go b/x/kavadist/client/cli/tx.go deleted file mode 100644 index 6cea532b..00000000 --- a/x/kavadist/client/cli/tx.go +++ /dev/null @@ -1,91 +0,0 @@ -package cli - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/cosmos/cosmos-sdk/version" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - "github.com/0glabs/0g-chain/x/kavadist/types" -) - -// GetCmdSubmitProposal implements the command to submit a community-pool multi-spend proposal -func GetCmdSubmitProposal() *cobra.Command { - cmd := &cobra.Command{ - Use: "community-pool-multi-spend [proposal-file]", - Args: cobra.ExactArgs(1), - Short: "Submit a community pool multi-spend proposal", - Long: strings.TrimSpace( - fmt.Sprintf(`Submit a community pool multi-spend proposal along with an initial deposit. -The proposal details must be supplied via a JSON file. - -Example: -$ %s tx gov submit-proposal community-pool-multi-spend --from= - -Where proposal.json contains: - -{ - "title": "Community Pool Multi-Spend", - "description": "Pay many users some KAVA!", - "recipient_list": [ - { - "address": "kava1mz2003lathm95n5vnlthmtfvrzrjkrr53j4464", - "amount": [ - { - "denom": "ukava", - "amount": "1000000" - } - ] - }, - { - "address": "kava1zqezafa0luyetvtj8j67g336vaqtuudnsjq7vm", - "amount": [ - { - "denom": "ukava", - "amount": "1000000" - } - ] - } - ], - "deposit": [ - { - "denom": "ukava", - "amount": "1000000000" - } - ] -} -`, - version.AppName, - ), - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - proposal, err := ParseCommunityPoolMultiSpendProposalJSON(clientCtx.Codec, args[0]) - if err != nil { - return err - } - - from := clientCtx.GetFromAddress() - content := types.NewCommunityPoolMultiSpendProposal(proposal.Title, proposal.Description, proposal.RecipientList) - msg, err := govv1beta1.NewMsgSubmitProposal(content, proposal.Deposit, from) - if err != nil { - return err - } - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - return cmd -} diff --git a/x/kavadist/client/cli/utils.go b/x/kavadist/client/cli/utils.go deleted file mode 100644 index 9113bf8a..00000000 --- a/x/kavadist/client/cli/utils.go +++ /dev/null @@ -1,24 +0,0 @@ -package cli - -import ( - "io/ioutil" - - "github.com/cosmos/cosmos-sdk/codec" - - "github.com/0glabs/0g-chain/x/kavadist/types" -) - -// ParseCommunityPoolMultiSpendProposalJSON reads and parses a CommunityPoolMultiSpendProposalJSON from a file. -func ParseCommunityPoolMultiSpendProposalJSON(cdc codec.JSONCodec, proposalFile string) (types.CommunityPoolMultiSpendProposalJSON, error) { - proposal := types.CommunityPoolMultiSpendProposalJSON{} - contents, err := ioutil.ReadFile(proposalFile) - if err != nil { - return proposal, err - } - - if err := cdc.UnmarshalJSON(contents, &proposal); err != nil { - return proposal, err - } - - return proposal, nil -} diff --git a/x/kavadist/client/proposal_handler.go b/x/kavadist/client/proposal_handler.go deleted file mode 100644 index d28eae04..00000000 --- a/x/kavadist/client/proposal_handler.go +++ /dev/null @@ -1,12 +0,0 @@ -package client - -import ( - govclient "github.com/cosmos/cosmos-sdk/x/gov/client" - - "github.com/0glabs/0g-chain/x/kavadist/client/cli" -) - -// community-pool multi-spend proposal handler -var ( - ProposalHandler = govclient.NewProposalHandler(cli.GetCmdSubmitProposal) -) diff --git a/x/kavadist/genesis.go b/x/kavadist/genesis.go deleted file mode 100644 index d92e06e6..00000000 --- a/x/kavadist/genesis.go +++ /dev/null @@ -1,49 +0,0 @@ -package kavadist - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/kavadist/keeper" - "github.com/0glabs/0g-chain/x/kavadist/types" -) - -// InitGenesis initializes the store state from a genesis state. -func InitGenesis(ctx sdk.Context, k keeper.Keeper, accountKeeper types.AccountKeeper, gs *types.GenesisState) { - if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) - } - - k.SetParams(ctx, gs.Params) - - // only set the previous block time if it's different than default - if !gs.PreviousBlockTime.Equal(types.DefaultPreviousBlockTime) { - k.SetPreviousBlockTime(ctx, gs.PreviousBlockTime) - } - - // check if the module account exists - moduleAcc := accountKeeper.GetModuleAccount(ctx, types.KavaDistMacc) - if moduleAcc == nil { - panic(fmt.Sprintf("%s module account has not been set", types.KavaDistMacc)) - } - - // check if the fund account exists - fundModuleAcc := accountKeeper.GetModuleAccount(ctx, types.FundModuleAccount) - if fundModuleAcc == nil { - panic(fmt.Sprintf("%s module account has not been set", types.FundModuleAccount)) - } -} - -// ExportGenesis export genesis state for cdp module -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { - params := k.GetParams(ctx) - previousBlockTime, found := k.GetPreviousBlockTime(ctx) - if !found { - previousBlockTime = types.DefaultPreviousBlockTime - } - return &types.GenesisState{ - Params: params, - PreviousBlockTime: previousBlockTime, - } -} diff --git a/x/kavadist/genesis_test.go b/x/kavadist/genesis_test.go deleted file mode 100644 index 4f2f3cb5..00000000 --- a/x/kavadist/genesis_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package kavadist_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - tmtime "github.com/cometbft/cometbft/types/time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/kavadist" - testutil "github.com/0glabs/0g-chain/x/kavadist/testutil" - "github.com/0glabs/0g-chain/x/kavadist/types" -) - -type genesisTestSuite struct { - testutil.Suite -} - -func (suite *genesisTestSuite) TestInitGenesis_ValidationPanic() { - invalidState := types.NewGenesisState( - types.Params{ - Active: true, - Periods: []types.Period{ - { - Start: time.Date(2021, 1, 1, 1, 1, 1, 1, time.UTC), - End: tmtime.Canonical(time.Unix(1, 0)), - Inflation: sdk.OneDec(), - }, - }, - }, - tmtime.Canonical(time.Unix(1, 0)), - ) - - suite.Require().Panics(func() { - kavadist.InitGenesis(suite.Ctx, suite.Keeper, suite.AccountKeeper, invalidState) - }, "expected init genesis to panic with invalid state") -} - -func (suite *genesisTestSuite) TestInitAndExportGenesis() { - state := types.NewGenesisState( - types.Params{ - Active: true, - Periods: []types.Period{ - { - Start: time.Date(2021, 1, 1, 1, 1, 1, 1, time.UTC), - End: time.Date(2021, 2, 1, 1, 1, 1, 1, time.UTC), - Inflation: sdk.OneDec(), - }, - }, - }, - time.Date(2020, 1, 2, 1, 1, 1, 1, time.UTC), - ) - - kavadist.InitGenesis(suite.Ctx, suite.Keeper, suite.AccountKeeper, state) - suite.Require().Equal(state.Params, suite.Keeper.GetParams(suite.Ctx)) - - exportedState := kavadist.ExportGenesis(suite.Ctx, suite.Keeper) - suite.Require().Equal(state, exportedState) -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(genesisTestSuite)) -} diff --git a/x/kavadist/handler.go b/x/kavadist/handler.go deleted file mode 100644 index 30474fa7..00000000 --- a/x/kavadist/handler.go +++ /dev/null @@ -1,23 +0,0 @@ -package kavadist - -import ( - errorsmod "cosmossdk.io/errors" - 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/0glabs/0g-chain/x/kavadist/keeper" - "github.com/0glabs/0g-chain/x/kavadist/types" -) - -// NewCommunityPoolMultiSpendProposalHandler -func NewCommunityPoolMultiSpendProposalHandler(k keeper.Keeper) govv1beta1.Handler { - return func(ctx sdk.Context, content govv1beta1.Content) error { - switch c := content.(type) { - case *types.CommunityPoolMultiSpendProposal: - return keeper.HandleCommunityPoolMultiSpendProposal(ctx, k, c) - default: - return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized kavadist proposal content type: %T", c) - } - } -} diff --git a/x/kavadist/keeper/grpc_query.go b/x/kavadist/keeper/grpc_query.go deleted file mode 100644 index ab9090eb..00000000 --- a/x/kavadist/keeper/grpc_query.go +++ /dev/null @@ -1,34 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/kavadist/types" -) - -type queryServer struct { - keeper Keeper -} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(k Keeper) types.QueryServer { - return &queryServer{keeper: k} -} - -var _ types.QueryServer = queryServer{} - -func (s queryServer) Balance(ctx context.Context, req *types.QueryBalanceRequest) (*types.QueryBalanceResponse, error) { - sdkCtx := sdk.UnwrapSDKContext(ctx) - acc := s.keeper.accountKeeper.GetModuleAccount(sdkCtx, types.KavaDistMacc) - balance := s.keeper.bankKeeper.GetAllBalances(sdkCtx, acc.GetAddress()) - return &types.QueryBalanceResponse{Coins: balance}, nil -} - -func (s queryServer) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - sdkCtx := sdk.UnwrapSDKContext(ctx) - params := s.keeper.GetParams(sdkCtx) - - return &types.QueryParamsResponse{Params: params}, nil -} diff --git a/x/kavadist/keeper/grpc_query_test.go b/x/kavadist/keeper/grpc_query_test.go deleted file mode 100644 index 60c9641a..00000000 --- a/x/kavadist/keeper/grpc_query_test.go +++ /dev/null @@ -1,116 +0,0 @@ -package keeper_test - -import ( - "context" - "fmt" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/kavadist/types" -) - -func (suite *keeperTestSuite) TestGRPCParams() { - ctx, keeper, queryClient := suite.Ctx, suite.Keeper, suite.QueryClient - - var ( - params types.Params - req *types.QueryParamsRequest - expParams types.Params - ) - - testCases := []struct { - msg string - malleate func() - expPass bool - }{ - { - "response with default params", - func() { - expParams = types.DefaultParams() - keeper.SetParams(ctx, expParams) - req = &types.QueryParamsRequest{} - }, - true, - }, - { - "response with params", - func() { - params = types.Params{ - Active: true, - Periods: suite.TestPeriods, - } - keeper.SetParams(ctx, params) - req = &types.QueryParamsRequest{} - expParams = params - }, - true, - }, - } - - for _, testCase := range testCases { - suite.Run(fmt.Sprintf("Case %s", testCase.msg), func() { - testCase.malleate() - - paramsRes, err := queryClient.Params(context.Background(), req) - - if testCase.expPass { - suite.Require().NoError(err) - suite.Require().NotNil(paramsRes) - suite.Require().True(expParams.Equal(paramsRes.Params)) - } else { - suite.Require().Error(err) - } - }) - } -} - -func (suite *keeperTestSuite) TestGRPCBalance() { - ctx, queryClient := suite.Ctx, suite.QueryClient - - var ( - req *types.QueryBalanceRequest - expCoins sdk.Coins - ) - - testCases := []struct { - msg string - malleate func() - expPass bool - }{ - { - "response with no balance", - func() { - expCoins = sdk.Coins{} - req = &types.QueryBalanceRequest{} - }, - true, - }, - { - "response with balance", - func() { - expCoins = sdk.Coins{ - sdk.NewCoin("ukava", sdkmath.NewInt(100)), - } - suite.App.FundModuleAccount(ctx, types.ModuleName, expCoins) - req = &types.QueryBalanceRequest{} - }, - true, - }, - } - - for _, testCase := range testCases { - suite.Run(fmt.Sprintf("Case %s", testCase.msg), func() { - testCase.malleate() - - res, err := queryClient.Balance(context.Background(), req) - - if testCase.expPass { - suite.Require().NoError(err) - suite.Require().True(expCoins.IsEqual(res.Coins)) - } else { - suite.Require().Error(err) - } - }) - } -} diff --git a/x/kavadist/keeper/infrastructure.go b/x/kavadist/keeper/infrastructure.go deleted file mode 100644 index 5ecefbdc..00000000 --- a/x/kavadist/keeper/infrastructure.go +++ /dev/null @@ -1,101 +0,0 @@ -package keeper - -import ( - "fmt" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/kavadist/types" -) - -func (k Keeper) mintInfrastructurePeriods(ctx sdk.Context, periods types.Periods, previousBlockTime time.Time) (sdk.Coin, sdkmath.Int, error) { - var err error - coinsMinted := sdk.NewCoin(types.GovDenom, sdk.ZeroInt()) - timeElapsed := sdk.ZeroInt() - for _, period := range periods { - switch { - // Case 1 - period is fully expired - case period.End.Before(previousBlockTime): - continue - - // Case 2 - period has ended since the previous block time - case period.End.After(previousBlockTime) && (period.End.Before(ctx.BlockTime()) || period.End.Equal(ctx.BlockTime())): - // calculate time elapsed relative to the periods end time - timeElapsed = sdkmath.NewInt(period.End.Unix() - previousBlockTime.Unix()) - coins, errI := k.mintInflationaryCoins(ctx, period.Inflation, timeElapsed, types.GovDenom) - err = errI - if !coins.IsZero() { - coinsMinted = coinsMinted.Add(coins) - } - // update the value of previousBlockTime so that the next period starts from the end of the last - // period and not the original value of previousBlockTime - previousBlockTime = period.End - - // Case 3 - period is ongoing - case (period.Start.Before(previousBlockTime) || period.Start.Equal(previousBlockTime)) && period.End.After(ctx.BlockTime()): - // calculate time elapsed relative to the current block time - timeElapsed = sdkmath.NewInt(ctx.BlockTime().Unix() - previousBlockTime.Unix()) - coins, errI := k.mintInflationaryCoins(ctx, period.Inflation, timeElapsed, types.GovDenom) - if !coins.IsZero() { - coinsMinted = coinsMinted.Add(coins) - } - err = errI - - // Case 4 - period hasn't started - case period.Start.After(ctx.BlockTime()) || period.Start.Equal(ctx.BlockTime()): - timeElapsed = sdkmath.NewInt(ctx.BlockTime().Unix() - previousBlockTime.Unix()) - continue - } - - if err != nil { - return sdk.Coin{}, sdkmath.Int{}, err - } - } - return coinsMinted, timeElapsed, nil -} - -func (k Keeper) distributeInfrastructureCoins(ctx sdk.Context, partnerRewards types.PartnerRewards, coreRewards types.CoreRewards, timeElapsed sdkmath.Int, coinsToDistribute sdk.Coin) error { - if timeElapsed.IsZero() { - return nil - } - if coinsToDistribute.IsZero() { - return nil - } - for _, pr := range partnerRewards { - coinsToSend := sdk.NewCoin(types.GovDenom, pr.RewardsPerSecond.Amount.Mul(timeElapsed)) - // TODO check balance, log if insufficient and return rather than error - err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, pr.Address, sdk.NewCoins(coinsToSend)) - if err != nil { - return err - } - neg, updatedCoins := safeSub(coinsToDistribute, coinsToSend) - if neg { - return fmt.Errorf("negative coins") - } - coinsToDistribute = updatedCoins - } - for _, cr := range coreRewards { - coinsToSend := sdk.NewCoin(types.GovDenom, sdk.NewDecFromInt(coinsToDistribute.Amount).Mul(cr.Weight).RoundInt()) - // TODO check balance, log if insufficient and return rather than error - err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, cr.Address, sdk.NewCoins(coinsToSend)) - if err != nil { - return err - } - neg, updatedCoins := safeSub(coinsToDistribute, coinsToSend) - if neg { - return fmt.Errorf("negative coins") - } - coinsToDistribute = updatedCoins - } - return nil -} - -func safeSub(a, b sdk.Coin) (bool, sdk.Coin) { - isNeg := a.IsLT(b) - if isNeg { - return true, sdk.Coin{} - } - return false, a.Sub(b) -} diff --git a/x/kavadist/keeper/keeper.go b/x/kavadist/keeper/keeper.go deleted file mode 100644 index fb1cd2eb..00000000 --- a/x/kavadist/keeper/keeper.go +++ /dev/null @@ -1,68 +0,0 @@ -package keeper - -import ( - "time" - - "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" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - - "github.com/0glabs/0g-chain/x/kavadist/types" -) - -// Keeper keeper for the cdp module -type Keeper struct { - key storetypes.StoreKey - cdc codec.BinaryCodec - paramSubspace paramtypes.Subspace - bankKeeper types.BankKeeper - distKeeper types.DistKeeper - accountKeeper types.AccountKeeper - - blacklistedAddrs map[string]bool -} - -// NewKeeper creates a new keeper -func NewKeeper( - cdc codec.BinaryCodec, key storetypes.StoreKey, paramstore paramtypes.Subspace, bk types.BankKeeper, ak types.AccountKeeper, - dk types.DistKeeper, blacklistedAddrs map[string]bool, -) Keeper { - if !paramstore.HasKeyTable() { - paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) - } - - return Keeper{ - key: key, - cdc: cdc, - paramSubspace: paramstore, - bankKeeper: bk, - distKeeper: dk, - accountKeeper: ak, - blacklistedAddrs: blacklistedAddrs, - } -} - -// GetPreviousBlockTime get the blocktime for the previous block -func (k Keeper) GetPreviousBlockTime(ctx sdk.Context) (blockTime time.Time, found bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousBlockTimeKey) - b := store.Get(types.PreviousBlockTimeKey) - if b == nil { - return time.Time{}, false - } - if err := blockTime.UnmarshalBinary(b); err != nil { - return time.Time{}, false - } - return blockTime, true -} - -// SetPreviousBlockTime set the time of the previous block -func (k Keeper) SetPreviousBlockTime(ctx sdk.Context, blockTime time.Time) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PreviousBlockTimeKey) - b, err := blockTime.MarshalBinary() - if err != nil { - panic(err) - } - store.Set(types.PreviousBlockTimeKey, b) -} diff --git a/x/kavadist/keeper/keeper_test.go b/x/kavadist/keeper/keeper_test.go deleted file mode 100644 index 62c62591..00000000 --- a/x/kavadist/keeper/keeper_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/x/kavadist/testutil" -) - -type keeperTestSuite struct { - testutil.Suite -} - -func (suite *keeperTestSuite) SetupTest() { - suite.Suite.SetupTest() -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(keeperTestSuite)) -} - -func (suite *keeperTestSuite) TestSetAndGetPreviousBlockTime() { - newTime := time.Date(2020, time.March, 1, 1, 0, 0, 0, time.UTC) - suite.Keeper.SetPreviousBlockTime(suite.Ctx, newTime) - blockTime, found := suite.Keeper.GetPreviousBlockTime(suite.Ctx) - suite.Require().True(found) - suite.Require().Equal(newTime, blockTime) -} diff --git a/x/kavadist/keeper/mint.go b/x/kavadist/keeper/mint.go deleted file mode 100644 index 496d35ba..00000000 --- a/x/kavadist/keeper/mint.go +++ /dev/null @@ -1,113 +0,0 @@ -package keeper - -import ( - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/kavadist/types" -) - -// MintPeriodInflation mints new tokens according to the inflation schedule specified in the parameters -func (k Keeper) MintPeriodInflation(ctx sdk.Context) error { - params := k.GetParams(ctx) - if !params.Active { - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeKavaDist, - sdk.NewAttribute(types.AttributeKeyStatus, types.AttributeValueInactive), - ), - ) - return nil - } - - previousBlockTime, found := k.GetPreviousBlockTime(ctx) - if !found { - previousBlockTime = ctx.BlockTime() - k.SetPreviousBlockTime(ctx, previousBlockTime) - return nil - } - err := k.mintIncentivePeriods(ctx, params.Periods, previousBlockTime) - if err != nil { - return err - } - - coinsToDistribute, timeElapsed, err := k.mintInfrastructurePeriods(ctx, params.InfrastructureParams.InfrastructurePeriods, previousBlockTime) - if err != nil { - return err - } - - err = k.distributeInfrastructureCoins(ctx, params.InfrastructureParams.PartnerRewards, params.InfrastructureParams.CoreRewards, timeElapsed, coinsToDistribute) - if err != nil { - return err - } - k.SetPreviousBlockTime(ctx, ctx.BlockTime()) - return nil -} - -func (k Keeper) mintIncentivePeriods(ctx sdk.Context, periods types.Periods, previousBlockTime time.Time) error { - var err error - for _, period := range periods { - switch { - // Case 1 - period is fully expired - case period.End.Before(previousBlockTime): - continue - - // Case 2 - period has ended since the previous block time - case period.End.After(previousBlockTime) && (period.End.Before(ctx.BlockTime()) || period.End.Equal(ctx.BlockTime())): - // calculate time elapsed relative to the periods end time - timeElapsed := sdkmath.NewInt(period.End.Unix() - previousBlockTime.Unix()) - _, err = k.mintInflationaryCoins(ctx, period.Inflation, timeElapsed, types.GovDenom) - // update the value of previousBlockTime so that the next period starts from the end of the last - // period and not the original value of previousBlockTime - previousBlockTime = period.End - - // Case 3 - period is ongoing - case (period.Start.Before(previousBlockTime) || period.Start.Equal(previousBlockTime)) && period.End.After(ctx.BlockTime()): - // calculate time elapsed relative to the current block time - timeElapsed := sdkmath.NewInt(ctx.BlockTime().Unix() - previousBlockTime.Unix()) - _, err = k.mintInflationaryCoins(ctx, period.Inflation, timeElapsed, types.GovDenom) - - // Case 4 - period hasn't started - case period.Start.After(ctx.BlockTime()) || period.Start.Equal(ctx.BlockTime()): - continue - } - - if err != nil { - return err - } - } - return nil -} - -func (k Keeper) mintInflationaryCoins(ctx sdk.Context, inflationRate sdk.Dec, timePeriods sdkmath.Int, denom string) (sdk.Coin, error) { - totalSupply := k.bankKeeper.GetSupply(ctx, denom) - // used to scale accumulator calculations by 10^18 - scalar := sdkmath.NewInt(1000000000000000000) - // convert inflation rate to integer - inflationInt := sdkmath.NewUintFromBigInt(inflationRate.Mul(sdk.NewDecFromInt(scalar)).TruncateInt().BigInt()) - timePeriodsUint := sdkmath.NewUintFromBigInt(timePeriods.BigInt()) - scalarUint := sdkmath.NewUintFromBigInt(scalar.BigInt()) - // calculate the multiplier (amount to multiply the total supply by to achieve the desired inflation) - // multiply the result by 10^-18 because RelativePow returns the result scaled by 10^18 - accumulator := sdk.NewDecFromBigInt(sdkmath.RelativePow(inflationInt, timePeriodsUint, scalarUint).BigInt()).Mul(sdk.SmallestDec()) - // calculate the number of coins to mint - amountToMint := (sdk.NewDecFromInt(totalSupply.Amount).Mul(accumulator)).Sub(sdk.NewDecFromInt(totalSupply.Amount)).TruncateInt() - if amountToMint.IsZero() { - return sdk.Coin{}, nil - } - err := k.bankKeeper.MintCoins(ctx, types.KavaDistMacc, sdk.NewCoins(sdk.NewCoin(denom, amountToMint))) - if err != nil { - return sdk.Coin{}, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeKavaDist, - sdk.NewAttribute(types.AttributeKeyInflation, sdk.NewCoin(denom, amountToMint).String()), - ), - ) - - return sdk.NewCoin(denom, amountToMint), nil -} diff --git a/x/kavadist/keeper/mint_test.go b/x/kavadist/keeper/mint_test.go deleted file mode 100644 index be86f6fa..00000000 --- a/x/kavadist/keeper/mint_test.go +++ /dev/null @@ -1,408 +0,0 @@ -package keeper_test - -import ( - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/kavadist/types" -) - -func (suite *keeperTestSuite) TestMintExpiredPeriod() { - initialSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - suite.Require().NotPanics(func() { suite.Keeper.SetPreviousBlockTime(suite.Ctx, time.Date(2022, 1, 1, 0, 0, 0, 0, time.UTC)) }) - ctx := suite.Ctx.WithBlockTime(time.Date(2022, 1, 1, 0, 7, 0, 0, time.UTC)) - err := suite.Keeper.MintPeriodInflation(ctx) - suite.Require().NoError(err) - finalSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - suite.Require().Equal(initialSupply, finalSupply) -} - -func (suite *keeperTestSuite) TestMintPeriodNotStarted() { - initialSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - suite.Require().NotPanics(func() { suite.Keeper.SetPreviousBlockTime(suite.Ctx, time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)) }) - ctx := suite.Ctx.WithBlockTime(time.Date(2019, 1, 1, 0, 7, 0, 0, time.UTC)) - err := suite.Keeper.MintPeriodInflation(ctx) - suite.Require().NoError(err) - finalSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - suite.Require().Equal(initialSupply, finalSupply) -} - -func (suite *keeperTestSuite) TestMintOngoingPeriod() { - initialSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - suite.Require().NotPanics(func() { - suite.Keeper.SetPreviousBlockTime(suite.Ctx, time.Date(2020, time.March, 1, 1, 0, 1, 0, time.UTC)) - }) - ctx := suite.Ctx.WithBlockTime(time.Date(2021, 2, 28, 23, 59, 59, 0, time.UTC)) - err := suite.Keeper.MintPeriodInflation(ctx) - suite.Require().NoError(err) - finalSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - suite.Require().True(finalSupply.Amount.GT(initialSupply.Amount)) - mAcc := suite.AccountKeeper.GetModuleAccount(ctx, types.ModuleName) - mAccSupply := suite.BankKeeper.GetAllBalances(ctx, mAcc.GetAddress()).AmountOf(types.GovDenom) - suite.Require().True(mAccSupply.Equal(finalSupply.Amount.Sub(initialSupply.Amount))) - // expect that inflation is ~10% - expectedSupply := sdk.NewDecFromInt(initialSupply.Amount).Mul(sdk.MustNewDecFromStr("1.1")) - supplyError := sdk.OneDec().Sub((sdk.NewDecFromInt(finalSupply.Amount).Quo(expectedSupply))).Abs() - suite.Require().True(supplyError.LTE(sdk.MustNewDecFromStr("0.001"))) -} - -func (suite *keeperTestSuite) TestMintPeriodTransition() { - initialSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - params := suite.Keeper.GetParams(suite.Ctx) - periods := []types.Period{ - suite.TestPeriods[0], - { - Start: time.Date(2021, time.March, 1, 1, 0, 0, 0, time.UTC), - End: time.Date(2022, time.March, 1, 1, 0, 0, 0, time.UTC), - Inflation: sdk.MustNewDecFromStr("1.000000003022265980"), - }, - } - params.Periods = periods - suite.Require().NotPanics(func() { - suite.Keeper.SetParams(suite.Ctx, params) - }) - suite.Require().NotPanics(func() { - suite.Keeper.SetPreviousBlockTime(suite.Ctx, time.Date(2020, time.March, 1, 1, 0, 1, 0, time.UTC)) - }) - ctx := suite.Ctx.WithBlockTime(time.Date(2021, 3, 10, 0, 0, 0, 0, time.UTC)) - err := suite.Keeper.MintPeriodInflation(ctx) - suite.Require().NoError(err) - finalSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - suite.Require().True(finalSupply.Amount.GT(initialSupply.Amount)) -} - -func (suite *keeperTestSuite) TestMintNotActive() { - initialSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - params := suite.Keeper.GetParams(suite.Ctx) - params.Active = false - suite.Require().NotPanics(func() { - suite.Keeper.SetParams(suite.Ctx, params) - }) - suite.Require().NotPanics(func() { - suite.Keeper.SetPreviousBlockTime(suite.Ctx, time.Date(2020, time.March, 1, 1, 0, 1, 0, time.UTC)) - }) - ctx := suite.Ctx.WithBlockTime(time.Date(2021, 2, 28, 23, 59, 59, 0, time.UTC)) - err := suite.Keeper.MintPeriodInflation(ctx) - suite.Require().NoError(err) - finalSupply := suite.BankKeeper.GetSupply(suite.Ctx, types.GovDenom) - suite.Require().Equal(initialSupply, finalSupply) -} - -func (suite *keeperTestSuite) TestInfraMinting() { - type args struct { - startTime time.Time - endTime time.Time - infraPeriods types.Periods - expectedFinalSupply sdk.Coin - marginOfError sdk.Dec - } - - type errArgs struct { - expectPass bool - contains string - } - - type test struct { - name string - args args - errArgs errArgs - } - - testCases := []test{ - { - "5% apy one year", - args{ - startTime: time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), - endTime: time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), - infraPeriods: types.Periods{types.NewPeriod(time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), sdk.MustNewDecFromStr("1.000000001547125958"))}, - expectedFinalSupply: sdk.NewCoin(types.GovDenom, sdkmath.NewInt(1050000000000)), - marginOfError: sdk.MustNewDecFromStr("0.0001"), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "5% apy 10 seconds", - args{ - startTime: time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), - endTime: time.Date(2022, time.October, 1, 1, 0, 10, 0, time.UTC), - infraPeriods: types.Periods{types.NewPeriod(time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), sdk.MustNewDecFromStr("1.000000001547125958"))}, - expectedFinalSupply: sdk.NewCoin(types.GovDenom, sdkmath.NewInt(1000000015471)), - marginOfError: sdk.MustNewDecFromStr("0.0001"), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - } - - for _, tc := range testCases { - suite.SetupTest() - params := types.NewParams(true, types.DefaultPeriods, types.NewInfraParams(tc.args.infraPeriods, types.DefaultInfraParams.PartnerRewards, types.DefaultInfraParams.CoreRewards)) - ctx := suite.Ctx.WithBlockTime(tc.args.startTime) - suite.Keeper.SetParams(ctx, params) - suite.Require().NotPanics(func() { - suite.Keeper.SetPreviousBlockTime(ctx, tc.args.startTime) - }) - - // Delete initial genesis tokens to start with a clean slate - suite.App.DeleteGenesisValidator(suite.T(), suite.Ctx) - suite.App.DeleteGenesisValidatorCoins(suite.T(), suite.Ctx) - - ctx = suite.Ctx.WithBlockTime(tc.args.endTime) - err := suite.Keeper.MintPeriodInflation(ctx) - suite.Require().NoError(err) - - finalSupply := suite.BankKeeper.GetSupply(ctx, types.GovDenom) - marginHigh := sdk.NewDecFromInt(tc.args.expectedFinalSupply.Amount).Mul(sdk.OneDec().Add(tc.args.marginOfError)) - marginLow := sdk.NewDecFromInt(tc.args.expectedFinalSupply.Amount).Mul(sdk.OneDec().Sub(tc.args.marginOfError)) - suite.Require().Truef( - sdk.NewDecFromInt(finalSupply.Amount).LTE(marginHigh), - "final supply %s is not <= %s high margin", - finalSupply.Amount.String(), - marginHigh.String(), - ) - suite.Require().Truef( - sdk.NewDecFromInt(finalSupply.Amount).GTE(marginLow), - "final supply %s is not >= %s low margin", - finalSupply.Amount.String(), - ) - - } - -} - -func (suite *keeperTestSuite) TestInfraPayoutCore() { - - type args struct { - startTime time.Time - endTime time.Time - infraPeriods types.Periods - expectedFinalSupply sdk.Coin - expectedBalanceIncrease sdk.Coin - marginOfError sdk.Dec - } - - type errArgs struct { - expectPass bool - contains string - } - - type test struct { - name string - args args - errArgs errArgs - } - - testCases := []test{ - { - "5% apy one year", - args{ - startTime: time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), - endTime: time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), - infraPeriods: types.Periods{types.NewPeriod(time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), sdk.MustNewDecFromStr("1.000000001547125958"))}, - expectedFinalSupply: sdk.NewCoin(types.GovDenom, sdkmath.NewInt(1050000000000)), - expectedBalanceIncrease: sdk.NewCoin(types.GovDenom, sdkmath.NewInt(50000000000)), - marginOfError: sdk.MustNewDecFromStr("0.0001"), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - } - - for _, tc := range testCases { - suite.SetupTest() - coreReward := types.NewCoreReward(suite.Addrs[0], sdk.OneDec()) - params := types.NewParams(true, types.DefaultPeriods, types.NewInfraParams(tc.args.infraPeriods, types.DefaultInfraParams.PartnerRewards, types.CoreRewards{coreReward})) - ctx := suite.Ctx.WithBlockTime(tc.args.startTime) - suite.Keeper.SetParams(ctx, params) - suite.Require().NotPanics(func() { - suite.Keeper.SetPreviousBlockTime(ctx, tc.args.startTime) - }) - - // Delete initial genesis tokens to start with a clean slate - suite.App.DeleteGenesisValidator(suite.T(), suite.Ctx) - suite.App.DeleteGenesisValidatorCoins(suite.T(), suite.Ctx) - - initialBalance := suite.BankKeeper.GetBalance(ctx, suite.Addrs[0], types.GovDenom) - ctx = suite.Ctx.WithBlockTime(tc.args.endTime) - err := suite.Keeper.MintPeriodInflation(ctx) - suite.Require().NoError(err) - finalSupply := suite.BankKeeper.GetSupply(ctx, types.GovDenom) - marginHigh := sdk.NewDecFromInt(tc.args.expectedFinalSupply.Amount).Mul(sdk.OneDec().Add(tc.args.marginOfError)) - marginLow := sdk.NewDecFromInt(tc.args.expectedFinalSupply.Amount).Mul(sdk.OneDec().Sub(tc.args.marginOfError)) - suite.Require().True(sdk.NewDecFromInt(finalSupply.Amount).LTE(marginHigh)) - suite.Require().True(sdk.NewDecFromInt(finalSupply.Amount).GTE(marginLow)) - - finalBalance := suite.BankKeeper.GetBalance(ctx, suite.Addrs[0], types.GovDenom) - suite.Require().Equal(tc.args.expectedBalanceIncrease, finalBalance.Sub(initialBalance)) - - } - -} - -func (suite *keeperTestSuite) TestInfraPayoutPartner() { - - type args struct { - startTime time.Time - endTime time.Time - infraPeriods types.Periods - expectedFinalSupply sdk.Coin - expectedBalanceIncrease sdk.Coin - marginOfError sdk.Dec - } - - type errArgs struct { - expectPass bool - contains string - } - - type test struct { - name string - args args - errArgs errArgs - } - - testCases := []test{ - { - "5% apy one year", - args{ - startTime: time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), - endTime: time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), - infraPeriods: types.Periods{types.NewPeriod(time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), sdk.MustNewDecFromStr("1.000000001547125958"))}, - expectedFinalSupply: sdk.NewCoin(types.GovDenom, sdkmath.NewInt(1050000000000)), - expectedBalanceIncrease: sdk.NewCoin(types.GovDenom, sdkmath.NewInt(63072000)), - marginOfError: sdk.MustNewDecFromStr("0.0001"), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - } - - for _, tc := range testCases { - suite.SetupTest() - partnerReward := types.NewPartnerReward(suite.Addrs[0], sdk.NewCoin(types.GovDenom, sdkmath.NewInt(2))) - params := types.NewParams(true, types.DefaultPeriods, types.NewInfraParams(tc.args.infraPeriods, types.PartnerRewards{partnerReward}, types.DefaultInfraParams.CoreRewards)) - ctx := suite.Ctx.WithBlockTime(tc.args.startTime) - suite.Keeper.SetParams(ctx, params) - suite.Require().NotPanics(func() { - suite.Keeper.SetPreviousBlockTime(ctx, tc.args.startTime) - }) - - // Delete initial genesis tokens to start with a clean slate - suite.App.DeleteGenesisValidator(suite.T(), suite.Ctx) - suite.App.DeleteGenesisValidatorCoins(suite.T(), suite.Ctx) - - initialBalance := suite.BankKeeper.GetBalance(ctx, suite.Addrs[0], types.GovDenom) - ctx = suite.Ctx.WithBlockTime(tc.args.endTime) - err := suite.Keeper.MintPeriodInflation(ctx) - suite.Require().NoError(err) - finalSupply := suite.BankKeeper.GetSupply(ctx, types.GovDenom) - marginHigh := sdk.NewDecFromInt(tc.args.expectedFinalSupply.Amount).Mul(sdk.OneDec().Add(tc.args.marginOfError)) - marginLow := sdk.NewDecFromInt(tc.args.expectedFinalSupply.Amount).Mul(sdk.OneDec().Sub(tc.args.marginOfError)) - suite.Require().True(sdk.NewDecFromInt(finalSupply.Amount).LTE(marginHigh)) - suite.Require().True(sdk.NewDecFromInt(finalSupply.Amount).GTE(marginLow)) - - finalBalance := suite.BankKeeper.GetBalance(ctx, suite.Addrs[0], types.GovDenom) - suite.Require().Equal(tc.args.expectedBalanceIncrease, finalBalance.Sub(initialBalance)) - - } - -} - -func (suite *keeperTestSuite) TestInfraPayoutE2E() { - - type balance struct { - address sdk.AccAddress - amount sdk.Coins - } - - type balances []balance - - type args struct { - periods types.Periods - startTime time.Time - endTime time.Time - infraPeriods types.Periods - coreRewards types.CoreRewards - partnerRewards types.PartnerRewards - expectedFinalSupply sdk.Coin - expectedBalances balances - marginOfError sdk.Dec - } - - type errArgs struct { - expectPass bool - contains string - } - - type test struct { - name string - args args - errArgs errArgs - } - - _, addrs := app.GeneratePrivKeyAddressPairs(3) - - testCases := []test{ - { - "5% apy one year", - args{ - periods: types.Periods{types.NewPeriod(time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), sdk.MustNewDecFromStr("1.000000001547125958"))}, - startTime: time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), - endTime: time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), - infraPeriods: types.Periods{types.NewPeriod(time.Date(2022, time.October, 1, 1, 0, 0, 0, time.UTC), time.Date(2023, time.October, 1, 1, 0, 0, 0, time.UTC), sdk.MustNewDecFromStr("1.000000001547125958"))}, - coreRewards: types.CoreRewards{types.NewCoreReward(addrs[1], sdk.OneDec())}, - partnerRewards: types.PartnerRewards{types.NewPartnerReward(addrs[2], sdk.NewCoin("ukava", sdkmath.NewInt(2)))}, - expectedFinalSupply: sdk.NewCoin(types.GovDenom, sdkmath.NewInt(1102500000000)), - expectedBalances: balances{ - balance{addrs[1], sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(52436928000)))}, - balance{addrs[2], sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(63072000)))}, - }, - marginOfError: sdk.MustNewDecFromStr("0.0001"), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - } - - for _, tc := range testCases { - suite.SetupTest() - params := types.NewParams(true, tc.args.periods, types.NewInfraParams(tc.args.infraPeriods, tc.args.partnerRewards, tc.args.coreRewards)) - ctx := suite.Ctx.WithBlockTime(tc.args.startTime) - suite.Keeper.SetParams(ctx, params) - suite.Require().NotPanics(func() { - suite.Keeper.SetPreviousBlockTime(ctx, tc.args.startTime) - }) - - // Delete initial genesis tokens to start with a clean slate - suite.App.DeleteGenesisValidator(suite.T(), suite.Ctx) - suite.App.DeleteGenesisValidatorCoins(suite.T(), suite.Ctx) - - ctx = suite.Ctx.WithBlockTime(tc.args.endTime) - err := suite.Keeper.MintPeriodInflation(ctx) - suite.Require().NoError(err) - finalSupply := suite.BankKeeper.GetSupply(ctx, types.GovDenom) - marginHigh := sdk.NewDecFromInt(tc.args.expectedFinalSupply.Amount).Mul(sdk.OneDec().Add(tc.args.marginOfError)) - marginLow := sdk.NewDecFromInt(tc.args.expectedFinalSupply.Amount).Mul(sdk.OneDec().Sub(tc.args.marginOfError)) - suite.Require().True(sdk.NewDecFromInt(finalSupply.Amount).LTE(marginHigh)) - suite.Require().True(sdk.NewDecFromInt(finalSupply.Amount).GTE(marginLow)) - - for _, bal := range tc.args.expectedBalances { - finalBalance := suite.BankKeeper.GetAllBalances(ctx, bal.address) - suite.Require().Equal(bal.amount, finalBalance) - } - } -} diff --git a/x/kavadist/keeper/params.go b/x/kavadist/keeper/params.go deleted file mode 100644 index 36fe2382..00000000 --- a/x/kavadist/keeper/params.go +++ /dev/null @@ -1,18 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/kavadist/types" -) - -// GetParams returns the params from the store -func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { - k.paramSubspace.GetParamSet(ctx, ¶ms) - return params -} - -// SetParams sets params on the store -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSubspace.SetParamSet(ctx, ¶ms) -} diff --git a/x/kavadist/keeper/proposal_handler.go b/x/kavadist/keeper/proposal_handler.go deleted file mode 100644 index 27f6f839..00000000 --- a/x/kavadist/keeper/proposal_handler.go +++ /dev/null @@ -1,24 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - "github.com/0glabs/0g-chain/x/kavadist/types" -) - -// HandleCommunityPoolMultiSpendProposal is a handler for executing a passed community multi-spend proposal -func HandleCommunityPoolMultiSpendProposal(ctx sdk.Context, k Keeper, p *types.CommunityPoolMultiSpendProposal) error { - for _, receiverInfo := range p.RecipientList { - if k.blacklistedAddrs[receiverInfo.Address] { - return errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "%s is blacklisted from receiving external funds", receiverInfo.Address) - } - err := k.distKeeper.DistributeFromFeePool(ctx, receiverInfo.Amount, receiverInfo.GetAddress()) - if err != nil { - return err - } - } - - return nil -} diff --git a/x/kavadist/keeper/proposal_handler_test.go b/x/kavadist/keeper/proposal_handler_test.go deleted file mode 100644 index 3355e7ea..00000000 --- a/x/kavadist/keeper/proposal_handler_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package keeper_test - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/kavadist/keeper" - "github.com/0glabs/0g-chain/x/kavadist/types" -) - -func (suite *keeperTestSuite) TestHandleCommunityPoolMultiSpendProposal() { - addr, distrKeeper, ctx := suite.Addrs[0], suite.App.GetDistrKeeper(), suite.Ctx - initBalances := suite.BankKeeper.GetAllBalances(ctx, addr) - - // add coins to the module account and fund fee pool - macc := distrKeeper.GetDistributionAccount(ctx) - fundAmount := sdk.NewCoins(sdk.NewInt64Coin("ukava", 1000000)) - suite.Require().NoError(suite.App.FundModuleAccount(ctx, macc.GetName(), fundAmount)) - feePool := distrKeeper.GetFeePool(ctx) - feePool.CommunityPool = sdk.NewDecCoinsFromCoins(fundAmount...) - distrKeeper.SetFeePool(ctx, feePool) - - proposalAmount1 := int64(1100) - proposalAmount2 := int64(1200) - proposal := types.NewCommunityPoolMultiSpendProposal("test title", "description", []types.MultiSpendRecipient{ - { - Address: addr.String(), - Amount: sdk.NewCoins(sdk.NewInt64Coin("ukava", proposalAmount1)), - }, - { - Address: addr.String(), - Amount: sdk.NewCoins(sdk.NewInt64Coin("ukava", proposalAmount2)), - }, - }) - err := keeper.HandleCommunityPoolMultiSpendProposal(ctx, suite.Keeper, proposal) - suite.Require().Nil(err) - - balances := suite.BankKeeper.GetAllBalances(ctx, addr) - expected := initBalances.AmountOf("ukava").Add(sdkmath.NewInt(proposalAmount1 + proposalAmount2)) - suite.Require().Equal(expected, balances.AmountOf("ukava")) -} diff --git a/x/kavadist/module.go b/x/kavadist/module.go deleted file mode 100644 index ec3fbbc1..00000000 --- a/x/kavadist/module.go +++ /dev/null @@ -1,144 +0,0 @@ -package kavadist - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - cdctypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - - "github.com/0glabs/0g-chain/x/kavadist/client/cli" - "github.com/0glabs/0g-chain/x/kavadist/keeper" - "github.com/0glabs/0g-chain/x/kavadist/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// ---------------------------------------------------------------------------- -// AppModuleBasic -// ---------------------------------------------------------------------------- - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -func NewAppModuleBasic() AppModuleBasic { - return AppModuleBasic{} -} - -// Name get module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// Registers legacy amino codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// RegisterInterfaces registers the module's interface types -func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) { - types.RegisterInterfaces(reg) -} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesisState()) -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var genState types.GenesisState - if err := cdc.UnmarshalJSON(bz, &genState); err != nil { - return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) - } - return genState.Validate() -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for kavadist module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) -} - -// GetTxCmd returns kavadist module's root tx command. -func (a AppModuleBasic) GetTxCmd() *cobra.Command { return nil } - -// GetQueryCmd returns kavadist module's root query command. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -// ---------------------------------------------------------------------------- -// AppModule -// ---------------------------------------------------------------------------- - -// AppModule implements the AppModule interface for kavadist module. -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, accountKeeper types.AccountKeeper) AppModule { - return AppModule{ - AppModuleBasic: NewAppModuleBasic(), - keeper: keeper, - accountKeeper: accountKeeper, - } -} - -// Name returns kavadist module's name. -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// RegisterServices registers a GRPC query service to respond to the -// module-specific GRPC queries. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) -} - -// RegisterInvariants registers kavadist module's invariants. -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// InitGenesis performs kavadist module's genesis initialization It returns -// no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { - var genState types.GenesisState - cdc.MustUnmarshalJSON(gs, &genState) - InitGenesis(ctx, am.keeper, am.accountKeeper, &genState) - return []abci.ValidatorUpdate{} -} - -// ExportGenesis returns kavadist module's exported genesis state as raw JSON bytes. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - genState := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(genState) -} - -// ConsensusVersion implements ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { return 1 } - -// BeginBlock executes all ABCI BeginBlock logic respective to kavadist module. -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { - BeginBlocker(ctx, am.keeper) -} - -// EndBlock executes all ABCI EndBlock logic respective to kavadist module. It -// returns no validator updates. -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/kavadist/spec/01_concepts.md b/x/kavadist/spec/01_concepts.md deleted file mode 100644 index df42d852..00000000 --- a/x/kavadist/spec/01_concepts.md +++ /dev/null @@ -1,9 +0,0 @@ - - -# Concepts - -The minting mechanism in this module is designed to allow governance to determine a set of inflationary periods and the APR rate of inflation for each period. This module mints coins each block according to the schedule such that after 1 year the APR inflation worth of coins will have been minted. Governance can alter the APR inflation using a parameter change proposal. Parameter change proposals that change the APR will take effect in the block after they pass. - -Additionally this module has parameters defining an inflationary period for minting rewards to a governance-specified list of infrastructure partners. Governance can alter the inflationary period and infrastructure reward distribution using a parameter change proposal. Parameter changes that change the distribution or inflationary period take effect the block after they pass. diff --git a/x/kavadist/spec/02_state.md b/x/kavadist/spec/02_state.md deleted file mode 100644 index abc3a0e6..00000000 --- a/x/kavadist/spec/02_state.md +++ /dev/null @@ -1,34 +0,0 @@ - - -# State - -## Parameters and Genesis State - -`Parameters` define the rate at which inflationary coins are minted and for how long inflationary periods last. - -```go -// Params governance parameters for kavadist module -type Params struct { - Active bool `json:"active" yaml:"active"` - Periods Periods `json:"periods" yaml:"periods"` -} - -// Period stores the specified start and end dates, and the inflation, expressed as a decimal representing the yearly APR of tokens that will be minted during that period -type Period struct { - Start time.Time `json:"start" yaml:"start"` // example "2020-03-01T15:20:00Z" - End time.Time `json:"end" yaml:"end"` // example "2020-06-01T15:20:00Z" - Inflation sdk.Dec `json:"inflation" yaml:"inflation"` // example "1.000000003022265980" - 10% inflation -} -``` - -`GenesisState` defines the state that must be persisted when the blockchain stops/restarts in order for normal function of the kavadist module to resume. - -```go -// GenesisState is the state that must be provided at genesis. -type GenesisState struct { - Params Params `json:"params" yaml:"params"` - PreviousBlockTime time.Time `json:"previous_block_time" yaml:"previous_block_time"` -} -``` diff --git a/x/kavadist/spec/03_messages.md b/x/kavadist/spec/03_messages.md deleted file mode 100644 index e72b7783..00000000 --- a/x/kavadist/spec/03_messages.md +++ /dev/null @@ -1,7 +0,0 @@ - - -# Messages - -There are no messages in the kavadist module. All state transitions are controlled by parameters, which can be updated via parameter change proposals. diff --git a/x/kavadist/spec/04_events.md b/x/kavadist/spec/04_events.md deleted file mode 100644 index c76d8b65..00000000 --- a/x/kavadist/spec/04_events.md +++ /dev/null @@ -1,14 +0,0 @@ - - -# Events - -The `x/kavadist` module emits the following events: - -## BeginBlock - -| Type | Attribute Key | Attribute Value | -|----------------------|---------------------|-----------------| -| kavadist | kava_dist_inflation | `{amount}` | -| kavadist | kava_dist_status | "inactive" | diff --git a/x/kavadist/spec/05_params.md b/x/kavadist/spec/05_params.md deleted file mode 100644 index 3860bc94..00000000 --- a/x/kavadist/spec/05_params.md +++ /dev/null @@ -1,43 +0,0 @@ - - -# Parameters - -The kavadist module has the following parameters: - -| Key | Type | Example | Description | -| -------------------- | -------------------- | ------------- | -------------------------------------------------------- | -| Active | bool | true | an all-or-nothing toggle of token minting in this module | -| Periods | array (Period) | [{see below}] | array of params for each inflationary period | -| InfrastructureParams | InfrastructureParams | [{see below}] | object containing infrastructure partner payout params | - -`InfrastructureParams` has the following parameters - -| Key | Type | Example | Description | -| --------------------- | --------------------- | ------------- | ----------------------------------------------------------- | -| InfrastructurePeriods | array (Period) | [{see below}] | array of params for each inflationary period | -| CoreRewards | array (CoreReward) | [{see below}] | array of params for reward weights for core infra providers | -| PartnerRewards | array (PartnerReward) | [{see below}] | array of params for infrastructure partner reward schedules | - -Each `Period` has the following parameters - -| Key | Type | Example | Description | -| --------- | --------- | ---------------------- | --------------------------------------- | -| Start | time.Time | "2020-03-01T15:20:00Z" | the time when the period will start | -| End | time.Time | "2020-06-01T15:20:00Z" | the time when the period will end | -| Inflation | sdk.Dec | "1.000000003022265980" | the per-second inflation for the period | - -Each `CoreReward` has the following properties - -| Key | Type | Example | Description | -| ------- | -------------- | --------------------------------------------- | -------------------------------------------------------- | -| Address | sdk.AccAddress | "kava1x07eng0q9027j7wayap8nvqegpf625uu0w90tq" | address of core infrastructure provider | -| Weight | sdk.Dec | "0.912345678907654321" | % of remaining minted rewards allocated to this provider | - -Each `PartnerReward` has the following properties - -| Key | Type | Example | Description | -| ---------------- | -------------- | --------------------------------------------- | ---------------------------------- | -| Address | sdk.AccAddress | "kava1x0cztstumgcfrw69s5nd5qtu9vdcg7alqtyhgr" | address of infrastructure partner | -| RewardsPerSecond | object (coin) | {"denom": "ukava", "amount": "1285" } | per second reward for this partner | diff --git a/x/kavadist/spec/06_begin_block.md b/x/kavadist/spec/06_begin_block.md deleted file mode 100644 index 783116cd..00000000 --- a/x/kavadist/spec/06_begin_block.md +++ /dev/null @@ -1,30 +0,0 @@ - - -# Begin Block - -At the start of each block, the inflationary coins for the ongoing period, if any, are minted. The logic is as follows: - -```go - func BeginBlocker(ctx sdk.Context, k Keeper) { - err := k.MintPeriodInflation(ctx) - if err != nil { - panic(err) - } - } -``` - -## Inflationary Coin Minting - -The `MintPeriodInflation` method mints inflationary coins for the two schedules defined in the parameters when `params.Active` is `true`. Coins are minted based off the number of seconds passed since the last block. When `params.Active` is `false`, the method is a no-op. - -Firstly, it mints coins at a per second rate derived from `params.Periods`. The coins are minted into `x/kavadist`'s module account. - -Next, it mints coins for infrastructure partner rewards at a per second rate derived from `params.InfrastructureParams.InfrastructurePeriods`. The coins are minted to the module account but are then immediately distributed to the infrastructure partners. - -## Infrastructure Partner Reward Distribution - -The coins minted for the `InfrastructurePeriods` are distributed as follows: -* A distribution is made to each of the infrastructure partners based on the number of seconds since the last distribution for each of the defined `params.InfrastructureParams.PartnerRewards`. -* The remaining coins are distributed to the core infrastructure providers by the weights defined in `params.InfrastructureParams.CoreRewards`. diff --git a/x/kavadist/spec/README.md b/x/kavadist/spec/README.md deleted file mode 100644 index 63c57d9e..00000000 --- a/x/kavadist/spec/README.md +++ /dev/null @@ -1,20 +0,0 @@ - - -# `kavadist` - - -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** -5. **[Params](05_params.md)** -6. **[BeginBlock](06_begin_block.md)** - -## Abstract - -`x/kavadist` is an implementation of a Cosmos SDK Module that allows for governance controlled minting of coins into a module account. Coins are minted during inflationary periods, for which each period has a governance specified APR and duration. Additionally, coin rewards for governance specified infrastructure partners are minted and distributed. diff --git a/x/kavadist/testutil/suite.go b/x/kavadist/testutil/suite.go deleted file mode 100644 index e5af0c5d..00000000 --- a/x/kavadist/testutil/suite.go +++ /dev/null @@ -1,82 +0,0 @@ -package testutil - -import ( - "fmt" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - - accountkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/kavadist/keeper" - "github.com/0glabs/0g-chain/x/kavadist/types" -) - -// Suite implements a test suite for the kavadist module integration tests -type Suite struct { - suite.Suite - - Keeper keeper.Keeper - BankKeeper bankkeeper.Keeper - AccountKeeper accountkeeper.AccountKeeper - App app.TestApp - Ctx sdk.Context - TestPeriods []types.Period - Addrs []sdk.AccAddress - QueryClient types.QueryClient -} - -// SetupTest instantiates a new app, keepers, and sets suite state -func (suite *Suite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - tApp := app.NewTestApp() - _, addrs := app.GeneratePrivKeyAddressPairs(1) - coins := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000000000000))) - authGS := app.NewFundedGenStateWithSameCoins(tApp.AppCodec(), coins, addrs) - - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - testPeriods := []types.Period{ - { - Start: time.Date(2020, time.March, 1, 1, 0, 0, 0, time.UTC), - End: time.Date(2021, time.March, 1, 1, 0, 0, 0, time.UTC), - Inflation: sdk.MustNewDecFromStr("1.000000003022265980"), - }, - } - params := types.NewParams(true, testPeriods, types.DefaultInfraParams) - moduleGs := types.ModuleCdc.MustMarshalJSON(types.NewGenesisState(params, types.DefaultPreviousBlockTime)) - gs := app.GenesisState{types.ModuleName: moduleGs} - suite.App = tApp.InitializeFromGenesisStates(authGS, gs) - suite.Ctx = ctx - suite.Addrs = addrs - suite.Keeper = tApp.GetKavadistKeeper() - suite.BankKeeper = tApp.GetBankKeeper() - suite.AccountKeeper = tApp.GetAccountKeeper() - suite.TestPeriods = testPeriods - - // Set query client - queryHelper := tApp.NewQueryServerTestHelper(ctx) - types.RegisterQueryServer(queryHelper, keeper.NewQueryServerImpl(suite.Keeper)) - suite.QueryClient = types.NewQueryClient(queryHelper) -} - -// CreateAccount creates a new account with the provided balance -func (suite *Suite) CreateAccount(initialBalance sdk.Coins) authtypes.AccountI { - _, addrs := app.GeneratePrivKeyAddressPairs(1) - fmt.Println(addrs[0].String()) - acc := suite.AccountKeeper.NewAccountWithAddress(suite.Ctx, addrs[0]) - suite.AccountKeeper.SetAccount(suite.Ctx, acc) - suite.Require().NoError(suite.App.FundAccount(suite.Ctx, addrs[0], initialBalance)) - suite.AccountKeeper.SetAccount(suite.Ctx, acc) - return acc -} diff --git a/x/kavadist/types/codec.go b/x/kavadist/types/codec.go deleted file mode 100644 index 10685c24..00000000 --- a/x/kavadist/types/codec.go +++ /dev/null @@ -1,37 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - cdctypes "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -// RegisterLegacyAminoCodec registers the necessary kavadist interfaces and concrete types -// on the provided LegacyAmino codec. These types are used for Amino JSON serialization. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&CommunityPoolMultiSpendProposal{}, "kava/CommunityPoolMultiSpendProposal", nil) -} - -func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { - registry.RegisterImplementations( - (*govv1beta1.Content)(nil), - &CommunityPoolMultiSpendProposal{}, - ) -} - -var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - amino.Seal() - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/kavadist/types/errors.go b/x/kavadist/types/errors.go deleted file mode 100644 index b0ab3910..00000000 --- a/x/kavadist/types/errors.go +++ /dev/null @@ -1,9 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -// x/kavadist errors -var ( - ErrInvalidProposalAmount = errorsmod.Register(ModuleName, 2, "invalid community pool multi-spend proposal amount") - ErrEmptyProposalRecipient = errorsmod.Register(ModuleName, 3, "invalid community pool multi-spend proposal recipient") -) diff --git a/x/kavadist/types/events.go b/x/kavadist/types/events.go deleted file mode 100644 index 3391bd73..00000000 --- a/x/kavadist/types/events.go +++ /dev/null @@ -1,8 +0,0 @@ -package types - -const ( - EventTypeKavaDist = ModuleName - AttributeKeyInflation = "kava_dist_inflation" - AttributeKeyStatus = "kava_dist_status" - AttributeValueInactive = "inactive" -) diff --git a/x/kavadist/types/expected_keepers.go b/x/kavadist/types/expected_keepers.go deleted file mode 100644 index e78d3d9f..00000000 --- a/x/kavadist/types/expected_keepers.go +++ /dev/null @@ -1,26 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - authTypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// DistKeeper defines the expected distribution keeper interface -type DistKeeper interface { - DistributeFromFeePool(ctx sdk.Context, amount sdk.Coins, receiveAddr sdk.AccAddress) error -} - -// AccountKeeper defines the expected account keeper interface -type AccountKeeper interface { - GetModuleAccount(ctx sdk.Context, moduleName string) authTypes.ModuleAccountI - SetModuleAccount(ctx sdk.Context, macc authTypes.ModuleAccountI) - NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) authTypes.AccountI -} - -// BankKeeper defines the expected bank keeper interface -type BankKeeper interface { - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - MintCoins(ctx sdk.Context, moduleName string, amounts sdk.Coins) error - GetSupply(ctx sdk.Context, denom string) sdk.Coin - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error -} diff --git a/x/kavadist/types/genesis.go b/x/kavadist/types/genesis.go deleted file mode 100644 index 1f702133..00000000 --- a/x/kavadist/types/genesis.go +++ /dev/null @@ -1,34 +0,0 @@ -package types - -import ( - "fmt" - "time" -) - -// NewGenesisState returns a new genesis state -func NewGenesisState(params Params, previousBlockTime time.Time) *GenesisState { - return &GenesisState{ - Params: params, - PreviousBlockTime: previousBlockTime, - } -} - -// DefaultGenesisState returns a default genesis state -func DefaultGenesisState() *GenesisState { - return &GenesisState{ - Params: DefaultParams(), - PreviousBlockTime: DefaultPreviousBlockTime, - } -} - -// Validate performs basic validation of genesis data returning an -// error for any failed validation criteria. -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - if gs.PreviousBlockTime.Equal(time.Time{}) { - return fmt.Errorf("previous block time not set") - } - return nil -} diff --git a/x/kavadist/types/genesis.pb.go b/x/kavadist/types/genesis.pb.go deleted file mode 100644 index f13d51d6..00000000 --- a/x/kavadist/types/genesis.pb.go +++ /dev/null @@ -1,383 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/kavadist/v1beta1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// GenesisState defines the kavadist module's genesis state. -type GenesisState struct { - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - PreviousBlockTime time.Time `protobuf:"bytes,2,opt,name=previous_block_time,json=previousBlockTime,proto3,stdtime" json:"previous_block_time"` -} - -func (m *GenesisState) Reset() { *m = GenesisState{} } -func (m *GenesisState) String() string { return proto.CompactTextString(m) } -func (*GenesisState) ProtoMessage() {} -func (*GenesisState) Descriptor() ([]byte, []int) { - return fileDescriptor_77f4885f7744ff13, []int{0} -} -func (m *GenesisState) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisState) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisState.Merge(m, src) -} -func (m *GenesisState) XXX_Size() int { - return m.Size() -} -func (m *GenesisState) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisState.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisState proto.InternalMessageInfo - -func (m *GenesisState) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -func (m *GenesisState) GetPreviousBlockTime() time.Time { - if m != nil { - return m.PreviousBlockTime - } - return time.Time{} -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "kava.kavadist.v1beta1.GenesisState") -} - -func init() { - proto.RegisterFile("kava/kavadist/v1beta1/genesis.proto", fileDescriptor_77f4885f7744ff13) -} - -var fileDescriptor_77f4885f7744ff13 = []byte{ - // 284 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x8f, 0xc1, 0x4a, 0xc3, 0x30, - 0x18, 0xc7, 0x1b, 0x91, 0x21, 0xd5, 0x8b, 0x55, 0x61, 0x14, 0x4c, 0x65, 0x5e, 0x04, 0x31, 0xd9, - 0xf4, 0xe8, 0xad, 0x20, 0x5e, 0x65, 0xee, 0xe4, 0x65, 0x24, 0x35, 0x66, 0x61, 0xed, 0x52, 0x9a, - 0xaf, 0x45, 0xdf, 0x62, 0xaf, 0xe0, 0xdb, 0xec, 0xb8, 0xa3, 0x27, 0x95, 0xf6, 0x45, 0x24, 0x69, - 0x8b, 0x97, 0x5d, 0x42, 0x42, 0x7e, 0xdf, 0xff, 0xff, 0xfb, 0xfc, 0xcb, 0x25, 0xab, 0x18, 0xb5, - 0xc7, 0xab, 0x32, 0x40, 0xab, 0x09, 0x17, 0xc0, 0x26, 0x54, 0x8a, 0x95, 0x30, 0xca, 0x90, 0xbc, - 0xd0, 0xa0, 0x83, 0x33, 0xfb, 0x4f, 0x7a, 0x88, 0x74, 0x50, 0x78, 0x2a, 0xb5, 0xd4, 0x8e, 0xa0, - 0xf6, 0xd6, 0xc2, 0x61, 0x24, 0xb5, 0x96, 0xa9, 0xa0, 0xee, 0xc5, 0xcb, 0x37, 0x0a, 0x2a, 0x13, - 0x06, 0x58, 0x96, 0x77, 0xc0, 0x68, 0x77, 0x65, 0xce, 0x0a, 0x96, 0x75, 0x8d, 0xa3, 0x4f, 0xe4, - 0x1f, 0x3d, 0xb6, 0x0e, 0xcf, 0xc0, 0x40, 0x04, 0xf7, 0xfe, 0xa0, 0x05, 0x86, 0xe8, 0x02, 0x5d, - 0x1d, 0xde, 0x9e, 0x93, 0x9d, 0x4e, 0xe4, 0xc9, 0x41, 0xf1, 0xfe, 0xe6, 0x3b, 0xf2, 0xa6, 0xdd, - 0x48, 0x30, 0xf3, 0x4f, 0xf2, 0x42, 0x54, 0x4a, 0x97, 0x66, 0xce, 0x53, 0x9d, 0x2c, 0xe7, 0xd6, - 0x69, 0xb8, 0xe7, 0x92, 0x42, 0xd2, 0x0a, 0x93, 0x5e, 0x98, 0xcc, 0x7a, 0xe1, 0xf8, 0xc0, 0xc6, - 0xac, 0x7f, 0x22, 0x34, 0x3d, 0xee, 0x03, 0x62, 0x3b, 0x6f, 0x89, 0xf8, 0x61, 0x53, 0x63, 0xb4, - 0xad, 0x31, 0xfa, 0xad, 0x31, 0x5a, 0x37, 0xd8, 0xdb, 0x36, 0xd8, 0xfb, 0x6a, 0xb0, 0xf7, 0x72, - 0x2d, 0x15, 0x2c, 0x4a, 0x4e, 0x12, 0x9d, 0xd1, 0xb1, 0x4c, 0x19, 0x37, 0x74, 0x2c, 0x6f, 0x92, - 0x05, 0x53, 0x2b, 0xfa, 0xfe, 0xbf, 0x39, 0x7c, 0xe4, 0xc2, 0xf0, 0x81, 0xeb, 0xbd, 0xfb, 0x0b, - 0x00, 0x00, 0xff, 0xff, 0x69, 0x8f, 0xb1, 0x6d, 0x8a, 0x01, 0x00, 0x00, -} - -func (m *GenesisState) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - n1, err1 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.PreviousBlockTime, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.PreviousBlockTime):]) - if err1 != nil { - return 0, err1 - } - i -= n1 - i = encodeVarintGenesis(dAtA, i, uint64(n1)) - i-- - dAtA[i] = 0x12 - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *GenesisState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.PreviousBlockTime) - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *GenesisState) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PreviousBlockTime", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.PreviousBlockTime, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/kavadist/types/keys.go b/x/kavadist/types/keys.go deleted file mode 100644 index a7b91014..00000000 --- a/x/kavadist/types/keys.go +++ /dev/null @@ -1,26 +0,0 @@ -package types - -const ( - // ModuleName name that will be used throughout the module - ModuleName = "kavadist" - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey Top level router key - RouterKey = ModuleName - - // DefaultParamspace default name for parameter store - DefaultParamspace = ModuleName - - // KavaDistMacc module account for kavadist - KavaDistMacc = ModuleName - - // Treasury - FundModuleAccount = "kava-fund" -) - -var ( - CurrentDistPeriodKey = []byte{0x00} - PreviousBlockTimeKey = []byte{0x01} -) diff --git a/x/kavadist/types/params.go b/x/kavadist/types/params.go deleted file mode 100644 index 84057fd4..00000000 --- a/x/kavadist/types/params.go +++ /dev/null @@ -1,191 +0,0 @@ -package types - -import ( - "fmt" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - - tmtime "github.com/cometbft/cometbft/types/time" - // cdptypes "github.com/0glabs/0g-chain/x/cdp/types" -) - -// Parameter keys and default values -var ( - KeyActive = []byte("Active") - KeyPeriods = []byte("Periods") - KeyInfra = []byte("InfrastructureParams") - DefaultActive = false - DefaultPeriods = []Period{} - DefaultInfraParams = InfrastructureParams{} - DefaultPreviousBlockTime = tmtime.Canonical(time.Unix(1, 0)) - GovDenom = "ukava" // TODO: replace with cdptypes.DefaultGovDenom -) - -func NewParams(active bool, periods []Period, infraParams InfrastructureParams) Params { - return Params{ - Active: active, - Periods: periods, - InfrastructureParams: infraParams, - } -} - -func DefaultParams() Params { - return NewParams(DefaultActive, DefaultPeriods, DefaultInfraParams) -} - -func (p Params) String() string { - periods := "Periods\n" - for _, pr := range p.Periods { - periods += fmt.Sprintf("%s\n", pr) - } - return fmt.Sprintf(`Params: - Active: %t - Periods %s`, p.Active, periods) -} - -func (p Params) Equal(other Params) bool { - if p.Active != other.Active { - return false - } - - if len(p.Periods) != len(other.Periods) { - return false - } - - for i, period := range p.Periods { - if !period.Equal(other.Periods[i]) { - return false - } - } - - return true -} - -// ParamKeyTable Key declaration for parameters -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements the ParamSet interface and returns all the key/value pairs -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyActive, &p.Active, validateActiveParam), - paramtypes.NewParamSetPair(KeyPeriods, &p.Periods, validatePeriodsParams), - paramtypes.NewParamSetPair(KeyInfra, &p.InfrastructureParams, validateInfraParams), - } -} - -// Validate checks that the parameters have valid values. -func (p Params) Validate() error { - if err := validateActiveParam(p.Active); err != nil { - return err - } - - return validatePeriodsParams(p.Periods) -} - -// NewPeriod returns a new instance of Period -func NewPeriod(start time.Time, end time.Time, inflation sdk.Dec) Period { - return Period{ - Start: start, - End: end, - Inflation: inflation, - } -} - -type Periods []Period - -// String implements fmt.Stringer -func (pr Period) String() string { - return fmt.Sprintf(`Period: - Start: %s - End: %s - Inflation: %s`, pr.Start, pr.End, pr.Inflation) -} - -func NewInfraParams(p Periods, pr PartnerRewards, cr CoreRewards) InfrastructureParams { - return InfrastructureParams{ - InfrastructurePeriods: p, - PartnerRewards: pr, - CoreRewards: cr, - } -} - -func NewPartnerReward(addr sdk.AccAddress, rps sdk.Coin) PartnerReward { - return PartnerReward{ - Address: addr, - RewardsPerSecond: rps, - } -} - -func NewCoreReward(addr sdk.AccAddress, w sdk.Dec) CoreReward { - return CoreReward{ - Address: addr, - Weight: w, - } -} - -func validateActiveParam(i interface{}) error { - _, ok := i.(bool) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return nil -} - -func validatePeriodsParams(i interface{}) error { - periods, ok := i.([]Period) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - prevEnd := tmtime.Canonical(time.Unix(0, 0)) - for _, pr := range periods { - if pr.End.Before(pr.Start) { - return fmt.Errorf("end time for period is before start time: %s", pr) - } - - if pr.Start.Before(prevEnd) { - return fmt.Errorf("periods must be in chronological order: %s", periods) - } - prevEnd = pr.End - - if pr.Start.Unix() <= 0 || pr.End.Unix() <= 0 { - return fmt.Errorf("start or end time cannot be zero: %s", pr) - } - - // TODO: validate period Inflation? - } - - return nil -} - -func validateInfraParams(i interface{}) error { - infraParams, ok := i.(InfrastructureParams) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - for _, pr := range infraParams.InfrastructurePeriods { - if pr.End.Before(pr.Start) { - return fmt.Errorf("end time for period is before start time: %s", pr) - } - prevEnd := tmtime.Canonical(time.Unix(0, 0)) - if pr.Start.Before(prevEnd) { - return fmt.Errorf("periods must be in chronological order: %s", infraParams.InfrastructurePeriods) - } - prevEnd = pr.End - - if pr.Start.Unix() <= 0 || pr.End.Unix() <= 0 { - return fmt.Errorf("start or end time cannot be zero: %s", pr) - } - - // TODO: validate period Inflation? - } - return nil -} - -type CoreRewards []CoreReward -type PartnerRewards []PartnerReward diff --git a/x/kavadist/types/params.pb.go b/x/kavadist/types/params.pb.go deleted file mode 100644 index 594f9b30..00000000 --- a/x/kavadist/types/params.pb.go +++ /dev/null @@ -1,1436 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/kavadist/v1beta1/params.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// Params governance parameters for kavadist module -type Params struct { - Active bool `protobuf:"varint,1,opt,name=active,proto3" json:"active,omitempty"` - Periods []Period `protobuf:"bytes,3,rep,name=periods,proto3" json:"periods"` - InfrastructureParams InfrastructureParams `protobuf:"bytes,4,opt,name=infrastructure_params,json=infrastructureParams,proto3" json:"infrastructure_params"` -} - -func (m *Params) Reset() { *m = Params{} } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_2c7a7a4b0c884a4e, []int{0} -} -func (m *Params) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Params.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Params) XXX_Merge(src proto.Message) { - xxx_messageInfo_Params.Merge(m, src) -} -func (m *Params) XXX_Size() int { - return m.Size() -} -func (m *Params) XXX_DiscardUnknown() { - xxx_messageInfo_Params.DiscardUnknown(m) -} - -var xxx_messageInfo_Params proto.InternalMessageInfo - -// InfrastructureParams define the parameters for infrastructure rewards. -type InfrastructureParams struct { - InfrastructurePeriods Periods `protobuf:"bytes,1,rep,name=infrastructure_periods,json=infrastructurePeriods,proto3,castrepeated=Periods" json:"infrastructure_periods"` - CoreRewards CoreRewards `protobuf:"bytes,2,rep,name=core_rewards,json=coreRewards,proto3,castrepeated=CoreRewards" json:"core_rewards"` - PartnerRewards PartnerRewards `protobuf:"bytes,3,rep,name=partner_rewards,json=partnerRewards,proto3,castrepeated=PartnerRewards" json:"partner_rewards"` -} - -func (m *InfrastructureParams) Reset() { *m = InfrastructureParams{} } -func (m *InfrastructureParams) String() string { return proto.CompactTextString(m) } -func (*InfrastructureParams) ProtoMessage() {} -func (*InfrastructureParams) Descriptor() ([]byte, []int) { - return fileDescriptor_2c7a7a4b0c884a4e, []int{1} -} -func (m *InfrastructureParams) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *InfrastructureParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_InfrastructureParams.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *InfrastructureParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_InfrastructureParams.Merge(m, src) -} -func (m *InfrastructureParams) XXX_Size() int { - return m.Size() -} -func (m *InfrastructureParams) XXX_DiscardUnknown() { - xxx_messageInfo_InfrastructureParams.DiscardUnknown(m) -} - -var xxx_messageInfo_InfrastructureParams proto.InternalMessageInfo - -// CoreReward defines the reward weights for core infrastructure providers. -type CoreReward struct { - Address github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=address,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"address,omitempty"` - Weight github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=weight,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"weight"` -} - -func (m *CoreReward) Reset() { *m = CoreReward{} } -func (m *CoreReward) String() string { return proto.CompactTextString(m) } -func (*CoreReward) ProtoMessage() {} -func (*CoreReward) Descriptor() ([]byte, []int) { - return fileDescriptor_2c7a7a4b0c884a4e, []int{2} -} -func (m *CoreReward) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CoreReward) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CoreReward.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CoreReward) XXX_Merge(src proto.Message) { - xxx_messageInfo_CoreReward.Merge(m, src) -} -func (m *CoreReward) XXX_Size() int { - return m.Size() -} -func (m *CoreReward) XXX_DiscardUnknown() { - xxx_messageInfo_CoreReward.DiscardUnknown(m) -} - -var xxx_messageInfo_CoreReward proto.InternalMessageInfo - -// PartnerRewards defines the reward schedule for partner infrastructure providers. -type PartnerReward struct { - Address github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=address,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"address,omitempty"` - RewardsPerSecond types.Coin `protobuf:"bytes,2,opt,name=rewards_per_second,json=rewardsPerSecond,proto3" json:"rewards_per_second"` -} - -func (m *PartnerReward) Reset() { *m = PartnerReward{} } -func (m *PartnerReward) String() string { return proto.CompactTextString(m) } -func (*PartnerReward) ProtoMessage() {} -func (*PartnerReward) Descriptor() ([]byte, []int) { - return fileDescriptor_2c7a7a4b0c884a4e, []int{3} -} -func (m *PartnerReward) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *PartnerReward) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_PartnerReward.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *PartnerReward) XXX_Merge(src proto.Message) { - xxx_messageInfo_PartnerReward.Merge(m, src) -} -func (m *PartnerReward) XXX_Size() int { - return m.Size() -} -func (m *PartnerReward) XXX_DiscardUnknown() { - xxx_messageInfo_PartnerReward.DiscardUnknown(m) -} - -var xxx_messageInfo_PartnerReward proto.InternalMessageInfo - -// Period stores the specified start and end dates, and the inflation, expressed as a decimal -// representing the yearly APR of KAVA tokens that will be minted during that period -type Period struct { - // example "2020-03-01T15:20:00Z" - Start time.Time `protobuf:"bytes,1,opt,name=start,proto3,stdtime" json:"start"` - // example "2020-06-01T15:20:00Z" - End time.Time `protobuf:"bytes,2,opt,name=end,proto3,stdtime" json:"end"` - // example "1.000000003022265980" - 10% inflation - Inflation github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=inflation,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"inflation"` -} - -func (m *Period) Reset() { *m = Period{} } -func (*Period) ProtoMessage() {} -func (*Period) Descriptor() ([]byte, []int) { - return fileDescriptor_2c7a7a4b0c884a4e, []int{4} -} -func (m *Period) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Period) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Period.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Period) XXX_Merge(src proto.Message) { - xxx_messageInfo_Period.Merge(m, src) -} -func (m *Period) XXX_Size() int { - return m.Size() -} -func (m *Period) XXX_DiscardUnknown() { - xxx_messageInfo_Period.DiscardUnknown(m) -} - -var xxx_messageInfo_Period proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Params)(nil), "kava.kavadist.v1beta1.Params") - proto.RegisterType((*InfrastructureParams)(nil), "kava.kavadist.v1beta1.InfrastructureParams") - proto.RegisterType((*CoreReward)(nil), "kava.kavadist.v1beta1.CoreReward") - proto.RegisterType((*PartnerReward)(nil), "kava.kavadist.v1beta1.PartnerReward") - proto.RegisterType((*Period)(nil), "kava.kavadist.v1beta1.Period") -} - -func init() { - proto.RegisterFile("kava/kavadist/v1beta1/params.proto", fileDescriptor_2c7a7a4b0c884a4e) -} - -var fileDescriptor_2c7a7a4b0c884a4e = []byte{ - // 652 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x54, 0x3f, 0x4f, 0x1b, 0x3f, - 0x18, 0x8e, 0x49, 0x7e, 0x01, 0x1c, 0x7e, 0x50, 0x99, 0x3f, 0x0a, 0x48, 0xbd, 0x4b, 0xa3, 0xaa, - 0x8a, 0x84, 0x72, 0x07, 0xa9, 0xd4, 0x01, 0xb5, 0x03, 0x29, 0x43, 0x2b, 0x15, 0x09, 0x5d, 0x59, - 0xda, 0x25, 0xf2, 0xf9, 0x9c, 0xc3, 0x82, 0x9c, 0x4f, 0xb6, 0x03, 0xe5, 0x5b, 0x30, 0x76, 0x64, - 0xee, 0xcc, 0x57, 0xa8, 0x9a, 0xa1, 0x03, 0x62, 0x42, 0x1d, 0xa0, 0xc0, 0xd2, 0xcf, 0xd0, 0xa9, - 0x3a, 0xdb, 0x21, 0x04, 0x81, 0x44, 0x97, 0x2e, 0x49, 0xde, 0xd7, 0xef, 0xf3, 0xbc, 0xcf, 0x63, - 0xbf, 0x6f, 0x60, 0x75, 0x1b, 0xef, 0x62, 0x3f, 0xfb, 0x88, 0x98, 0x54, 0xfe, 0xee, 0x72, 0x48, - 0x15, 0x5e, 0xf6, 0x53, 0x2c, 0x70, 0x47, 0x7a, 0xa9, 0xe0, 0x8a, 0xa3, 0xd9, 0xec, 0xd8, 0xeb, - 0xd7, 0x78, 0xb6, 0x66, 0xc1, 0x21, 0x5c, 0x76, 0xb8, 0xf4, 0x43, 0x2c, 0xe9, 0x35, 0x90, 0x70, - 0x96, 0x18, 0xd8, 0xc2, 0xbc, 0x39, 0x6f, 0xe9, 0xc8, 0x37, 0x81, 0x3d, 0x9a, 0x89, 0x79, 0xcc, - 0x4d, 0x3e, 0xfb, 0x65, 0xb3, 0x6e, 0xcc, 0x79, 0xbc, 0x43, 0x7d, 0x1d, 0x85, 0xdd, 0xb6, 0xaf, - 0x58, 0x87, 0x4a, 0x85, 0x3b, 0xa9, 0x29, 0xa8, 0x7e, 0x03, 0xb0, 0xb8, 0xa1, 0x95, 0xa1, 0x39, - 0x58, 0xc4, 0x44, 0xb1, 0x5d, 0x5a, 0x06, 0x15, 0x50, 0x1b, 0x0b, 0x6c, 0x84, 0x5e, 0xc1, 0xd1, - 0x94, 0x0a, 0xc6, 0x23, 0x59, 0xce, 0x57, 0xf2, 0xb5, 0x52, 0xe3, 0xb1, 0x77, 0xa7, 0x7a, 0x6f, - 0x43, 0x57, 0x35, 0x0b, 0xbd, 0x33, 0x37, 0x17, 0xf4, 0x31, 0xa8, 0x0d, 0x67, 0x59, 0xd2, 0x16, - 0x58, 0x2a, 0xd1, 0x25, 0xaa, 0x2b, 0x68, 0xcb, 0xdc, 0x44, 0xb9, 0x50, 0x01, 0xb5, 0x52, 0x63, - 0xf1, 0x1e, 0xb2, 0xb7, 0x43, 0x18, 0x23, 0xd1, 0x52, 0xcf, 0xb0, 0x3b, 0xce, 0xaa, 0x5f, 0x47, - 0xe0, 0xcc, 0x5d, 0x20, 0x44, 0xe1, 0xdc, 0x6d, 0x01, 0xd6, 0x0e, 0x78, 0x88, 0x9d, 0xa9, 0xac, - 0xe7, 0x97, 0x73, 0x77, 0xd4, 0xc4, 0x32, 0xb8, 0x65, 0xc7, 0xa6, 0xd1, 0x07, 0x38, 0x41, 0xb8, - 0xa0, 0x2d, 0x41, 0xf7, 0xb0, 0x88, 0x64, 0x79, 0x44, 0x93, 0x3f, 0xb9, 0x87, 0xfc, 0x35, 0x17, - 0x34, 0xd0, 0x95, 0xcd, 0x69, 0xdb, 0xa0, 0x34, 0xc8, 0xc9, 0xa0, 0x44, 0x06, 0x01, 0xa2, 0x70, - 0x2a, 0xc5, 0x42, 0x25, 0x54, 0x5c, 0xb3, 0x9b, 0x97, 0x78, 0x7a, 0x9f, 0x74, 0x53, 0x6d, 0x1b, - 0xcc, 0xd9, 0x06, 0x93, 0x43, 0x69, 0x19, 0x4c, 0xa6, 0x43, 0xf1, 0x4a, 0xe1, 0xf3, 0xa1, 0x0b, - 0xaa, 0xdf, 0x01, 0x84, 0x03, 0x25, 0x28, 0x84, 0xa3, 0x38, 0x8a, 0x04, 0x95, 0x52, 0x8f, 0xc5, - 0x44, 0xf3, 0xcd, 0xef, 0x33, 0xb7, 0x1e, 0x33, 0xb5, 0xd5, 0x0d, 0x3d, 0xc2, 0x3b, 0x76, 0x0a, - 0xed, 0x57, 0x5d, 0x46, 0xdb, 0xbe, 0xda, 0x4f, 0xa9, 0xf4, 0x56, 0x09, 0x59, 0x35, 0xc0, 0x93, - 0xa3, 0xfa, 0xb4, 0x9d, 0x55, 0x9b, 0x69, 0xee, 0x2b, 0x2a, 0x83, 0x3e, 0x31, 0xda, 0x84, 0xc5, - 0x3d, 0xca, 0xe2, 0x2d, 0x55, 0x1e, 0xa9, 0x80, 0xda, 0x78, 0xf3, 0x65, 0x26, 0xf8, 0xc7, 0x99, - 0xfb, 0xec, 0x01, 0x6d, 0xd6, 0x28, 0x39, 0x39, 0xaa, 0x43, 0xcb, 0xbf, 0x46, 0x49, 0x60, 0xb9, - 0xac, 0x9d, 0x1e, 0x80, 0xff, 0x0f, 0xf9, 0xfe, 0x27, 0x8e, 0xd6, 0x21, 0xb2, 0x2f, 0x95, 0x0d, - 0x5b, 0x4b, 0x52, 0xc2, 0x93, 0x48, 0xbb, 0x2b, 0x35, 0xe6, 0x3d, 0x0b, 0xcd, 0xb6, 0xfc, 0xc6, - 0x40, 0xb0, 0xc4, 0xce, 0xf7, 0x23, 0x0b, 0xdd, 0xa0, 0xe2, 0xbd, 0x06, 0x5a, 0x2b, 0xc7, 0xd9, - 0xae, 0xea, 0x69, 0x43, 0x2b, 0xf0, 0x3f, 0xa9, 0xb0, 0x50, 0xda, 0x41, 0xa9, 0xb1, 0xe0, 0x99, - 0x3d, 0xf7, 0xfa, 0x7b, 0xee, 0x6d, 0xf6, 0xf7, 0xbc, 0x39, 0x96, 0x71, 0x1e, 0x9c, 0xbb, 0x20, - 0x30, 0x10, 0xf4, 0x02, 0xe6, 0xe9, 0xb5, 0x98, 0x87, 0x21, 0x33, 0x00, 0x7a, 0x07, 0xc7, 0x59, - 0xd2, 0xde, 0xc1, 0x8a, 0xf1, 0xa4, 0x9c, 0xd7, 0x37, 0xe7, 0xfd, 0xdd, 0x43, 0x05, 0x03, 0x82, - 0x95, 0xc2, 0xaf, 0x43, 0x17, 0x34, 0xd7, 0x7b, 0x17, 0x4e, 0xee, 0xf4, 0xc2, 0xc9, 0xf5, 0x2e, - 0x1d, 0x70, 0x7c, 0xe9, 0x80, 0x9f, 0x97, 0x0e, 0x38, 0xb8, 0x72, 0x72, 0xc7, 0x57, 0x4e, 0xee, - 0xf4, 0xca, 0xc9, 0x7d, 0x5c, 0xbc, 0x41, 0xbd, 0x14, 0xef, 0xe0, 0x50, 0xfa, 0x4b, 0x71, 0x9d, - 0x6c, 0x61, 0x96, 0xf8, 0x9f, 0x06, 0xff, 0xb2, 0xba, 0x47, 0x58, 0xd4, 0x2e, 0x9e, 0xff, 0x09, - 0x00, 0x00, 0xff, 0xff, 0x18, 0xb9, 0xf4, 0x6c, 0x83, 0x05, 0x00, 0x00, -} - -func (this *Period) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*Period) - if !ok { - that2, ok := that.(Period) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if !this.Start.Equal(that1.Start) { - return false - } - if !this.End.Equal(that1.End) { - return false - } - if !this.Inflation.Equal(that1.Inflation) { - return false - } - return true -} -func (m *Params) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Params) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.InfrastructureParams.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - if len(m.Periods) > 0 { - for iNdEx := len(m.Periods) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Periods[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if m.Active { - i-- - if m.Active { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *InfrastructureParams) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *InfrastructureParams) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *InfrastructureParams) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.PartnerRewards) > 0 { - for iNdEx := len(m.PartnerRewards) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.PartnerRewards[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.CoreRewards) > 0 { - for iNdEx := len(m.CoreRewards) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.CoreRewards[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.InfrastructurePeriods) > 0 { - for iNdEx := len(m.InfrastructurePeriods) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.InfrastructurePeriods[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *CoreReward) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CoreReward) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CoreReward) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Weight.Size() - i -= size - if _, err := m.Weight.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintParams(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *PartnerReward) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PartnerReward) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PartnerReward) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.RewardsPerSecond.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintParams(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *Period) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Period) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Period) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Inflation.Size() - i -= size - if _, err := m.Inflation.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - n3, err3 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.End, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.End):]) - if err3 != nil { - return 0, err3 - } - i -= n3 - i = encodeVarintParams(dAtA, i, uint64(n3)) - i-- - dAtA[i] = 0x12 - n4, err4 := github_com_cosmos_gogoproto_types.StdTimeMarshalTo(m.Start, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Start):]) - if err4 != nil { - return 0, err4 - } - i -= n4 - i = encodeVarintParams(dAtA, i, uint64(n4)) - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintParams(dAtA []byte, offset int, v uint64) int { - offset -= sovParams(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Active { - n += 2 - } - if len(m.Periods) > 0 { - for _, e := range m.Periods { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - l = m.InfrastructureParams.Size() - n += 1 + l + sovParams(uint64(l)) - return n -} - -func (m *InfrastructureParams) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.InfrastructurePeriods) > 0 { - for _, e := range m.InfrastructurePeriods { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - if len(m.CoreRewards) > 0 { - for _, e := range m.CoreRewards { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - if len(m.PartnerRewards) > 0 { - for _, e := range m.PartnerRewards { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - return n -} - -func (m *CoreReward) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovParams(uint64(l)) - } - l = m.Weight.Size() - n += 1 + l + sovParams(uint64(l)) - return n -} - -func (m *PartnerReward) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovParams(uint64(l)) - } - l = m.RewardsPerSecond.Size() - n += 1 + l + sovParams(uint64(l)) - return n -} - -func (m *Period) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.Start) - n += 1 + l + sovParams(uint64(l)) - l = github_com_cosmos_gogoproto_types.SizeOfStdTime(m.End) - n += 1 + l + sovParams(uint64(l)) - l = m.Inflation.Size() - n += 1 + l + sovParams(uint64(l)) - return n -} - -func sovParams(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozParams(x uint64) (n int) { - return sovParams(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Params) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Params: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Active", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Active = bool(v != 0) - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Periods", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Periods = append(m.Periods, Period{}) - if err := m.Periods[len(m.Periods)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InfrastructureParams", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.InfrastructureParams.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParams(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParams - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *InfrastructureParams) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: InfrastructureParams: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: InfrastructureParams: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InfrastructurePeriods", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.InfrastructurePeriods = append(m.InfrastructurePeriods, Period{}) - if err := m.InfrastructurePeriods[len(m.InfrastructurePeriods)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CoreRewards", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CoreRewards = append(m.CoreRewards, CoreReward{}) - if err := m.CoreRewards[len(m.CoreRewards)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PartnerRewards", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PartnerRewards = append(m.PartnerRewards, PartnerReward{}) - if err := m.PartnerRewards[len(m.PartnerRewards)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParams(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParams - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CoreReward) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CoreReward: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CoreReward: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = append(m.Address[:0], dAtA[iNdEx:postIndex]...) - if m.Address == nil { - m.Address = []byte{} - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Weight", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Weight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParams(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParams - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *PartnerReward) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PartnerReward: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PartnerReward: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = append(m.Address[:0], dAtA[iNdEx:postIndex]...) - if m.Address == nil { - m.Address = []byte{} - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RewardsPerSecond", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.RewardsPerSecond.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParams(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParams - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Period) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Period: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Period: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Start", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.Start, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field End", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdTimeUnmarshal(&m.End, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Inflation", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Inflation.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParams(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParams - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipParams(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParams - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParams - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParams - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthParams - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupParams - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthParams - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthParams = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowParams = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupParams = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/kavadist/types/params_test.go b/x/kavadist/types/params_test.go deleted file mode 100644 index 08542770..00000000 --- a/x/kavadist/types/params_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package types_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/kavadist/types" -) - -type paramTest struct { - params types.Params - expectPass bool -} - -type ParamTestSuite struct { - suite.Suite - - tests []paramTest -} - -func (suite *ParamTestSuite) SetupTest() { - p1 := types.Params{ - Active: true, - Periods: []types.Period{ - { - Start: time.Date(2020, time.March, 1, 1, 0, 0, 0, time.UTC), - End: time.Date(2021, time.March, 1, 1, 0, 0, 0, time.UTC), - Inflation: sdk.MustNewDecFromStr("1.000000003022265980"), - }, - { - Start: time.Date(2021, time.March, 1, 1, 0, 0, 0, time.UTC), - End: time.Date(2022, time.March, 1, 1, 0, 0, 0, time.UTC), - Inflation: sdk.MustNewDecFromStr("1.000000003022265980"), - }, - }, - } - p2 := types.Params{ - Active: true, - Periods: []types.Period{ - { - Start: time.Date(2022, time.March, 1, 1, 0, 0, 0, time.UTC), - End: time.Date(2021, time.March, 1, 1, 0, 0, 0, time.UTC), - Inflation: sdk.MustNewDecFromStr("1.000000003022265980"), - }, - { - Start: time.Date(2023, time.March, 1, 1, 0, 0, 0, time.UTC), - End: time.Date(2024, time.March, 1, 1, 0, 0, 0, time.UTC), - Inflation: sdk.MustNewDecFromStr("1.000000003022265980"), - }, - }, - } - p3 := types.Params{ - Active: true, - Periods: []types.Period{ - { - Start: time.Date(2020, time.March, 1, 1, 0, 0, 0, time.UTC), - End: time.Date(2021, time.March, 1, 1, 0, 0, 0, time.UTC), - Inflation: sdk.MustNewDecFromStr("1.000000003022265980"), - }, - { - Start: time.Date(2020, time.March, 1, 1, 0, 0, 0, time.UTC), - End: time.Date(2022, time.March, 1, 1, 0, 0, 0, time.UTC), - Inflation: sdk.MustNewDecFromStr("1.000000003022265980"), - }, - }, - } - - suite.tests = []paramTest{ - { - params: p1, - expectPass: true, - }, - { - params: p2, - expectPass: false, - }, - { - params: p3, - expectPass: false, - }, - } -} - -func (suite *ParamTestSuite) TestParamValidation() { - for _, t := range suite.tests { - err := t.params.Validate() - if t.expectPass { - suite.Require().NoError(err) - } else { - suite.Require().Error(err) - } - } -} - -func TestParamsTestSuite(t *testing.T) { - suite.Run(t, new(ParamTestSuite)) -} diff --git a/x/kavadist/types/proposal.go b/x/kavadist/types/proposal.go deleted file mode 100644 index 3fa8e06f..00000000 --- a/x/kavadist/types/proposal.go +++ /dev/null @@ -1,106 +0,0 @@ -package types - -import ( - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" - govcodec "github.com/cosmos/cosmos-sdk/x/gov/codec" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -const ( - // ProposalTypeCommunityPoolMultiSpend defines the type for a CommunityPoolMultiSpendProposal - ProposalTypeCommunityPoolMultiSpend = "CommunityPoolMultiSpend" -) - -// Assert CommunityPoolMultiSpendProposal implements govtypes.Content at compile-time -var _ govv1beta1.Content = CommunityPoolMultiSpendProposal{} - -func init() { - govv1beta1.RegisterProposalType(ProposalTypeCommunityPoolMultiSpend) - govcodec.ModuleCdc.Amino.RegisterConcrete(CommunityPoolMultiSpendProposal{}, "kava/CommunityPoolMultiSpendProposal", nil) -} - -// NewCommunityPoolMultiSpendProposal creates a new community pool multi-spend proposal. -func NewCommunityPoolMultiSpendProposal(title, description string, recipientList []MultiSpendRecipient) *CommunityPoolMultiSpendProposal { - return &CommunityPoolMultiSpendProposal{ - Title: title, - Description: description, - RecipientList: recipientList, - } -} - -// GetTitle returns the title of a community pool multi-spend proposal. -func (csp CommunityPoolMultiSpendProposal) GetTitle() string { return csp.Title } - -// GetDescription returns the description of a community pool multi-spend proposal. -func (csp CommunityPoolMultiSpendProposal) GetDescription() string { return csp.Description } - -// GetDescription returns the routing key of a community pool multi-spend proposal. -func (csp CommunityPoolMultiSpendProposal) ProposalRoute() string { return RouterKey } - -// ProposalType returns the type of a community pool multi-spend proposal. -func (csp CommunityPoolMultiSpendProposal) ProposalType() string { - return ProposalTypeCommunityPoolMultiSpend -} - -// ValidateBasic stateless validation of a community pool multi-spend proposal. -func (csp CommunityPoolMultiSpendProposal) ValidateBasic() error { - err := govv1beta1.ValidateAbstract(csp) - if err != nil { - return err - } - for _, msr := range csp.RecipientList { - if err := msr.Validate(); err != nil { - return err - } - } - return nil -} - -// String implements fmt.Stringer -func (csp CommunityPoolMultiSpendProposal) String() string { - receiptList := "" - for _, msr := range csp.RecipientList { - receiptList += msr.String() - } - var b strings.Builder - b.WriteString(fmt.Sprintf(`Community Pool Multi Spend Proposal: - Title: %s - Description: %s - Recipient List: %s -`, csp.Title, csp.Description, receiptList)) - return b.String() -} - -// Validate stateless validation of MultiSpendRecipient -func (msr MultiSpendRecipient) Validate() error { - if !msr.Amount.IsValid() { - return ErrInvalidProposalAmount - } - if msr.Address == "" { - return ErrEmptyProposalRecipient - } - if _, err := sdk.AccAddressFromBech32(msr.Address); err != nil { - return err - } - return nil -} - -// String implements fmt.Stringer -func (msr MultiSpendRecipient) String() string { - return fmt.Sprintf(`Receiver: %s - Amount: %s - `, msr.Address, msr.Amount) -} - -// Gets recipient address in sdk.AccAddress -func (msr MultiSpendRecipient) GetAddress() sdk.AccAddress { - addr, err := sdk.AccAddressFromBech32(msr.Address) - if err != nil { - panic(fmt.Errorf("couldn't convert %q to account address: %v", msr.Address, err)) - } - - return addr -} diff --git a/x/kavadist/types/proposal.pb.go b/x/kavadist/types/proposal.pb.go deleted file mode 100644 index 3a079174..00000000 --- a/x/kavadist/types/proposal.pb.go +++ /dev/null @@ -1,964 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/kavadist/v1beta1/proposal.proto - -package types - -import ( - fmt "fmt" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// CommunityPoolMultiSpendProposal spends from the community pool by sending to one or more -// addresses -type CommunityPoolMultiSpendProposal struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - RecipientList []MultiSpendRecipient `protobuf:"bytes,3,rep,name=recipient_list,json=recipientList,proto3" json:"recipient_list"` -} - -func (m *CommunityPoolMultiSpendProposal) Reset() { *m = CommunityPoolMultiSpendProposal{} } -func (*CommunityPoolMultiSpendProposal) ProtoMessage() {} -func (*CommunityPoolMultiSpendProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_22ee2c0b398254fd, []int{0} -} -func (m *CommunityPoolMultiSpendProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityPoolMultiSpendProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityPoolMultiSpendProposal.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CommunityPoolMultiSpendProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityPoolMultiSpendProposal.Merge(m, src) -} -func (m *CommunityPoolMultiSpendProposal) XXX_Size() int { - return m.Size() -} -func (m *CommunityPoolMultiSpendProposal) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityPoolMultiSpendProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityPoolMultiSpendProposal proto.InternalMessageInfo - -// CommunityPoolMultiSpendProposalJSON defines a CommunityPoolMultiSpendProposal with a deposit -type CommunityPoolMultiSpendProposalJSON struct { - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - RecipientList []MultiSpendRecipient `protobuf:"bytes,3,rep,name=recipient_list,json=recipientList,proto3" json:"recipient_list"` - Deposit github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,4,rep,name=deposit,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"deposit"` -} - -func (m *CommunityPoolMultiSpendProposalJSON) Reset() { *m = CommunityPoolMultiSpendProposalJSON{} } -func (m *CommunityPoolMultiSpendProposalJSON) String() string { return proto.CompactTextString(m) } -func (*CommunityPoolMultiSpendProposalJSON) ProtoMessage() {} -func (*CommunityPoolMultiSpendProposalJSON) Descriptor() ([]byte, []int) { - return fileDescriptor_22ee2c0b398254fd, []int{1} -} -func (m *CommunityPoolMultiSpendProposalJSON) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CommunityPoolMultiSpendProposalJSON) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CommunityPoolMultiSpendProposalJSON.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CommunityPoolMultiSpendProposalJSON) XXX_Merge(src proto.Message) { - xxx_messageInfo_CommunityPoolMultiSpendProposalJSON.Merge(m, src) -} -func (m *CommunityPoolMultiSpendProposalJSON) XXX_Size() int { - return m.Size() -} -func (m *CommunityPoolMultiSpendProposalJSON) XXX_DiscardUnknown() { - xxx_messageInfo_CommunityPoolMultiSpendProposalJSON.DiscardUnknown(m) -} - -var xxx_messageInfo_CommunityPoolMultiSpendProposalJSON proto.InternalMessageInfo - -// MultiSpendRecipient defines a recipient and the amount of coins they are receiving -type MultiSpendRecipient struct { - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *MultiSpendRecipient) Reset() { *m = MultiSpendRecipient{} } -func (*MultiSpendRecipient) ProtoMessage() {} -func (*MultiSpendRecipient) Descriptor() ([]byte, []int) { - return fileDescriptor_22ee2c0b398254fd, []int{2} -} -func (m *MultiSpendRecipient) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MultiSpendRecipient) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MultiSpendRecipient.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MultiSpendRecipient) XXX_Merge(src proto.Message) { - xxx_messageInfo_MultiSpendRecipient.Merge(m, src) -} -func (m *MultiSpendRecipient) XXX_Size() int { - return m.Size() -} -func (m *MultiSpendRecipient) XXX_DiscardUnknown() { - xxx_messageInfo_MultiSpendRecipient.DiscardUnknown(m) -} - -var xxx_messageInfo_MultiSpendRecipient proto.InternalMessageInfo - -func init() { - proto.RegisterType((*CommunityPoolMultiSpendProposal)(nil), "kava.kavadist.v1beta1.CommunityPoolMultiSpendProposal") - proto.RegisterType((*CommunityPoolMultiSpendProposalJSON)(nil), "kava.kavadist.v1beta1.CommunityPoolMultiSpendProposalJSON") - proto.RegisterType((*MultiSpendRecipient)(nil), "kava.kavadist.v1beta1.MultiSpendRecipient") -} - -func init() { - proto.RegisterFile("kava/kavadist/v1beta1/proposal.proto", fileDescriptor_22ee2c0b398254fd) -} - -var fileDescriptor_22ee2c0b398254fd = []byte{ - // 415 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x93, 0x3d, 0x8f, 0xd3, 0x30, - 0x18, 0xc7, 0xe3, 0xde, 0x71, 0x07, 0x3e, 0xc1, 0x10, 0x0e, 0x29, 0xdc, 0x90, 0x54, 0x85, 0xa1, - 0x02, 0x9d, 0xdd, 0xc2, 0xc6, 0xd8, 0x8a, 0x05, 0xf1, 0x52, 0xa5, 0x03, 0x12, 0x0b, 0x72, 0x12, - 0x2b, 0xb5, 0x9a, 0xf8, 0xb1, 0x62, 0xa7, 0xa2, 0xdf, 0x80, 0x91, 0x91, 0x09, 0x75, 0x43, 0xe2, - 0x33, 0xf0, 0x01, 0x3a, 0x76, 0x64, 0x02, 0xd4, 0x7e, 0x11, 0x94, 0xd7, 0x76, 0xa8, 0xc4, 0xc2, - 0xc0, 0x92, 0xd8, 0xce, 0xf3, 0xff, 0x3d, 0x2f, 0xff, 0x18, 0x3f, 0x9c, 0xb3, 0x05, 0xa3, 0xc5, - 0x23, 0x12, 0xda, 0xd0, 0xc5, 0x30, 0xe0, 0x86, 0x0d, 0xa9, 0xca, 0x40, 0x81, 0x66, 0x09, 0x51, - 0x19, 0x18, 0xb0, 0xef, 0x15, 0x01, 0xa4, 0x89, 0x22, 0x75, 0xd4, 0x95, 0x1b, 0x82, 0x4e, 0x41, - 0xd3, 0x80, 0x69, 0xde, 0x4a, 0x43, 0x10, 0xb2, 0x92, 0x5d, 0x5d, 0xc6, 0x10, 0x43, 0xb9, 0xa4, - 0xc5, 0xaa, 0x3a, 0xed, 0x7d, 0x47, 0xd8, 0x1b, 0x43, 0x9a, 0xe6, 0x52, 0x98, 0xe5, 0x04, 0x20, - 0x79, 0x95, 0x27, 0x46, 0x4c, 0x15, 0x97, 0xd1, 0xa4, 0x4e, 0x6b, 0x5f, 0xe2, 0x1b, 0x46, 0x98, - 0x84, 0x3b, 0xa8, 0x8b, 0xfa, 0xb7, 0xfc, 0x6a, 0x63, 0x77, 0xf1, 0x45, 0xc4, 0x75, 0x98, 0x09, - 0x65, 0x04, 0x48, 0xa7, 0x53, 0x7e, 0x3b, 0x3c, 0xb2, 0xdf, 0xe2, 0x3b, 0x19, 0x0f, 0x85, 0x12, - 0x5c, 0x9a, 0xf7, 0x89, 0xd0, 0xc6, 0x39, 0xe9, 0x9e, 0xf4, 0x2f, 0x9e, 0x3c, 0x22, 0x47, 0x3b, - 0x20, 0xfb, 0xd4, 0x7e, 0x23, 0x1b, 0x9d, 0xae, 0x7f, 0x7a, 0x96, 0x7f, 0xbb, 0xe5, 0xbc, 0x14, - 0xda, 0x3c, 0xbb, 0xf9, 0x71, 0xe5, 0x59, 0x9f, 0x57, 0x9e, 0xd5, 0xfb, 0xda, 0xc1, 0x0f, 0xfe, - 0x52, 0xfe, 0x8b, 0xe9, 0x9b, 0xd7, 0xff, 0x5d, 0x0b, 0x36, 0xc7, 0xe7, 0x11, 0x57, 0xa0, 0x85, - 0x71, 0x4e, 0x4b, 0xe2, 0x7d, 0x52, 0xf9, 0x47, 0x0a, 0xff, 0x5a, 0xde, 0x18, 0x84, 0x1c, 0x0d, - 0x0a, 0xc0, 0xb7, 0x5f, 0x5e, 0x3f, 0x16, 0x66, 0x96, 0x07, 0x24, 0x84, 0x94, 0xd6, 0x66, 0x57, - 0xaf, 0x6b, 0x1d, 0xcd, 0xa9, 0x59, 0x2a, 0xae, 0x4b, 0x81, 0xf6, 0x1b, 0x76, 0x3b, 0x29, 0xd4, - 0xfb, 0x82, 0xf0, 0xdd, 0x23, 0xd5, 0xd9, 0x0e, 0x3e, 0x67, 0x51, 0x94, 0x71, 0xad, 0xeb, 0xd9, - 0x34, 0x5b, 0x3b, 0xc4, 0x67, 0x2c, 0x85, 0x5c, 0x1a, 0xa7, 0xf3, 0xef, 0x2b, 0xac, 0xd1, 0x7b, - 0x2b, 0x47, 0xcf, 0xd7, 0x5b, 0x17, 0x6d, 0xb6, 0x2e, 0xfa, 0xbd, 0x75, 0xd1, 0xa7, 0x9d, 0x6b, - 0x6d, 0x76, 0xae, 0xf5, 0x63, 0xe7, 0x5a, 0xef, 0x1e, 0x1f, 0x50, 0x07, 0x71, 0xc2, 0x02, 0x4d, - 0x07, 0xf1, 0x75, 0x38, 0x63, 0x42, 0xd2, 0x0f, 0xfb, 0xeb, 0x52, 0xe2, 0x83, 0xb3, 0xf2, 0xbf, - 0x7e, 0xfa, 0x27, 0x00, 0x00, 0xff, 0xff, 0x48, 0xb5, 0xa3, 0x9e, 0x4c, 0x03, 0x00, 0x00, -} - -func (m *CommunityPoolMultiSpendProposal) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CommunityPoolMultiSpendProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityPoolMultiSpendProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RecipientList) > 0 { - for iNdEx := len(m.RecipientList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RecipientList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *CommunityPoolMultiSpendProposalJSON) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CommunityPoolMultiSpendProposalJSON) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CommunityPoolMultiSpendProposalJSON) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Deposit) > 0 { - for iNdEx := len(m.Deposit) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposit[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.RecipientList) > 0 { - for iNdEx := len(m.RecipientList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RecipientList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MultiSpendRecipient) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MultiSpendRecipient) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MultiSpendRecipient) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintProposal(dAtA []byte, offset int, v uint64) int { - offset -= sovProposal(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *CommunityPoolMultiSpendProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.RecipientList) > 0 { - for _, e := range m.RecipientList { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func (m *CommunityPoolMultiSpendProposalJSON) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.RecipientList) > 0 { - for _, e := range m.RecipientList { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - if len(m.Deposit) > 0 { - for _, e := range m.Deposit { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func (m *MultiSpendRecipient) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func sovProposal(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozProposal(x uint64) (n int) { - return sovProposal(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *CommunityPoolMultiSpendProposal) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CommunityPoolMultiSpendProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityPoolMultiSpendProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RecipientList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RecipientList = append(m.RecipientList, MultiSpendRecipient{}) - if err := m.RecipientList[len(m.RecipientList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CommunityPoolMultiSpendProposalJSON) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CommunityPoolMultiSpendProposalJSON: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CommunityPoolMultiSpendProposalJSON: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RecipientList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RecipientList = append(m.RecipientList, MultiSpendRecipient{}) - if err := m.RecipientList[len(m.RecipientList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposit", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Deposit = append(m.Deposit, types.Coin{}) - if err := m.Deposit[len(m.Deposit)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MultiSpendRecipient) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MultiSpendRecipient: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MultiSpendRecipient: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipProposal(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProposal - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProposal - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProposal - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthProposal - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupProposal - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthProposal - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthProposal = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowProposal = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupProposal = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/kavadist/types/query.pb.go b/x/kavadist/types/query.pb.go deleted file mode 100644 index 62718acc..00000000 --- a/x/kavadist/types/query.pb.go +++ /dev/null @@ -1,884 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/kavadist/v1beta1/query.proto - -package types - -import ( - context "context" - fmt "fmt" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// QueryParamsRequest defines the request type for querying x/kavadist parameters. -type QueryParamsRequest struct { -} - -func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } -func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryParamsRequest) ProtoMessage() {} -func (*QueryParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_08142b3a0a4f2f78, []int{0} -} -func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsRequest.Merge(m, src) -} -func (m *QueryParamsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo - -// QueryParamsResponse defines the response type for querying x/kavadist parameters. -type QueryParamsResponse struct { - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` -} - -func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } -func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryParamsResponse) ProtoMessage() {} -func (*QueryParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_08142b3a0a4f2f78, []int{1} -} -func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsResponse.Merge(m, src) -} -func (m *QueryParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo - -func (m *QueryParamsResponse) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -// QueryBalanceRequest defines the request type for querying x/kavadist balance. -type QueryBalanceRequest struct { -} - -func (m *QueryBalanceRequest) Reset() { *m = QueryBalanceRequest{} } -func (m *QueryBalanceRequest) String() string { return proto.CompactTextString(m) } -func (*QueryBalanceRequest) ProtoMessage() {} -func (*QueryBalanceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_08142b3a0a4f2f78, []int{2} -} -func (m *QueryBalanceRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryBalanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryBalanceRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryBalanceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryBalanceRequest.Merge(m, src) -} -func (m *QueryBalanceRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryBalanceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryBalanceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryBalanceRequest proto.InternalMessageInfo - -// QueryBalanceResponse defines the response type for querying x/kavadist balance. -type QueryBalanceResponse struct { - Coins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=coins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"coins"` -} - -func (m *QueryBalanceResponse) Reset() { *m = QueryBalanceResponse{} } -func (m *QueryBalanceResponse) String() string { return proto.CompactTextString(m) } -func (*QueryBalanceResponse) ProtoMessage() {} -func (*QueryBalanceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_08142b3a0a4f2f78, []int{3} -} -func (m *QueryBalanceResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryBalanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryBalanceResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryBalanceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryBalanceResponse.Merge(m, src) -} -func (m *QueryBalanceResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryBalanceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryBalanceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryBalanceResponse proto.InternalMessageInfo - -func (m *QueryBalanceResponse) GetCoins() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Coins - } - return nil -} - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.kavadist.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.kavadist.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryBalanceRequest)(nil), "kava.kavadist.v1beta1.QueryBalanceRequest") - proto.RegisterType((*QueryBalanceResponse)(nil), "kava.kavadist.v1beta1.QueryBalanceResponse") -} - -func init() { proto.RegisterFile("kava/kavadist/v1beta1/query.proto", fileDescriptor_08142b3a0a4f2f78) } - -var fileDescriptor_08142b3a0a4f2f78 = []byte{ - // 403 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x52, 0x4f, 0xcf, 0xd2, 0x30, - 0x1c, 0xde, 0x50, 0x30, 0x29, 0xb7, 0x0a, 0x89, 0x2e, 0x5a, 0x60, 0x26, 0x06, 0x24, 0xb4, 0x80, - 0x47, 0x6f, 0x33, 0xde, 0x75, 0x47, 0x6f, 0xdd, 0x68, 0xc6, 0x02, 0xb4, 0x63, 0x2d, 0x44, 0xae, - 0x1e, 0x3d, 0x99, 0xf8, 0x09, 0xbc, 0xfa, 0x49, 0x38, 0x92, 0x78, 0xf1, 0xa4, 0x06, 0xde, 0x0f, - 0xf2, 0xa6, 0x6b, 0xe1, 0x7d, 0xc9, 0x0b, 0x84, 0xcb, 0xd6, 0xfc, 0xfa, 0x3c, 0xbf, 0xe7, 0xcf, - 0x06, 0x5a, 0x13, 0xba, 0xa4, 0x44, 0x3f, 0x46, 0xa9, 0x54, 0x64, 0x39, 0x88, 0x98, 0xa2, 0x03, - 0x32, 0x5f, 0xb0, 0x7c, 0x85, 0xb3, 0x5c, 0x28, 0x01, 0xeb, 0xfa, 0x16, 0xef, 0x21, 0xd8, 0x42, - 0x3c, 0x14, 0x0b, 0x39, 0x13, 0x92, 0x44, 0x54, 0xb2, 0x03, 0x2f, 0x16, 0x29, 0x37, 0x34, 0xaf, - 0x96, 0x88, 0x44, 0x14, 0x47, 0xa2, 0x4f, 0x76, 0xfa, 0x22, 0x11, 0x22, 0x99, 0x32, 0x42, 0xb3, - 0x94, 0x50, 0xce, 0x85, 0xa2, 0x2a, 0x15, 0x5c, 0xda, 0x5b, 0xff, 0xb4, 0x9b, 0x8c, 0xe6, 0x74, - 0x66, 0x31, 0x7e, 0x0d, 0xc0, 0x4f, 0xda, 0xdd, 0xc7, 0x62, 0x18, 0xb2, 0xf9, 0x82, 0x49, 0xe5, - 0x87, 0xe0, 0xe9, 0xd1, 0x54, 0x66, 0x82, 0x4b, 0x06, 0xdf, 0x81, 0x8a, 0x21, 0x3f, 0x73, 0x9b, - 0x6e, 0xbb, 0x3a, 0x7c, 0x89, 0x4f, 0x86, 0xc1, 0x86, 0x16, 0x3c, 0x5e, 0xff, 0x6d, 0x38, 0xa1, - 0xa5, 0xf8, 0x75, 0xbb, 0x33, 0xa0, 0x53, 0xca, 0x63, 0xb6, 0x97, 0x5a, 0x81, 0xda, 0xf1, 0xd8, - 0x6a, 0x51, 0x50, 0xd6, 0xf1, 0xb5, 0xd4, 0xa3, 0x76, 0x75, 0xf8, 0x1c, 0x9b, 0x82, 0xb0, 0x2e, - 0xe8, 0x20, 0xf4, 0x5e, 0xa4, 0x3c, 0xe8, 0x6b, 0x99, 0x5f, 0xff, 0x1a, 0xed, 0x24, 0x55, 0xe3, - 0x45, 0x84, 0x63, 0x31, 0x23, 0xb6, 0x4d, 0xf3, 0xea, 0xc9, 0xd1, 0x84, 0xa8, 0x55, 0xc6, 0x64, - 0x41, 0x90, 0xa1, 0xd9, 0x3c, 0xfc, 0x59, 0x02, 0xe5, 0x42, 0x1b, 0x7e, 0x73, 0x41, 0xc5, 0x98, - 0x86, 0x9d, 0x33, 0x99, 0x1e, 0xb6, 0xe4, 0xbd, 0xb9, 0x06, 0x6a, 0xe2, 0xf8, 0x9d, 0xaf, 0xbf, - 0x6f, 0x7e, 0x94, 0x5e, 0xc1, 0x16, 0xb9, 0xf0, 0x51, 0x98, 0x62, 0xb9, 0xd4, 0x66, 0x9e, 0xd8, - 0x36, 0xe0, 0x45, 0x89, 0xe3, 0x26, 0xbd, 0xee, 0x55, 0x58, 0xeb, 0xe7, 0x75, 0xe1, 0xa7, 0x09, - 0xd1, 0x19, 0x3f, 0x91, 0xc1, 0x07, 0x1f, 0xd6, 0x5b, 0xe4, 0x6e, 0xb6, 0xc8, 0xfd, 0xbf, 0x45, - 0xee, 0xf7, 0x1d, 0x72, 0x36, 0x3b, 0xe4, 0xfc, 0xd9, 0x21, 0xe7, 0x73, 0xf7, 0x5e, 0xdd, 0xfd, - 0x64, 0x4a, 0x23, 0x49, 0xfa, 0x49, 0x2f, 0x1e, 0xd3, 0x94, 0x93, 0x2f, 0x77, 0x0b, 0x8b, 0xde, - 0xa3, 0x4a, 0xf1, 0xb7, 0xbd, 0xbd, 0x0d, 0x00, 0x00, 0xff, 0xff, 0xfa, 0xe0, 0x74, 0x45, 0x21, - 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - // Params queries the parameters of x/kavadist module. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Balance queries the balance of all coins of x/kavadist module. - Balance(ctx context.Context, in *QueryBalanceRequest, opts ...grpc.CallOption) (*QueryBalanceResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { - out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, "/kava.kavadist.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Balance(ctx context.Context, in *QueryBalanceRequest, opts ...grpc.CallOption) (*QueryBalanceResponse, error) { - out := new(QueryBalanceResponse) - err := c.cc.Invoke(ctx, "/kava.kavadist.v1beta1.Query/Balance", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries the parameters of x/kavadist module. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Balance queries the balance of all coins of x/kavadist module. - Balance(context.Context, *QueryBalanceRequest) (*QueryBalanceResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") -} -func (*UnimplementedQueryServer) Balance(ctx context.Context, req *QueryBalanceRequest) (*QueryBalanceResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Balance not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryParamsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Params(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.kavadist.v1beta1.Query/Params", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Balance_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryBalanceRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Balance(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.kavadist.v1beta1.Query/Balance", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Balance(ctx, req.(*QueryBalanceRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.kavadist.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Balance", - Handler: _Query_Balance_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/kavadist/v1beta1/query.proto", -} - -func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryBalanceRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryBalanceRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryBalanceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryBalanceResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryBalanceResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryBalanceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Coins) > 0 { - for iNdEx := len(m.Coins) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Coins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryParamsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryBalanceRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryBalanceResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Coins) > 0 { - for _, e := range m.Coins { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryBalanceRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryBalanceRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryBalanceRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryBalanceResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryBalanceResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryBalanceResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Coins", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Coins = append(m.Coins, types.Coin{}) - if err := m.Coins[len(m.Coins)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/kavadist/types/query.pb.gw.go b/x/kavadist/types/query.pb.gw.go deleted file mode 100644 index 2f6503d3..00000000 --- a/x/kavadist/types/query.pb.gw.go +++ /dev/null @@ -1,218 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/kavadist/v1beta1/query.proto - -/* -Package types is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package types - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join - -func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Params(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_Balance_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryBalanceRequest - var metadata runtime.ServerMetadata - - msg, err := client.Balance(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Balance_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryBalanceRequest - var metadata runtime.ServerMetadata - - msg, err := server.Balance(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Balance_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Balance_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Balance_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Balance_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Balance_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Balance_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "kavadist", "v1beta1", "parameters"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Balance_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "kavadist", "v1beta1", "balance"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Balance_0 = runtime.ForwardResponseMessage -) diff --git a/x/liquid/client/cli/query.go b/x/liquid/client/cli/query.go deleted file mode 100644 index 6b7314fa..00000000 --- a/x/liquid/client/cli/query.go +++ /dev/null @@ -1,31 +0,0 @@ -package cli - -import ( - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - - "github.com/0glabs/0g-chain/x/liquid/types" -) - -// GetQueryCmd returns the cli query commands for this module -func GetQueryCmd() *cobra.Command { - liquidQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the liquid module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{} - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - liquidQueryCmd.AddCommand(cmds...) - - return liquidQueryCmd -} diff --git a/x/liquid/client/cli/tx.go b/x/liquid/client/cli/tx.go deleted file mode 100644 index 4e078baa..00000000 --- a/x/liquid/client/cli/tx.go +++ /dev/null @@ -1,109 +0,0 @@ -package cli - -import ( - "fmt" - - "github.com/spf13/cobra" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/0glabs/0g-chain/x/liquid/types" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - liquidTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "liquid transactions subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - getCmdMintDerivative(), - getCmdBurnDerivative(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - liquidTxCmd.AddCommand(cmds...) - - return liquidTxCmd -} - -func getCmdMintDerivative() *cobra.Command { - return &cobra.Command{ - Use: "mint [validator-addr] [amount]", - Short: "mints staking derivative from a delegation", - Long: "Mint removes a portion of a user's staking delegation and issues them validator specific staking derivative tokens.", - Args: cobra.ExactArgs(2), - Example: fmt.Sprintf( - `%s tx %s mint kavavaloper16lnfpgn6llvn4fstg5nfrljj6aaxyee9z59jqd 10000000ukava --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - valAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - coin, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - msg := types.NewMsgMintDerivative(clientCtx.GetFromAddress(), valAddr, coin) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -func getCmdBurnDerivative() *cobra.Command { - return &cobra.Command{ - Use: "burn [amount]", - Short: "burns staking derivative to redeem a delegation", - Long: "Burn removes some staking derivative from a user's account and converts it back to a staking delegation.", - Example: fmt.Sprintf( - `%s tx %s burn 10000000bkava-kavavaloper16lnfpgn6llvn4fstg5nfrljj6aaxyee9z59jqd --from `, version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - amount, err := sdk.ParseCoinNormalized(args[0]) - if err != nil { - return err - } - - valAddr, err := types.ParseLiquidStakingTokenDenom(amount.Denom) - if err != nil { - return errorsmod.Wrap(types.ErrInvalidDenom, err.Error()) - } - - msg := types.NewMsgBurnDerivative(clientCtx.GetFromAddress(), valAddr, amount) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} diff --git a/x/liquid/keeper/claim.go b/x/liquid/keeper/claim.go deleted file mode 100644 index 00de72fc..00000000 --- a/x/liquid/keeper/claim.go +++ /dev/null @@ -1,55 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/liquid/types" -) - -func (k Keeper) CollectStakingRewards( - ctx sdk.Context, - validator sdk.ValAddress, - destinationModAccount string, -) (sdk.Coins, error) { - macc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) - - // Ensure withdraw address is as expected - withdrawAddr := k.distributionKeeper.GetDelegatorWithdrawAddr(ctx, macc.GetAddress()) - if !withdrawAddr.Equals(macc.GetAddress()) { - panic(fmt.Sprintf( - "unexpected withdraw address for liquid staking module account, expected %s, got %s", - macc.GetAddress(), withdrawAddr, - )) - } - - rewards, err := k.distributionKeeper.WithdrawDelegationRewards(ctx, macc.GetAddress(), validator) - if err != nil { - return nil, err - } - - if rewards.IsZero() { - return rewards, nil - } - - err = k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleAccountName, destinationModAccount, rewards) - if err != nil { - return nil, err - } - - return rewards, nil -} - -func (k Keeper) CollectStakingRewardsByDenom( - ctx sdk.Context, - derivativeDenom string, - destinationModAccount string, -) (sdk.Coins, error) { - valAddr, err := types.ParseLiquidStakingTokenDenom(derivativeDenom) - if err != nil { - return nil, err - } - - return k.CollectStakingRewards(ctx, valAddr, destinationModAccount) -} diff --git a/x/liquid/keeper/claim_test.go b/x/liquid/keeper/claim_test.go deleted file mode 100644 index 6c0d30c1..00000000 --- a/x/liquid/keeper/claim_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package keeper_test - -import ( - sdkmath "cosmossdk.io/math" - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/liquid/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" - - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" -) - -func (suite *KeeperTestSuite) TestCollectStakingRewards() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr1, delegator := addrs[0], addrs[1] - valAddr1 := sdk.ValAddress(valAccAddr1) - - initialBalance := i(1e9) - delegateAmount := i(100e6) - - suite.NoError(suite.App.FundModuleAccount( - suite.Ctx, - distrtypes.ModuleName, - sdk.NewCoins( - sdk.NewCoin("ukava", initialBalance), - ), - )) - - suite.CreateAccountWithAddress(valAccAddr1, suite.NewBondCoins(initialBalance)) - suite.CreateAccountWithAddress(delegator, suite.NewBondCoins(initialBalance)) - - suite.CreateNewUnbondedValidator(valAddr1, initialBalance) - suite.CreateDelegation(valAddr1, delegator, delegateAmount) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - // Transfers delegation to module account - _, err := suite.Keeper.MintDerivative(suite.Ctx, delegator, valAddr1, suite.NewBondCoin(delegateAmount)) - suite.Require().NoError(err) - - validator, found := suite.StakingKeeper.GetValidator(suite.Ctx, valAddr1) - suite.Require().True(found) - - suite.Ctx = suite.Ctx.WithBlockHeight(2) - - distrKeeper := suite.App.GetDistrKeeper() - stakingKeeper := suite.App.GetStakingKeeper() - accKeeper := suite.App.GetAccountKeeper() - liquidMacc := accKeeper.GetModuleAccount(suite.Ctx, types.ModuleAccountName) - - // Add rewards - rewardCoins := sdk.NewDecCoins(sdk.NewDecCoin("ukava", sdkmath.NewInt(500e6))) - distrKeeper.AllocateTokensToValidator(suite.Ctx, validator, rewardCoins) - - delegation, found := stakingKeeper.GetDelegation(suite.Ctx, liquidMacc.GetAddress(), valAddr1) - suite.Require().True(found) - - // Get amount of rewards - endingPeriod := distrKeeper.IncrementValidatorPeriod(suite.Ctx, validator) - delegationRewards := distrKeeper.CalculateDelegationRewards(suite.Ctx, validator, delegation, endingPeriod) - truncatedRewards, _ := delegationRewards.TruncateDecimal() - - suite.Run("collect staking rewards", func() { - // Collect rewards - derivativeDenom := suite.Keeper.GetLiquidStakingTokenDenom(valAddr1) - rewards, err := suite.Keeper.CollectStakingRewardsByDenom(suite.Ctx, derivativeDenom, types.ModuleName) - suite.Require().NoError(err) - suite.Require().Equal(truncatedRewards, rewards) - - suite.True(rewards.AmountOf("ukava").IsPositive()) - - // Check balances - suite.AccountBalanceEqual(liquidMacc.GetAddress(), rewards) - }) - - suite.Run("collect staking rewards with non-validator", func() { - // acc2 not a validator - derivativeDenom := suite.Keeper.GetLiquidStakingTokenDenom(sdk.ValAddress(addrs[2])) - _, err := suite.Keeper.CollectStakingRewardsByDenom(suite.Ctx, derivativeDenom, types.ModuleName) - suite.Require().Error(err) - suite.Require().Equal("no validator distribution info", err.Error()) - }) - - suite.Run("collect staking rewards with invalid denom", func() { - derivativeDenom := "bkava" - _, err := suite.Keeper.CollectStakingRewardsByDenom(suite.Ctx, derivativeDenom, types.ModuleName) - suite.Require().Error(err) - suite.Require().Equal("cannot parse denom bkava", err.Error()) - }) -} diff --git a/x/liquid/keeper/derivative.go b/x/liquid/keeper/derivative.go deleted file mode 100644 index 06adddad..00000000 --- a/x/liquid/keeper/derivative.go +++ /dev/null @@ -1,198 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/liquid/types" -) - -// MintDerivative removes a user's staking delegation and mints them equivalent staking derivative coins. -// -// The input staking token amount is used to calculate shares in the user's delegation, which are transferred to a delegation owned by the module. -// Derivative coins are them minted and transferred to the user. -func (k Keeper) MintDerivative(ctx sdk.Context, delegatorAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) (sdk.Coin, error) { - bondDenom := k.stakingKeeper.BondDenom(ctx) - if amount.Denom != bondDenom { - return sdk.Coin{}, errorsmod.Wrapf(types.ErrInvalidDenom, "expected %s", bondDenom) - } - - derivativeAmount, shares, err := k.CalculateDerivativeSharesFromTokens(ctx, delegatorAddr, valAddr, amount.Amount) - if err != nil { - return sdk.Coin{}, err - } - - // Fetching the module account will create it if it doesn't exist. - // This is necessary as otherwise TransferDelegation will create a normal account. - modAcc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) - if _, err := k.TransferDelegation(ctx, valAddr, delegatorAddr, modAcc.GetAddress(), shares); err != nil { - return sdk.Coin{}, err - } - - liquidTokenDenom := k.GetLiquidStakingTokenDenom(valAddr) - liquidToken := sdk.NewCoin(liquidTokenDenom, derivativeAmount) - if err = k.mintCoins(ctx, delegatorAddr, sdk.NewCoins(liquidToken)); err != nil { - return sdk.Coin{}, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeMintDerivative, - sdk.NewAttribute(types.AttributeKeyDelegator, delegatorAddr.String()), - sdk.NewAttribute(types.AttributeKeyValidator, valAddr.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, liquidToken.String()), - sdk.NewAttribute(types.AttributeKeySharesTransferred, shares.String()), - ), - ) - - return liquidToken, nil -} - -// CalculateDerivativeSharesFromTokens converts a staking token amount into its equivalent delegation shares, and staking derivative amount. -// This combines the code for calculating the shares to be transferred, and the derivative coins to be minted. -func (k Keeper) CalculateDerivativeSharesFromTokens(ctx sdk.Context, delegator sdk.AccAddress, validator sdk.ValAddress, tokens sdkmath.Int) (sdkmath.Int, sdk.Dec, error) { - if !tokens.IsPositive() { - return sdkmath.Int{}, sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, "token amount must be positive") - } - shares, err := k.stakingKeeper.ValidateUnbondAmount(ctx, delegator, validator, tokens) - if err != nil { - return sdkmath.Int{}, sdk.Dec{}, err - } - return shares.TruncateInt(), shares, nil -} - -// BurnDerivative burns an user's staking derivative coins and returns them an equivalent staking delegation. -// -// The derivative coins are burned, and an equivalent number of shares in the module's staking delegation are transferred back to the user. -func (k Keeper) BurnDerivative(ctx sdk.Context, delegatorAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) (sdk.Dec, error) { - - if amount.Denom != k.GetLiquidStakingTokenDenom(valAddr) { - return sdk.Dec{}, errorsmod.Wrap(types.ErrInvalidDenom, "derivative denom does not match validator") - } - - if err := k.burnCoins(ctx, delegatorAddr, sdk.NewCoins(amount)); err != nil { - return sdk.Dec{}, err - } - - modAcc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) - shares := sdk.NewDecFromInt(amount.Amount) - receivedShares, err := k.TransferDelegation(ctx, valAddr, modAcc.GetAddress(), delegatorAddr, shares) - if err != nil { - return sdk.Dec{}, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeBurnDerivative, - sdk.NewAttribute(types.AttributeKeyDelegator, delegatorAddr.String()), - sdk.NewAttribute(types.AttributeKeyValidator, valAddr.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, amount.String()), - sdk.NewAttribute(types.AttributeKeySharesTransferred, shares.String()), - ), - ) - return receivedShares, nil -} - -func (k Keeper) GetLiquidStakingTokenDenom(valAddr sdk.ValAddress) string { - return types.GetLiquidStakingTokenDenom(k.derivativeDenom, valAddr) -} - -// IsDerivativeDenom returns true if the denom is a valid derivative denom and -// corresponds to a valid validator. -func (k Keeper) IsDerivativeDenom(ctx sdk.Context, denom string) bool { - valAddr, err := types.ParseLiquidStakingTokenDenom(denom) - if err != nil { - return false - } - - _, found := k.stakingKeeper.GetValidator(ctx, valAddr) - return found -} - -// GetStakedTokensForDerivatives returns the total value of the provided derivatives -// in staked tokens, accounting for the specific share prices. -func (k Keeper) GetStakedTokensForDerivatives(ctx sdk.Context, coins sdk.Coins) (sdk.Coin, error) { - total := sdk.ZeroInt() - - for _, coin := range coins { - valAddr, err := types.ParseLiquidStakingTokenDenom(coin.Denom) - if err != nil { - return sdk.Coin{}, fmt.Errorf("invalid derivative denom: %w", err) - } - - validator, found := k.stakingKeeper.GetValidator(ctx, valAddr) - if !found { - return sdk.Coin{}, fmt.Errorf("invalid derivative denom %s: validator not found", coin.Denom) - } - - // bkava is 1:1 to delegation shares - valTokens := validator.TokensFromSharesTruncated(sdk.NewDecFromInt(coin.Amount)) - total = total.Add(valTokens.TruncateInt()) - } - - totalCoin := sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), total) - return totalCoin, nil -} - -// GetTotalDerivativeValue returns the total sum value of all derivative coins -// for all validators denominated by the bond token (ukava). -func (k Keeper) GetTotalDerivativeValue(ctx sdk.Context) (sdk.Coin, error) { - bkavaCoins := sdk.NewCoins() - - k.bankKeeper.IterateTotalSupply(ctx, func(c sdk.Coin) bool { - if k.IsDerivativeDenom(ctx, c.Denom) { - bkavaCoins = bkavaCoins.Add(c) - } - - return false - }) - - return k.GetStakedTokensForDerivatives(ctx, bkavaCoins) -} - -// GetDerivativeValue returns the total underlying value of the provided -// derivative denominated by the bond token (ukava). -func (k Keeper) GetDerivativeValue(ctx sdk.Context, denom string) (sdk.Coin, error) { - return k.GetStakedTokensForDerivatives(ctx, sdk.NewCoins(k.bankKeeper.GetSupply(ctx, denom))) -} - -func (k Keeper) mintCoins(ctx sdk.Context, receiver sdk.AccAddress, amount sdk.Coins) error { - if err := k.bankKeeper.MintCoins(ctx, types.ModuleAccountName, amount); err != nil { - return err - } - if err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, receiver, amount); err != nil { - return err - } - return nil -} - -func (k Keeper) burnCoins(ctx sdk.Context, sender sdk.AccAddress, amount sdk.Coins) error { - if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleAccountName, amount); err != nil { - return err - } - if err := k.bankKeeper.BurnCoins(ctx, types.ModuleAccountName, amount); err != nil { - return err - } - return nil -} - -// DerivativeFromTokens calculates the approximate amount of derivative coins that would be minted for a given amount of staking tokens. -func (k Keeper) DerivativeFromTokens(ctx sdk.Context, valAddr sdk.ValAddress, tokens sdk.Coin) (sdk.Coin, error) { - bondDenom := k.stakingKeeper.BondDenom(ctx) - if tokens.Denom != bondDenom { - return sdk.Coin{}, errorsmod.Wrapf(types.ErrInvalidDenom, "'%s' does not match staking denom '%s'", tokens.Denom, bondDenom) - } - - // Use GetModuleAddress instead of GetModuleAccount to avoid creating a module account if it doesn't exist. - modAddress := k.accountKeeper.GetModuleAddress(types.ModuleAccountName) - derivative, _, err := k.CalculateDerivativeSharesFromTokens(ctx, modAddress, valAddr, tokens.Amount) - if err != nil { - return sdk.Coin{}, err - } - liquidTokenDenom := k.GetLiquidStakingTokenDenom(valAddr) - liquidToken := sdk.NewCoin(liquidTokenDenom, derivative) - return liquidToken, nil -} diff --git a/x/liquid/keeper/derivative_test.go b/x/liquid/keeper/derivative_test.go deleted file mode 100644 index d53b1769..00000000 --- a/x/liquid/keeper/derivative_test.go +++ /dev/null @@ -1,551 +0,0 @@ -package keeper_test - -import ( - "fmt" - - 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/cosmos/cosmos-sdk/x/staking" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/liquid/types" -) - -func (suite *KeeperTestSuite) TestBurnDerivative() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, user := addrs[0], addrs[1] - valAddr := sdk.ValAddress(valAccAddr) - - liquidDenom := suite.Keeper.GetLiquidStakingTokenDenom(valAddr) - - testCases := []struct { - name string - balance sdk.Coin - moduleDelegation sdkmath.Int - burnAmount sdk.Coin - expectedErr error - }{ - { - name: "user can burn their entire balance", - balance: c(liquidDenom, 1e9), - moduleDelegation: i(1e9), - burnAmount: c(liquidDenom, 1e9), - }, - { - name: "user can burn minimum derivative unit", - balance: c(liquidDenom, 1e9), - moduleDelegation: i(1e9), - burnAmount: c(liquidDenom, 1), - }, - { - name: "error when denom cannot be parsed", - balance: c(liquidDenom, 1e9), - moduleDelegation: i(1e9), - burnAmount: c(fmt.Sprintf("ckava-%s", valAddr), 1e6), - expectedErr: types.ErrInvalidDenom, - }, - { - name: "error when burn amount is 0", - balance: c(liquidDenom, 1e9), - moduleDelegation: i(1e9), - burnAmount: c(liquidDenom, 0), - expectedErr: types.ErrUntransferableShares, - }, - { - name: "error when user doesn't have enough funds", - balance: c("ukava", 10), - moduleDelegation: i(1e9), - burnAmount: c(liquidDenom, 1e9), - expectedErr: sdkerrors.ErrInsufficientFunds, - }, - { - name: "error when backing delegation isn't large enough", - balance: c(liquidDenom, 1e9), - moduleDelegation: i(999_999_999), - burnAmount: c(liquidDenom, 1e9), - expectedErr: stakingtypes.ErrNotEnoughDelegationShares, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(i(1e6))) - suite.CreateAccountWithAddress(user, sdk.NewCoins(tc.balance)) - suite.AddCoinsToModule(types.ModuleAccountName, suite.NewBondCoins(tc.moduleDelegation)) - - // create delegation from module account to back the derivatives - moduleAccAddress := authtypes.NewModuleAddress(types.ModuleAccountName) - suite.CreateNewUnbondedValidator(valAddr, i(1e6)) - suite.CreateDelegation(valAddr, moduleAccAddress, tc.moduleDelegation) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - modBalance := suite.BankKeeper.GetAllBalances(suite.Ctx, moduleAccAddress) - - _, err := suite.Keeper.BurnDerivative(suite.Ctx, user, valAddr, tc.burnAmount) - - suite.Require().ErrorIs(err, tc.expectedErr) - if tc.expectedErr != nil { - // if an error is expected, state should be reverted so don't need to test state is unchanged - return - } - - suite.AccountBalanceEqual(user, sdk.NewCoins(tc.balance.Sub(tc.burnAmount))) - suite.AccountBalanceEqual(moduleAccAddress, modBalance) // ensure derivatives are burned, and not in module account - - sharesTransferred := sdk.NewDecFromInt(tc.burnAmount.Amount) - suite.DelegationSharesEqual(valAddr, user, sharesTransferred) - suite.DelegationSharesEqual(valAddr, moduleAccAddress, sdk.NewDecFromInt(tc.moduleDelegation).Sub(sharesTransferred)) - - suite.EventsContains(suite.Ctx.EventManager().Events(), sdk.NewEvent( - types.EventTypeBurnDerivative, - sdk.NewAttribute(types.AttributeKeyDelegator, user.String()), - sdk.NewAttribute(types.AttributeKeyValidator, valAddr.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, tc.burnAmount.String()), - sdk.NewAttribute(types.AttributeKeySharesTransferred, sharesTransferred.String()), - )) - }) - } -} - -func (suite *KeeperTestSuite) TestCalculateShares() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, delegator := addrs[0], addrs[1] - valAddr := sdk.ValAddress(valAccAddr) - - type returns struct { - derivatives sdkmath.Int - shares sdk.Dec - err error - } - type validator struct { - tokens sdkmath.Int - delegatorShares sdk.Dec - } - testCases := []struct { - name string - validator *validator - delegation sdk.Dec - transfer sdkmath.Int - expected returns - }{ - { - name: "error when validator not found", - validator: nil, - delegation: d("1000000000"), - transfer: i(500e6), - expected: returns{ - err: stakingtypes.ErrNoValidatorFound, - }, - }, - { - name: "error when delegation not found", - validator: &validator{i(1e9), d("1000000000")}, - delegation: sdk.Dec{}, - transfer: i(500e6), - expected: returns{ - err: stakingtypes.ErrNoDelegation, - }, - }, - { - name: "error when transfer < 0", - validator: &validator{i(10), d("10")}, - delegation: d("10"), - transfer: i(-1), - expected: returns{ - err: types.ErrUntransferableShares, - }, - }, - { // disallow zero transfers - name: "error when transfer = 0", - validator: &validator{i(10), d("10")}, - delegation: d("10"), - transfer: i(0), - expected: returns{ - err: types.ErrUntransferableShares, - }, - }, - { - name: "error when transfer > delegated shares", - validator: &validator{i(10), d("10")}, - delegation: d("10"), - transfer: i(11), - expected: returns{ - err: sdkerrors.ErrInvalidRequest, - }, - }, - { - name: "error when validator has no tokens", - validator: &validator{i(0), d("10")}, - delegation: d("10"), - transfer: i(5), - expected: returns{ - err: stakingtypes.ErrInsufficientShares, - }, - }, - { - name: "shares and derivatives are truncated", - validator: &validator{i(3), d("4")}, - delegation: d("4"), - transfer: i(2), - expected: returns{ - derivatives: i(2), // truncated down - shares: d("2.666666666666666666"), // 2/3 * 4 not rounded to ...667 - }, - }, - { - name: "error if calculated shares > shares in delegation", - validator: &validator{i(3), d("4")}, - delegation: d("2.666666666666666665"), // one less than 2/3 * 4 - transfer: i(2), - expected: returns{ - err: sdkerrors.ErrInvalidRequest, - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - if tc.validator != nil { - suite.StakingKeeper.SetValidator(suite.Ctx, stakingtypes.Validator{ - OperatorAddress: valAddr.String(), - Tokens: tc.validator.tokens, - DelegatorShares: tc.validator.delegatorShares, - }) - } - if !tc.delegation.IsNil() { - suite.StakingKeeper.SetDelegation(suite.Ctx, stakingtypes.Delegation{ - DelegatorAddress: delegator.String(), - ValidatorAddress: valAddr.String(), - Shares: tc.delegation, - }) - } - - derivatives, shares, err := suite.Keeper.CalculateDerivativeSharesFromTokens(suite.Ctx, delegator, valAddr, tc.transfer) - if tc.expected.err != nil { - suite.ErrorIs(err, tc.expected.err) - } else { - suite.NoError(err) - suite.Equal(tc.expected.derivatives, derivatives, "expected '%s' got '%s'", tc.expected.derivatives, derivatives) - suite.Equal(tc.expected.shares, shares) - } - }) - } -} - -func (suite *KeeperTestSuite) TestMintDerivative() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, delegator := addrs[0], addrs[1] - valAddr := sdk.ValAddress(valAccAddr) - moduleAccAddress := authtypes.NewModuleAddress(types.ModuleAccountName) - - initialBalance := i(1e9) - vestedBalance := i(500e6) - - testCases := []struct { - name string - amount sdk.Coin - expectedDerivatives sdkmath.Int - expectedSharesRemaining sdk.Dec - expectedSharesAdded sdk.Dec - expectedErr error - }{ - { - name: "derivative is minted", - amount: suite.NewBondCoin(vestedBalance), - expectedDerivatives: i(500e6), - expectedSharesRemaining: d("500000000.0"), - expectedSharesAdded: d("500000000.0"), - }, - { - name: "error when the input denom isn't correct", - amount: sdk.NewCoin("invalid", i(1000)), - expectedErr: types.ErrInvalidDenom, - }, - { - name: "error when shares cannot be calculated", - amount: suite.NewBondCoin(initialBalance.Mul(i(100))), - expectedErr: sdkerrors.ErrInvalidRequest, - }, - { - name: "error when shares cannot be transferred", - amount: suite.NewBondCoin(initialBalance), // trying to move vesting coins will fail in `TransferShares` - expectedErr: sdkerrors.ErrInsufficientFunds, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(initialBalance)) - suite.CreateVestingAccountWithAddress(delegator, suite.NewBondCoins(initialBalance), suite.NewBondCoins(vestedBalance)) - - suite.CreateNewUnbondedValidator(valAddr, initialBalance) - suite.CreateDelegation(valAddr, delegator, initialBalance) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - _, err := suite.Keeper.MintDerivative(suite.Ctx, delegator, valAddr, tc.amount) - - suite.Require().ErrorIs(err, tc.expectedErr) - if tc.expectedErr != nil { - // if an error is expected, state should be reverted so don't need to test state is unchanged - return - } - - derivative := sdk.NewCoins(sdk.NewCoin(fmt.Sprintf("bkava-%s", valAddr), tc.expectedDerivatives)) - suite.AccountBalanceEqual(delegator, derivative) - - suite.DelegationSharesEqual(valAddr, delegator, tc.expectedSharesRemaining) - suite.DelegationSharesEqual(valAddr, moduleAccAddress, tc.expectedSharesAdded) - - sharesTransferred := sdk.NewDecFromInt(initialBalance).Sub(tc.expectedSharesRemaining) - suite.EventsContains(suite.Ctx.EventManager().Events(), sdk.NewEvent( - types.EventTypeMintDerivative, - sdk.NewAttribute(types.AttributeKeyDelegator, delegator.String()), - sdk.NewAttribute(types.AttributeKeyValidator, valAddr.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, derivative.String()), - sdk.NewAttribute(types.AttributeKeySharesTransferred, sharesTransferred.String()), - )) - }) - } -} - -func (suite *KeeperTestSuite) TestIsDerivativeDenom() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr1, delegator, valAccAddr2 := addrs[0], addrs[1], addrs[2] - valAddr1 := sdk.ValAddress(valAccAddr1) - - // Validator addr that has **not** delegated anything - valAddr2 := sdk.ValAddress(valAccAddr2) - - initialBalance := i(1e9) - vestedBalance := i(500e6) - - suite.CreateAccountWithAddress(valAccAddr1, suite.NewBondCoins(initialBalance)) - suite.CreateVestingAccountWithAddress(delegator, suite.NewBondCoins(initialBalance), suite.NewBondCoins(vestedBalance)) - - suite.CreateNewUnbondedValidator(valAddr1, initialBalance) - suite.CreateDelegation(valAddr1, delegator, initialBalance) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - testCases := []struct { - name string - denom string - wantIsDenom bool - }{ - { - name: "valid derivative denom", - denom: suite.Keeper.GetLiquidStakingTokenDenom(valAddr1), - wantIsDenom: true, - }, - { - name: "invalid - undelegated validator addr", - denom: suite.Keeper.GetLiquidStakingTokenDenom(valAddr2), - wantIsDenom: false, - }, - { - name: "invalid - invalid val addr", - denom: "bkava-asdfasdf", - wantIsDenom: false, - }, - { - name: "invalid - ukava", - denom: "ukava", - wantIsDenom: false, - }, - { - name: "invalid - plain bkava", - denom: "bkava", - wantIsDenom: false, - }, - { - name: "invalid - bkava prefix", - denom: "bkava-", - wantIsDenom: false, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - isDenom := suite.Keeper.IsDerivativeDenom(suite.Ctx, tc.denom) - - suite.Require().Equal(tc.wantIsDenom, isDenom) - }) - } -} - -func (suite *KeeperTestSuite) TestGetStakedTokensForDerivatives() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr1, delegator, valAccAddr2, valAccAddr3 := addrs[0], addrs[1], addrs[2], addrs[3] - valAddr1 := sdk.ValAddress(valAccAddr1) - - // Validator addr that has **not** delegated anything - valAddr2 := sdk.ValAddress(valAccAddr2) - - valAddr3 := sdk.ValAddress(valAccAddr3) - - initialBalance := i(1e9) - vestedBalance := i(500e6) - delegateAmount := i(100e6) - - suite.CreateAccountWithAddress(valAccAddr1, suite.NewBondCoins(initialBalance)) - suite.CreateVestingAccountWithAddress(delegator, suite.NewBondCoins(initialBalance), suite.NewBondCoins(vestedBalance)) - - suite.CreateNewUnbondedValidator(valAddr1, initialBalance) - suite.CreateDelegation(valAddr1, delegator, delegateAmount) - - suite.CreateAccountWithAddress(valAccAddr3, suite.NewBondCoins(initialBalance)) - - suite.CreateNewUnbondedValidator(valAddr3, initialBalance) - suite.CreateDelegation(valAddr3, delegator, delegateAmount) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - suite.SlashValidator(valAddr3, d("0.05")) - - _, err := suite.Keeper.MintDerivative(suite.Ctx, delegator, valAddr1, suite.NewBondCoin(delegateAmount)) - suite.Require().NoError(err) - - testCases := []struct { - name string - derivatives sdk.Coins - wantKavaAmount sdkmath.Int - err error - }{ - { - name: "valid derivative denom", - derivatives: sdk.NewCoins( - sdk.NewCoin(suite.Keeper.GetLiquidStakingTokenDenom(valAddr1), vestedBalance), - ), - wantKavaAmount: vestedBalance, - }, - { - name: "valid - slashed validator", - derivatives: sdk.NewCoins( - sdk.NewCoin(suite.Keeper.GetLiquidStakingTokenDenom(valAddr3), vestedBalance), - ), - // vestedBalance * 95% - wantKavaAmount: vestedBalance.Mul(sdkmath.NewInt(95)).Quo(sdkmath.NewInt(100)), - }, - { - name: "valid - sum", - derivatives: sdk.NewCoins( - sdk.NewCoin(suite.Keeper.GetLiquidStakingTokenDenom(valAddr3), vestedBalance), - sdk.NewCoin(suite.Keeper.GetLiquidStakingTokenDenom(valAddr1), vestedBalance), - ), - // vestedBalance + (vestedBalance * 95%) - wantKavaAmount: vestedBalance.Mul(sdkmath.NewInt(95)).Quo(sdkmath.NewInt(100)).Add(vestedBalance), - }, - { - name: "invalid - undelegated validator address denom", - derivatives: sdk.NewCoins( - sdk.NewCoin(suite.Keeper.GetLiquidStakingTokenDenom(valAddr2), vestedBalance), - ), - err: fmt.Errorf("invalid derivative denom %s: validator not found", suite.Keeper.GetLiquidStakingTokenDenom(valAddr2)), - }, - { - name: "invalid - denom", - derivatives: sdk.NewCoins( - sdk.NewCoin("kava", vestedBalance), - ), - err: fmt.Errorf("invalid derivative denom: cannot parse denom kava"), - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - kavaAmount, err := suite.Keeper.GetStakedTokensForDerivatives(suite.Ctx, tc.derivatives) - - if tc.err != nil { - suite.Require().Error(err) - } else { - suite.Require().NoError(err) - suite.Require().Equal(suite.NewBondCoin(tc.wantKavaAmount), kavaAmount) - } - }) - } -} - -func (suite *KeeperTestSuite) TestGetDerivativeValue() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr1, delegator, valAccAddr2 := addrs[0], addrs[1], addrs[2] - valAddr1 := sdk.ValAddress(valAccAddr1) - - valAddr2 := sdk.ValAddress(valAccAddr2) - - initialBalance := i(1e9) - vestedBalance := i(500e6) - delegateAmount := i(100e6) - - suite.CreateAccountWithAddress(valAccAddr1, suite.NewBondCoins(initialBalance)) - suite.CreateVestingAccountWithAddress(delegator, suite.NewBondCoins(initialBalance), suite.NewBondCoins(vestedBalance)) - - suite.CreateNewUnbondedValidator(valAddr1, initialBalance) - suite.CreateDelegation(valAddr1, delegator, delegateAmount) - - suite.CreateAccountWithAddress(valAccAddr2, suite.NewBondCoins(initialBalance)) - - suite.CreateNewUnbondedValidator(valAddr2, initialBalance) - suite.CreateDelegation(valAddr2, delegator, delegateAmount) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - _, err := suite.Keeper.MintDerivative(suite.Ctx, delegator, valAddr1, suite.NewBondCoin(delegateAmount)) - suite.Require().NoError(err) - - _, err = suite.Keeper.MintDerivative(suite.Ctx, delegator, valAddr2, suite.NewBondCoin(delegateAmount)) - suite.Require().NoError(err) - - suite.SlashValidator(valAddr2, d("0.05")) - - suite.Run("total value", func() { - totalValue, err := suite.Keeper.GetTotalDerivativeValue(suite.Ctx) - suite.Require().NoError(err) - suite.Require().Equal( - // delegateAmount + (delegateAmount * 95%) - delegateAmount.Add(delegateAmount.MulRaw(95).QuoRaw(100)), - totalValue.Amount, - ) - }) - - suite.Run("1:1 derivative value", func() { - derivativeValue, err := suite.Keeper.GetDerivativeValue(suite.Ctx, suite.Keeper.GetLiquidStakingTokenDenom(valAddr1)) - suite.Require().NoError(err) - suite.Require().Equal(suite.NewBondCoin(delegateAmount), derivativeValue) - }) - - suite.Run("slashed derivative value", func() { - derivativeValue, err := suite.Keeper.GetDerivativeValue(suite.Ctx, suite.Keeper.GetLiquidStakingTokenDenom(valAddr2)) - suite.Require().NoError(err) - // delegateAmount * 95% - suite.Require().Equal(delegateAmount.MulRaw(95).QuoRaw(100), derivativeValue.Amount) - }) -} - -func (suite *KeeperTestSuite) TestDerivativeFromTokens() { - _, addrs := app.GeneratePrivKeyAddressPairs(1) - valAccAddr := addrs[0] - valAddr := sdk.ValAddress(valAccAddr) - moduleAccAddress := authtypes.NewModuleAddress(types.ModuleAccountName) - - initialBalance := i(1e9) - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(initialBalance)) - suite.AddCoinsToModule(types.ModuleAccountName, suite.NewBondCoins(initialBalance)) - - suite.CreateNewUnbondedValidator(valAddr, initialBalance) - suite.CreateDelegation(valAddr, moduleAccAddress, initialBalance) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - _, err := suite.Keeper.DerivativeFromTokens(suite.Ctx, valAddr, sdk.NewCoin("invalid", initialBalance)) - suite.ErrorIs(err, types.ErrInvalidDenom) - - derivatives, err := suite.Keeper.DerivativeFromTokens(suite.Ctx, valAddr, suite.NewBondCoin(initialBalance)) - suite.NoError(err) - expected := sdk.NewCoin(fmt.Sprintf("bkava-%s", valAddr), initialBalance) - suite.Equal(expected, derivatives) -} diff --git a/x/liquid/keeper/grpc_query.go b/x/liquid/keeper/grpc_query.go deleted file mode 100644 index 756feb61..00000000 --- a/x/liquid/keeper/grpc_query.go +++ /dev/null @@ -1,99 +0,0 @@ -package keeper - -import ( - "context" - "fmt" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - vestingexported "github.com/cosmos/cosmos-sdk/x/auth/vesting/exported" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/0glabs/0g-chain/x/liquid/types" -) - -type queryServer struct { - keeper Keeper -} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(k Keeper) types.QueryServer { - return &queryServer{keeper: k} -} - -var _ types.QueryServer = queryServer{} - -func (s queryServer) DelegatedBalance( - goCtx context.Context, - req *types.QueryDelegatedBalanceRequest, -) (*types.QueryDelegatedBalanceResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - delegator, err := sdk.AccAddressFromBech32(req.Delegator) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid delegator address: %s", err) - } - - delegated := s.getDelegatedBalance(ctx, delegator) - - bondDenom := s.keeper.stakingKeeper.BondDenom(ctx) - vesting := s.getVesting(ctx, delegator).AmountOf(bondDenom) - - vestingDelegated := sdk.MinInt(vesting, delegated) - vestedDelegated := delegated.Sub(vestingDelegated) - - res := types.QueryDelegatedBalanceResponse{ - Vested: sdk.NewCoin(bondDenom, vestedDelegated), - Vesting: sdk.NewCoin(bondDenom, vestingDelegated), - } - return &res, nil -} - -func (s queryServer) TotalSupply( - goCtx context.Context, - req *types.QueryTotalSupplyRequest, -) (*types.QueryTotalSupplyResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - totalValue, err := s.keeper.GetTotalDerivativeValue(ctx) - if err != nil { - return nil, err - } - - return &types.QueryTotalSupplyResponse{ - Height: ctx.BlockHeight(), - Result: []sdk.Coin{totalValue}, - }, nil -} - -func (s queryServer) getDelegatedBalance(ctx sdk.Context, delegator sdk.AccAddress) sdkmath.Int { - balance := sdk.ZeroDec() - - s.keeper.stakingKeeper.IterateDelegatorDelegations(ctx, delegator, func(delegation stakingtypes.Delegation) bool { - validator, found := s.keeper.stakingKeeper.GetValidator(ctx, delegation.GetValidatorAddr()) - if !found { - panic(fmt.Sprintf("validator %s for delegation not found", delegation.GetValidatorAddr())) - } - tokens := validator.TokensFromSharesTruncated(delegation.GetShares()) - balance = balance.Add(tokens) - - return false - }) - return balance.TruncateInt() -} - -func (s queryServer) getVesting(ctx sdk.Context, delegator sdk.AccAddress) sdk.Coins { - acc := s.keeper.accountKeeper.GetAccount(ctx, delegator) - if acc == nil { - // account doesn't exist so amount vesting is 0 - return nil - } - vestAcc, ok := acc.(vestingexported.VestingAccount) - if !ok { - // account is not vesting type, so amount vesting is 0 - return nil - } - return vestAcc.GetVestingCoins(ctx.BlockTime()) -} diff --git a/x/liquid/keeper/grpc_query_test.go b/x/liquid/keeper/grpc_query_test.go deleted file mode 100644 index 4ca92f86..00000000 --- a/x/liquid/keeper/grpc_query_test.go +++ /dev/null @@ -1,292 +0,0 @@ -package keeper_test - -import ( - "context" - "testing" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/liquid/keeper" - "github.com/0glabs/0g-chain/x/liquid/types" -) - -type grpcQueryTestSuite struct { - KeeperTestSuite - - queryClient types.QueryClient -} - -func (suite *grpcQueryTestSuite) SetupTest() { - suite.KeeperTestSuite.SetupTest() - - queryHelper := baseapp.NewQueryServerTestHelper(suite.Ctx, suite.App.InterfaceRegistry()) - types.RegisterQueryServer(queryHelper, keeper.NewQueryServerImpl(suite.Keeper)) - - suite.queryClient = types.NewQueryClient(queryHelper) -} - -func TestGrpcQueryTestSuite(t *testing.T) { - suite.Run(t, new(grpcQueryTestSuite)) -} - -func (suite *grpcQueryTestSuite) TestQueryDelegatedBalance() { - zeroResponse := &types.QueryDelegatedBalanceResponse{ - Vested: suite.NewBondCoin(sdk.ZeroInt()), - Vesting: suite.NewBondCoin(sdk.ZeroInt()), - } - - testCases := []struct { - name string - setup func() string - expectedRes *types.QueryDelegatedBalanceResponse - expectedErr error - }{ - { - name: "vesting account with stake less than vesting", - setup: func() string { - initBalance := suite.NewBondCoin(i(1e9)) - _, addrs := app.GeneratePrivKeyAddressPairs(2) - valAddr, delAddr := addrs[0], addrs[1] - - suite.CreateAccountWithAddress(valAddr, sdk.NewCoins(initBalance)) - - suite.CreateVestingAccountWithAddress(delAddr, sdk.NewCoins(initBalance), suite.NewBondCoins(initBalance.Amount.QuoRaw(2))) - - suite.CreateNewUnbondedValidator(sdk.ValAddress(valAddr), initBalance.Amount) - suite.CreateDelegation(sdk.ValAddress(valAddr), delAddr, initBalance.Amount.QuoRaw(4)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) // bond the validator - - return delAddr.String() - }, - expectedRes: &types.QueryDelegatedBalanceResponse{ - Vested: suite.NewBondCoin(sdk.ZeroInt()), - Vesting: suite.NewBondCoin(i(250e6)), - }, - }, - { - name: "vesting account with stake greater than vesting", - setup: func() string { - initBalance := suite.NewBondCoin(i(1e9)) - _, addrs := app.GeneratePrivKeyAddressPairs(2) - valAddr, delAddr := addrs[0], addrs[1] - - suite.CreateAccountWithAddress(valAddr, sdk.NewCoins(initBalance)) - - suite.CreateVestingAccountWithAddress(delAddr, sdk.NewCoins(initBalance), suite.NewBondCoins(initBalance.Amount.QuoRaw(2))) - - suite.CreateNewUnbondedValidator(sdk.ValAddress(valAddr), initBalance.Amount) - threeQuarters := initBalance.Amount.QuoRaw(4).MulRaw(3) - suite.CreateDelegation(sdk.ValAddress(valAddr), delAddr, threeQuarters) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) // bond the validator - - return delAddr.String() - }, - expectedRes: &types.QueryDelegatedBalanceResponse{ - Vested: suite.NewBondCoin(i(250e6)), - Vesting: suite.NewBondCoin(i(500e6)), - }, - }, - { - name: "no account returns zeros", - setup: func() string { - return "kava10wlnqzyss4accfqmyxwx5jy5x9nfkwh6qm7n4t" - }, - expectedRes: zeroResponse, - }, - { - name: "base account no delegations returns zeros", - setup: func() string { - acc := suite.CreateAccount(suite.NewBondCoins(i(1e9)), 0) - return acc.GetAddress().String() - }, - expectedRes: zeroResponse, - }, - { - name: "base account with delegations returns delegated", - setup: func() string { - initBalance := suite.NewBondCoin(i(1e9)) - val1Acc := suite.CreateAccount(sdk.NewCoins(initBalance), 0) - val2Acc := suite.CreateAccount(sdk.NewCoins(initBalance), 1) - delAcc := suite.CreateAccount(sdk.NewCoins(initBalance), 2) - - suite.CreateNewUnbondedValidator(val1Acc.GetAddress().Bytes(), initBalance.Amount) - suite.CreateNewUnbondedValidator(val2Acc.GetAddress().Bytes(), initBalance.Amount) - - suite.CreateDelegation(val1Acc.GetAddress().Bytes(), delAcc.GetAddress(), initBalance.Amount.QuoRaw(2)) - suite.CreateDelegation(val2Acc.GetAddress().Bytes(), delAcc.GetAddress(), initBalance.Amount.QuoRaw(2)) - - return delAcc.GetAddress().String() - }, - expectedRes: &types.QueryDelegatedBalanceResponse{ - Vested: suite.NewBondCoin(i(1e9)), - Vesting: suite.NewBondCoin(sdk.ZeroInt()), - }, - }, - { - name: "base account with delegations and unbonding delegations returns only delegations", - setup: func() string { - initBalance := suite.NewBondCoin(i(1e9)) - valAcc := suite.CreateAccount(sdk.NewCoins(initBalance), 0) - delAcc := suite.CreateAccount(sdk.NewCoins(initBalance), 1) - - suite.CreateNewUnbondedValidator(valAcc.GetAddress().Bytes(), initBalance.Amount) - suite.CreateDelegation(valAcc.GetAddress().Bytes(), delAcc.GetAddress(), initBalance.Amount) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) // bond the validator - - suite.CreateUnbondingDelegation(delAcc.GetAddress(), valAcc.GetAddress().Bytes(), initBalance.Amount.QuoRaw(2)) - - return delAcc.GetAddress().String() - }, - expectedRes: &types.QueryDelegatedBalanceResponse{ - Vested: suite.NewBondCoin(i(500e6)), - Vesting: suite.NewBondCoin(sdk.ZeroInt()), - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - address := tc.setup() - - res, err := suite.queryClient.DelegatedBalance( - context.Background(), - &types.QueryDelegatedBalanceRequest{ - Delegator: address, - }, - ) - suite.ErrorIs(err, tc.expectedErr) - if err == nil { - suite.Equal(tc.expectedRes, res) - } - }) - } -} - -func (suite *grpcQueryTestSuite) TestQueryTotalSupply() { - testCases := []struct { - name string - setup func() - expectedTotal sdkmath.Int - expectedErr error - }{ - { - name: "no liquid kava means no tvl", - setup: func() {}, - expectedTotal: sdk.ZeroInt(), - expectedErr: nil, - }, - { - name: "returns TVL from one bkava denom", - setup: func() { - initBalance := suite.NewBondCoin(i(1e9)) - valAcc := suite.CreateAccount(sdk.NewCoins(initBalance), 0) - delAcc := suite.CreateAccount(sdk.NewCoins(initBalance), 1) - - suite.CreateNewUnbondedValidator(valAcc.GetAddress().Bytes(), initBalance.Amount) - suite.CreateDelegation(valAcc.GetAddress().Bytes(), delAcc.GetAddress(), initBalance.Amount) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) // bond the validator - - _, err := suite.Keeper.MintDerivative( - suite.Ctx, - delAcc.GetAddress(), - valAcc.GetAddress().Bytes(), - initBalance, - ) - suite.Require().NoError(err) - }, - expectedTotal: i(1e9), - expectedErr: nil, - }, - { - name: "returns TVL from multiple bkava denoms", - setup: func() { - initBalance := suite.NewBondCoin(i(1e9)) - val1Acc := suite.CreateAccount(sdk.NewCoins(initBalance), 0) - val2Acc := suite.CreateAccount(sdk.NewCoins(initBalance), 1) - delAcc := suite.CreateAccount(sdk.NewCoins(initBalance.Add(initBalance)), 2) - - suite.CreateNewUnbondedValidator(val1Acc.GetAddress().Bytes(), initBalance.Amount) - suite.CreateDelegation(val1Acc.GetAddress().Bytes(), delAcc.GetAddress(), initBalance.Amount) - suite.CreateNewUnbondedValidator(val2Acc.GetAddress().Bytes(), initBalance.Amount) - suite.CreateDelegation(val2Acc.GetAddress().Bytes(), delAcc.GetAddress(), initBalance.Amount) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) // bond the validator - - _, err := suite.Keeper.MintDerivative(suite.Ctx, delAcc.GetAddress(), val1Acc.GetAddress().Bytes(), initBalance) - suite.Require().NoError(err) - _, err = suite.Keeper.MintDerivative(suite.Ctx, delAcc.GetAddress(), val2Acc.GetAddress().Bytes(), initBalance) - suite.Require().NoError(err) - }, - expectedTotal: i(2e9), - expectedErr: nil, - }, - { - name: "returns TVL from multiple delegators", - setup: func() { - initBalance := suite.NewBondCoin(i(1e9)) - valAcc := suite.CreateAccount(sdk.NewCoins(initBalance), 0) - del1Acc := suite.CreateAccount(sdk.NewCoins(initBalance), 1) - del2Acc := suite.CreateAccount(sdk.NewCoins(initBalance), 2) - - suite.CreateNewUnbondedValidator(valAcc.GetAddress().Bytes(), initBalance.Amount) - suite.CreateDelegation(valAcc.GetAddress().Bytes(), del1Acc.GetAddress(), initBalance.Amount) - suite.CreateDelegation(valAcc.GetAddress().Bytes(), del2Acc.GetAddress(), initBalance.Amount) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) // bond the validator - - _, err := suite.Keeper.MintDerivative(suite.Ctx, del1Acc.GetAddress(), valAcc.GetAddress().Bytes(), initBalance) - suite.Require().NoError(err) - _, err = suite.Keeper.MintDerivative(suite.Ctx, del2Acc.GetAddress(), valAcc.GetAddress().Bytes(), initBalance) - suite.Require().NoError(err) - }, - expectedTotal: i(2e9), - expectedErr: nil, - }, - { - name: "handles calculating tvl after slashing", - setup: func() { - initBalance := suite.NewBondCoin(i(1e9)) - val1Acc := suite.CreateAccount(sdk.NewCoins(initBalance), 0) - val2Acc := suite.CreateAccount(sdk.NewCoins(initBalance), 1) - delAcc := suite.CreateAccount(sdk.NewCoins(initBalance.Add(initBalance)), 2) - - suite.CreateNewUnbondedValidator(val1Acc.GetAddress().Bytes(), initBalance.Amount) - suite.CreateDelegation(val1Acc.GetAddress().Bytes(), delAcc.GetAddress(), initBalance.Amount) - suite.CreateNewUnbondedValidator(val2Acc.GetAddress().Bytes(), initBalance.Amount) - suite.CreateDelegation(val2Acc.GetAddress().Bytes(), delAcc.GetAddress(), initBalance.Amount) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) // bond the validator - - _, err := suite.Keeper.MintDerivative(suite.Ctx, delAcc.GetAddress(), val1Acc.GetAddress().Bytes(), initBalance) - suite.Require().NoError(err) - _, err = suite.Keeper.MintDerivative(suite.Ctx, delAcc.GetAddress(), val2Acc.GetAddress().Bytes(), initBalance) - suite.Require().NoError(err) - - suite.SlashValidator(val2Acc.GetAddress().Bytes(), d("0.1")) - }, - // delegation + (delegation * 90%) - expectedTotal: i(1e9).Add(i(1e9).MulRaw(90).QuoRaw(100)), - expectedErr: nil, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - tc.setup() - - res, err := suite.queryClient.TotalSupply( - context.Background(), - &types.QueryTotalSupplyRequest{}, - ) - - suite.ErrorIs(err, tc.expectedErr) - if err == nil { - suite.Equal(tc.expectedTotal, res.Result[0].Amount) - } - }) - } -} diff --git a/x/liquid/keeper/keeper.go b/x/liquid/keeper/keeper.go deleted file mode 100644 index 20b4dc85..00000000 --- a/x/liquid/keeper/keeper.go +++ /dev/null @@ -1,54 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/liquid/types" -) - -// Keeper struct for the liquid module. -type Keeper struct { - cdc codec.Codec - - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - stakingKeeper types.StakingKeeper - distributionKeeper types.DistributionKeeper - - derivativeDenom string -} - -// NewKeeper returns a new keeper for the liquid module. -func NewKeeper( - cdc codec.Codec, - ak types.AccountKeeper, bk types.BankKeeper, sk types.StakingKeeper, dk types.DistributionKeeper, - derivativeDenom string, -) Keeper { - - return Keeper{ - cdc: cdc, - accountKeeper: ak, - bankKeeper: bk, - stakingKeeper: sk, - distributionKeeper: dk, - derivativeDenom: derivativeDenom, - } -} - -// NewDefaultKeeper returns a new keeper for the liquid module with default values. -func NewDefaultKeeper( - cdc codec.Codec, - ak types.AccountKeeper, bk types.BankKeeper, sk types.StakingKeeper, dk types.DistributionKeeper, -) Keeper { - - return NewKeeper(cdc, ak, bk, sk, dk, types.DefaultDerivativeDenom) -} - -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) -} diff --git a/x/liquid/keeper/keeper_test.go b/x/liquid/keeper/keeper_test.go deleted file mode 100644 index 4fdc41c0..00000000 --- a/x/liquid/keeper/keeper_test.go +++ /dev/null @@ -1,251 +0,0 @@ -package keeper_test - -import ( - "fmt" - "reflect" - "testing" - - sdkmath "cosmossdk.io/math" - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/liquid/keeper" -) - -// Test suite used for all keeper tests -type KeeperTestSuite struct { - suite.Suite - App app.TestApp - Ctx sdk.Context - Keeper keeper.Keeper - BankKeeper bankkeeper.Keeper - StakingKeeper *stakingkeeper.Keeper -} - -// The default state used by each test -func (suite *KeeperTestSuite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - tApp.InitializeFromGenesisStates() - - suite.App = tApp - suite.Ctx = ctx - suite.Keeper = tApp.GetLiquidKeeper() - suite.StakingKeeper = tApp.GetStakingKeeper() - suite.BankKeeper = tApp.GetBankKeeper() -} - -// CreateAccount creates a new account (with a fixed address) from the provided balance. -func (suite *KeeperTestSuite) CreateAccount(initialBalance sdk.Coins, index int) authtypes.AccountI { - _, addrs := app.GeneratePrivKeyAddressPairs(index + 1) - - return suite.CreateAccountWithAddress(addrs[index], initialBalance) -} - -// CreateAccount creates a new account from the provided balance and address -func (suite *KeeperTestSuite) CreateAccountWithAddress(addr sdk.AccAddress, initialBalance sdk.Coins) authtypes.AccountI { - ak := suite.App.GetAccountKeeper() - - acc := ak.NewAccountWithAddress(suite.Ctx, addr) - ak.SetAccount(suite.Ctx, acc) - - err := suite.App.FundAccount(suite.Ctx, acc.GetAddress(), initialBalance) - suite.Require().NoError(err) - - return acc -} - -// CreateVestingAccount creates a new vesting account. `vestingBalance` should be a fraction of `initialBalance`. -func (suite *KeeperTestSuite) CreateVestingAccountWithAddress(addr sdk.AccAddress, initialBalance sdk.Coins, vestingBalance sdk.Coins) authtypes.AccountI { - if vestingBalance.IsAnyGT(initialBalance) { - panic("vesting balance must be less than initial balance") - } - acc := suite.CreateAccountWithAddress(addr, initialBalance) - bacc := acc.(*authtypes.BaseAccount) - - periods := vestingtypes.Periods{ - vestingtypes.Period{ - Length: 31556952, - Amount: vestingBalance, - }, - } - vacc := vestingtypes.NewPeriodicVestingAccount(bacc, vestingBalance, suite.Ctx.BlockTime().Unix(), periods) - suite.App.GetAccountKeeper().SetAccount(suite.Ctx, vacc) - return vacc -} - -// AddCoinsToModule adds coins to the a module account, creating it if it doesn't exist. -func (suite *KeeperTestSuite) AddCoinsToModule(module string, amount sdk.Coins) { - err := suite.App.FundModuleAccount(suite.Ctx, module, amount) - suite.Require().NoError(err) -} - -// AccountBalanceEqual checks if an account has the specified coins. -func (suite *KeeperTestSuite) AccountBalanceEqual(addr sdk.AccAddress, coins sdk.Coins) { - balance := suite.BankKeeper.GetAllBalances(suite.Ctx, addr) - suite.Truef(coins.IsEqual(balance), "expected account balance to equal coins %s, but got %s", coins, balance) -} - -func (suite *KeeperTestSuite) deliverMsgCreateValidator(ctx sdk.Context, address sdk.ValAddress, selfDelegation sdk.Coin) error { - msg, err := stakingtypes.NewMsgCreateValidator( - address, - ed25519.GenPrivKey().PubKey(), - selfDelegation, - stakingtypes.Description{}, - stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - sdkmath.NewInt(1e6), - ) - if err != nil { - return err - } - - msgServer := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - _, err = msgServer.CreateValidator(sdk.WrapSDKContext(suite.Ctx), msg) - return err -} - -// NewBondCoin creates a Coin with the current staking denom. -func (suite *KeeperTestSuite) NewBondCoin(amount sdkmath.Int) sdk.Coin { - stakingDenom := suite.StakingKeeper.BondDenom(suite.Ctx) - return sdk.NewCoin(stakingDenom, amount) -} - -// NewBondCoins creates Coins with the current staking denom. -func (suite *KeeperTestSuite) NewBondCoins(amount sdkmath.Int) sdk.Coins { - return sdk.NewCoins(suite.NewBondCoin(amount)) -} - -// CreateNewUnbondedValidator creates a new validator in the staking module. -// New validators are unbonded until the end blocker is run. -func (suite *KeeperTestSuite) CreateNewUnbondedValidator(addr sdk.ValAddress, selfDelegation sdkmath.Int) stakingtypes.Validator { - // Create a validator - err := suite.deliverMsgCreateValidator(suite.Ctx, addr, suite.NewBondCoin(selfDelegation)) - suite.Require().NoError(err) - - // New validators are created in an unbonded state. Note if the end blocker is run later this validator could become bonded. - - validator, found := suite.StakingKeeper.GetValidator(suite.Ctx, addr) - suite.Require().True(found) - return validator -} - -// SlashValidator burns tokens staked in a validator. new_tokens = old_tokens * (1-slashFraction) -func (suite *KeeperTestSuite) SlashValidator(addr sdk.ValAddress, slashFraction sdk.Dec) { - validator, found := suite.StakingKeeper.GetValidator(suite.Ctx, addr) - suite.Require().True(found) - consAddr, err := validator.GetConsAddr() - suite.Require().NoError(err) - - // Assume infraction was at current height. Note unbonding delegations and redelegations are only slashed if created after - // the infraction height so none will be slashed. - infractionHeight := suite.Ctx.BlockHeight() - - power := suite.StakingKeeper.TokensToConsensusPower(suite.Ctx, validator.GetTokens()) - - suite.StakingKeeper.Slash(suite.Ctx, consAddr, infractionHeight, power, slashFraction) -} - -// CreateDelegation delegates tokens to a validator. -func (suite *KeeperTestSuite) CreateDelegation(valAddr sdk.ValAddress, delegator sdk.AccAddress, amount sdkmath.Int) sdk.Dec { - stakingDenom := suite.StakingKeeper.BondDenom(suite.Ctx) - msg := stakingtypes.NewMsgDelegate( - delegator, - valAddr, - sdk.NewCoin(stakingDenom, amount), - ) - - msgServer := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - _, err := msgServer.Delegate(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - - del, found := suite.StakingKeeper.GetDelegation(suite.Ctx, delegator, valAddr) - suite.Require().True(found) - return del.Shares -} - -// CreateRedelegation undelegates tokens from one validator and delegates to another. -func (suite *KeeperTestSuite) CreateRedelegation(delegator sdk.AccAddress, fromValidator, toValidator sdk.ValAddress, amount sdkmath.Int) { - stakingDenom := suite.StakingKeeper.BondDenom(suite.Ctx) - msg := stakingtypes.NewMsgBeginRedelegate( - delegator, - fromValidator, - toValidator, - sdk.NewCoin(stakingDenom, amount), - ) - - msgServer := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - _, err := msgServer.BeginRedelegate(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) -} - -// CreateUnbondingDelegation undelegates tokens from a validator. -func (suite *KeeperTestSuite) CreateUnbondingDelegation(delegator sdk.AccAddress, validator sdk.ValAddress, amount sdkmath.Int) { - stakingDenom := suite.StakingKeeper.BondDenom(suite.Ctx) - msg := stakingtypes.NewMsgUndelegate( - delegator, - validator, - sdk.NewCoin(stakingDenom, amount), - ) - msgServer := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - _, err := msgServer.Undelegate(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) -} - -// DelegationSharesEqual checks if a delegation has the specified shares. -// It expects delegations with zero shares to not be stored in state. -func (suite *KeeperTestSuite) DelegationSharesEqual(valAddr sdk.ValAddress, delegator sdk.AccAddress, shares sdk.Dec) bool { - del, found := suite.StakingKeeper.GetDelegation(suite.Ctx, delegator, valAddr) - - if shares.IsZero() { - return suite.Falsef(found, "expected delegator to not be found, got %s shares", del.Shares) - } else { - res := suite.True(found, "expected delegator to be found") - return res && suite.Truef(shares.Equal(del.Shares), "expected %s delegator shares but got %s", shares, del.Shares) - } -} - -// EventsContains asserts that the expected event is in the provided events -func (suite *KeeperTestSuite) EventsContains(events sdk.Events, expectedEvent sdk.Event) { - foundMatch := false - for _, event := range events { - if event.Type == expectedEvent.Type { - if reflect.DeepEqual(attrsToMap(expectedEvent.Attributes), attrsToMap(event.Attributes)) { - foundMatch = true - } - } - } - - suite.True(foundMatch, fmt.Sprintf("event of type %s not found or did not match", expectedEvent.Type)) -} - -// EventsDoNotContainType asserts that the provided events do contain an event of a certain type. -func (suite *KeeperTestSuite) EventsDoNotContainType(events sdk.Events, eventType string) { - for _, event := range events { - suite.Falsef(event.Type == eventType, "found unexpected event %s", eventType) - } -} - -func attrsToMap(attrs []abci.EventAttribute) []sdk.Attribute { - out := []sdk.Attribute{} - - for _, attr := range attrs { - out = append(out, sdk.NewAttribute(string(attr.Key), string(attr.Value))) - } - - return out -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} diff --git a/x/liquid/keeper/msg_server.go b/x/liquid/keeper/msg_server.go deleted file mode 100644 index 885ee243..00000000 --- a/x/liquid/keeper/msg_server.go +++ /dev/null @@ -1,84 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/liquid/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the liquid MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -// MintDerivative handles MintDerivative msgs. -func (k msgServer) MintDerivative(goCtx context.Context, msg *types.MsgMintDerivative) (*types.MsgMintDerivativeResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - validator, err := sdk.ValAddressFromBech32(msg.Validator) - if err != nil { - return nil, err - } - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - mintedDerivative, err := k.keeper.MintDerivative(ctx, sender, validator, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - ), - ) - - return &types.MsgMintDerivativeResponse{ - Received: mintedDerivative, - }, nil -} - -// BurnDerivative handles BurnDerivative msgs. -func (k msgServer) BurnDerivative(goCtx context.Context, msg *types.MsgBurnDerivative) (*types.MsgBurnDerivativeResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - validator, err := sdk.ValAddressFromBech32(msg.Validator) - if err != nil { - return nil, err - } - - sharesReceived, err := k.keeper.BurnDerivative(ctx, sender, validator, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - ), - ) - return &types.MsgBurnDerivativeResponse{ - Received: sharesReceived, - }, nil -} diff --git a/x/liquid/keeper/staking.go b/x/liquid/keeper/staking.go deleted file mode 100644 index 21e55721..00000000 --- a/x/liquid/keeper/staking.go +++ /dev/null @@ -1,110 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - "github.com/0glabs/0g-chain/x/liquid/types" -) - -// TransferDelegation moves some delegation shares between addresses, while keeping the same validator. -// -// Internally shares are unbonded, tokens moved then bonded again. This limits only vested tokens from being transferred. -// The sending delegation must not have any active redelegations. -// A validator cannot reduce self delegated shares below its min self delegation. -// Attempting to transfer zero shares will error. -func (k Keeper) TransferDelegation(ctx sdk.Context, valAddr sdk.ValAddress, fromDelegator, toDelegator sdk.AccAddress, shares sdk.Dec) (sdk.Dec, error) { - // Redelegations link a delegation to it's previous validator so slashes are propagated to the new validator. - // If the delegation is transferred to a new owner, the redelegation object must be updated. - // For expediency all transfers with redelegations are blocked. - if k.stakingKeeper.HasReceivingRedelegation(ctx, fromDelegator, valAddr) { - return sdk.Dec{}, types.ErrRedelegationsNotCompleted - } - - if shares.IsNil() || shares.LT(sdk.ZeroDec()) { - return sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, "nil or negative shares") - } - if shares.Equal(sdk.ZeroDec()) { - // Block 0 transfers to reduce edge cases. - return sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, "zero shares") - } - - fromDelegation, found := k.stakingKeeper.GetDelegation(ctx, fromDelegator, valAddr) - if !found { - return sdk.Dec{}, types.ErrNoDelegatorForAddress - } - validator, found := k.stakingKeeper.GetValidator(ctx, valAddr) - if !found { - return sdk.Dec{}, types.ErrNoValidatorFound - } - // Prevent validators from reducing their self delegation below the min. - isValidatorOperator := fromDelegator.Equals(valAddr) - if isValidatorOperator { - if isBelowMinSelfDelegation(validator, fromDelegation.Shares.Sub(shares)) { - return sdk.Dec{}, types.ErrSelfDelegationBelowMinimum - } - } - - returnAmount, err := k.fastUndelegate(ctx, valAddr, fromDelegator, shares) - if err != nil { - return sdk.Dec{}, err - } - returnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount)) - - if err := k.bankKeeper.SendCoins(ctx, fromDelegator, toDelegator, returnCoins); err != nil { - return sdk.Dec{}, err - } - receivedShares, err := k.delegateFromAccount(ctx, valAddr, toDelegator, returnAmount) - if err != nil { - return sdk.Dec{}, err - } - - return receivedShares, nil -} - -// isBelowMinSelfDelegation check if the supplied shares, converted to tokens, are under the validator's min_self_delegation. -func isBelowMinSelfDelegation(validator stakingtypes.ValidatorI, shares sdk.Dec) bool { - return validator.TokensFromShares(shares).TruncateInt().LT(validator.GetMinSelfDelegation()) -} - -// fastUndelegate undelegates shares from a validator skipping the unbonding period and not creating any unbonding delegations. -func (k Keeper) fastUndelegate(ctx sdk.Context, valAddr sdk.ValAddress, delegator sdk.AccAddress, shares sdk.Dec) (sdkmath.Int, error) { - validator, found := k.stakingKeeper.GetValidator(ctx, valAddr) - if !found { - return sdkmath.Int{}, types.ErrNoDelegatorForAddress - } - - returnAmount, err := k.stakingKeeper.Unbond(ctx, delegator, valAddr, shares) - if err != nil { - return sdkmath.Int{}, err - } - returnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount)) - - // transfer the validator tokens to the not bonded pool - if validator.IsBonded() { - if err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, returnCoins); err != nil { - panic(err) - } - } - - if err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, stakingtypes.NotBondedPoolName, delegator, returnCoins); err != nil { - return sdkmath.Int{}, err - } - return returnAmount, nil -} - -// delegateFromAccount delegates to a validator from an account (vs redelegating from an existing delegation) -func (k Keeper) delegateFromAccount(ctx sdk.Context, valAddr sdk.ValAddress, delegator sdk.AccAddress, amount sdkmath.Int) (sdk.Dec, error) { - validator, found := k.stakingKeeper.GetValidator(ctx, valAddr) - if !found { - return sdk.Dec{}, types.ErrNoValidatorFound - } - // source tokens are from an account, so subtractAccount true and tokenSrc unbonded - newShares, err := k.stakingKeeper.Delegate(ctx, delegator, amount, stakingtypes.Unbonded, validator, true) - if err != nil { - return sdk.Dec{}, err - } - return newShares, nil -} diff --git a/x/liquid/keeper/staking_test.go b/x/liquid/keeper/staking_test.go deleted file mode 100644 index 720224da..00000000 --- a/x/liquid/keeper/staking_test.go +++ /dev/null @@ -1,379 +0,0 @@ -package keeper_test - -import ( - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - 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/cosmos/cosmos-sdk/x/staking" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/liquid/types" -) - -var ( - // d is an alias for sdk.MustNewDecFromStr - d = sdk.MustNewDecFromStr - // i is an alias for sdkmath.NewInt - i = sdkmath.NewInt - // c is an alias for sdk.NewInt64Coin - c = sdk.NewInt64Coin -) - -func (suite *KeeperTestSuite) TestTransferDelegation_ValidatorStates() { - _, addrs := app.GeneratePrivKeyAddressPairs(3) - valAccAddr, fromDelegator, toDelegator := addrs[0], addrs[1], addrs[2] - valAddr := sdk.ValAddress(valAccAddr) - - initialBalance := i(1e9) - - notBondedModAddr := authtypes.NewModuleAddress(stakingtypes.NotBondedPoolName) - bondedModAddr := authtypes.NewModuleAddress(stakingtypes.BondedPoolName) - - testCases := []struct { - name string - createValidator func() (delegatorShares sdk.Dec, err error) - }{ - { - name: "bonded validator", - createValidator: func() (sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, initialBalance) - delegatorShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - - // Run end blocker to update validator state to bonded. - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - return delegatorShares, nil - }, - }, - { - name: "unbonded validator", - createValidator: func() (sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, initialBalance) - delegatorShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - - // Don't run end blocker, new validators are by default unbonded. - return delegatorShares, nil - }, - }, - { - name: "ubonding (jailed) validator", - createValidator: func() (sdk.Dec, error) { - val := suite.CreateNewUnbondedValidator(valAddr, initialBalance) - delegatorShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - - // Run end blocker to update validator state to bonded. - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - // Jail and run end blocker to transition validator to unbonding. - consAddr, err := val.GetConsAddr() - if err != nil { - return sdk.Dec{}, err - } - suite.StakingKeeper.Jail(suite.Ctx, consAddr) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - return delegatorShares, nil - }, - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(i(1e9))) - suite.CreateAccountWithAddress(fromDelegator, suite.NewBondCoins(i(1e9))) - - fromDelegationShares, err := tc.createValidator() - suite.Require().NoError(err) - - validator, found := suite.StakingKeeper.GetValidator(suite.Ctx, valAddr) - suite.Require().True(found) - notBondedBalance := suite.BankKeeper.GetAllBalances(suite.Ctx, notBondedModAddr) - bondedBalance := suite.BankKeeper.GetAllBalances(suite.Ctx, bondedModAddr) - - shares := d("1000") - - _, err = suite.Keeper.TransferDelegation(suite.Ctx, valAddr, fromDelegator, toDelegator, shares) - suite.Require().NoError(err) - - // Transferring a delegation should move shares, and leave the validator and pool balances the same. - - suite.DelegationSharesEqual(valAddr, fromDelegator, fromDelegationShares.Sub(shares)) - suite.DelegationSharesEqual(valAddr, toDelegator, shares) // also creates new delegation - - validatorAfter, found := suite.StakingKeeper.GetValidator(suite.Ctx, valAddr) - suite.Require().True(found) - suite.Equal(validator.GetTokens(), validatorAfter.GetTokens()) - suite.Equal(validator.GetDelegatorShares(), validatorAfter.GetDelegatorShares()) - suite.Equal(validator.GetStatus(), validatorAfter.GetStatus()) - - suite.AccountBalanceEqual(notBondedModAddr, notBondedBalance) - suite.AccountBalanceEqual(bondedModAddr, bondedBalance) - }) - } -} - -func (suite *KeeperTestSuite) TestTransferDelegation_Shares() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, fromDelegator, toDelegator := addrs[0], addrs[1], addrs[2] - valAddr := sdk.ValAddress(valAccAddr) - - initialBalance := i(1e12) - - testCases := []struct { - name string - createDelegations func() (fromDelegatorShares, toDelegatorShares sdk.Dec, err error) - shares sdk.Dec - expectReceived sdk.Dec - expectedErr error - }{ - { - name: "negative shares cannot be transferred", - createDelegations: func() (sdk.Dec, sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - // Run end blocker to update validator state to bonded. - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - return fromDelegationShares, sdk.ZeroDec(), nil - }, - shares: d("-1.0"), - expectedErr: types.ErrUntransferableShares, - }, - { - name: "nil shares cannot be transferred", - createDelegations: func() (sdk.Dec, sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - return fromDelegationShares, sdk.ZeroDec(), nil - }, - shares: sdk.Dec{}, - expectedErr: types.ErrUntransferableShares, - }, - { - name: "0 shares cannot be transferred", - createDelegations: func() (sdk.Dec, sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - toDelegationShares := suite.CreateDelegation(valAddr, toDelegator, i(2e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - return fromDelegationShares, toDelegationShares, nil - }, - shares: sdk.ZeroDec(), - expectedErr: types.ErrUntransferableShares, - }, - { - name: "all shares can be transferred", - createDelegations: func() (sdk.Dec, sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - toDelegationShares := suite.CreateDelegation(valAddr, toDelegator, i(2e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - return fromDelegationShares, toDelegationShares, nil - }, - shares: d("1000000000.0"), - expectReceived: d("1000000000.0"), - }, - { - name: "excess shares cannot be transferred", - createDelegations: func() (sdk.Dec, sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - return fromDelegationShares, sdk.ZeroDec(), nil - }, - shares: d("1000000000.000000000000000001"), - expectedErr: stakingtypes.ErrNotEnoughDelegationShares, - }, - { - name: "shares can be transferred to a non existent delegation", - createDelegations: func() (sdk.Dec, sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - return fromDelegationShares, sdk.ZeroDec(), nil - }, - shares: d("500000000.0"), - expectReceived: d("500000000.0"), - }, - { - name: "shares cannot be transferred from a non existent delegation", - createDelegations: func() (sdk.Dec, sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - return sdk.ZeroDec(), sdk.ZeroDec(), nil - }, - shares: d("500000000.0"), - expectedErr: types.ErrNoDelegatorForAddress, - }, - { - name: "slashed validator shares can be transferred", - createDelegations: func() (sdk.Dec, sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - suite.SlashValidator(valAddr, d("0.05")) - - return fromDelegationShares, sdk.ZeroDec(), nil - }, - shares: d("500000000.0"), - expectReceived: d("500000000.0"), - }, - { - name: "zero shares received when transfer < 1 token", - createDelegations: func() (sdk.Dec, sdk.Dec, error) { - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(valAddr, fromDelegator, i(1e9)) - toDelegationShares := suite.CreateDelegation(valAddr, toDelegator, i(1e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - // make 1 share worth more than 1 token - suite.SlashValidator(valAddr, d("0.05")) - - return fromDelegationShares, toDelegationShares, nil - }, - shares: d("1.0"), // send 1 share (truncates to zero tokens) - expectReceived: d("0.0"), - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(initialBalance)) - suite.CreateAccountWithAddress(fromDelegator, suite.NewBondCoins(initialBalance)) - suite.CreateAccountWithAddress(toDelegator, suite.NewBondCoins(initialBalance)) - - fromDelegationShares, toDelegationShares, err := tc.createDelegations() - suite.Require().NoError(err) - validator, found := suite.StakingKeeper.GetValidator(suite.Ctx, valAddr) - suite.Require().True(found) - - _, err = suite.Keeper.TransferDelegation(suite.Ctx, valAddr, fromDelegator, toDelegator, tc.shares) - - if tc.expectedErr != nil { - suite.ErrorIs(err, tc.expectedErr) - return - } - - suite.NoError(err) - suite.DelegationSharesEqual(valAddr, fromDelegator, fromDelegationShares.Sub(tc.shares)) - suite.DelegationSharesEqual(valAddr, toDelegator, toDelegationShares.Add(tc.expectReceived)) - - validatorAfter, found := suite.StakingKeeper.GetValidator(suite.Ctx, valAddr) - suite.Require().True(found) - // total tokens should not change - suite.Equal(validator.GetTokens(), validatorAfter.GetTokens()) - // but total shares can differ - suite.Equal( - validator.GetDelegatorShares().Sub(tc.shares).Add(tc.expectReceived), - validatorAfter.GetDelegatorShares(), - ) - }) - } -} - -func (suite *KeeperTestSuite) TestTransferDelegation_RedelegationsForbidden() { - _, addrs := app.GeneratePrivKeyAddressPairs(4) - val1AccAddr, val2AccAddr, fromDelegator, toDelegator := addrs[0], addrs[1], addrs[2], addrs[3] - val1Addr := sdk.ValAddress(val1AccAddr) - val2Addr := sdk.ValAddress(val2AccAddr) - - initialBalance := i(1e12) - - suite.CreateAccountWithAddress(val1AccAddr, suite.NewBondCoins(initialBalance)) - suite.CreateAccountWithAddress(val2AccAddr, suite.NewBondCoins(initialBalance)) - suite.CreateAccountWithAddress(fromDelegator, suite.NewBondCoins(initialBalance)) - - // create bonded validator 1 with a delegation - suite.CreateNewUnbondedValidator(val1Addr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(val1Addr, fromDelegator, i(1e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - // create validator 2 and redelegate to it - suite.CreateNewUnbondedValidator(val2Addr, i(1e9)) - suite.CreateRedelegation(fromDelegator, val1Addr, val2Addr, i(1e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - _, err := suite.Keeper.TransferDelegation(suite.Ctx, val2Addr, fromDelegator, toDelegator, fromDelegationShares) - suite.ErrorIs(err, types.ErrRedelegationsNotCompleted) - suite.DelegationSharesEqual(val2Addr, fromDelegator, fromDelegationShares) - suite.DelegationSharesEqual(val2Addr, toDelegator, sdk.ZeroDec()) -} - -func (suite *KeeperTestSuite) TestTransferDelegation_CompliesWithMinSelfDelegation() { - _, addrs := app.GeneratePrivKeyAddressPairs(4) - valAccAddr, toDelegator := addrs[0], addrs[1] - valAddr := sdk.ValAddress(valAccAddr) - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(i(1e12))) - - // create bonded validator with minimum delegated - minSelfDelegation := i(1e9) - delegation := suite.NewBondCoin(i(1e9)) - msg, err := stakingtypes.NewMsgCreateValidator( - valAddr, - ed25519.GenPrivKey().PubKey(), - delegation, - stakingtypes.Description{}, - stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - minSelfDelegation, - ) - suite.Require().NoError(err) - - msgServer := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - _, err = msgServer.CreateValidator(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - _, err = suite.Keeper.TransferDelegation(suite.Ctx, valAddr, valAccAddr, toDelegator, d("0.000000000000000001")) - suite.ErrorIs(err, types.ErrSelfDelegationBelowMinimum) - suite.DelegationSharesEqual(valAddr, valAccAddr, sdk.NewDecFromInt(delegation.Amount)) -} - -func (suite *KeeperTestSuite) TestTransferDelegation_CanTransferVested() { - _, addrs := app.GeneratePrivKeyAddressPairs(4) - valAccAddr, fromDelegator, toDelegator := addrs[0], addrs[1], addrs[2] - valAddr := sdk.ValAddress(valAccAddr) - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(i(1e9))) - suite.CreateVestingAccountWithAddress(fromDelegator, suite.NewBondCoins(i(2e9)), suite.NewBondCoins(i(1e9))) - - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - fromDelegationShares := suite.CreateDelegation(valAddr, fromDelegator, i(2e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - shares := d("1000000000.0") - _, err := suite.Keeper.TransferDelegation(suite.Ctx, valAddr, fromDelegator, toDelegator, shares) - suite.NoError(err) - suite.DelegationSharesEqual(valAddr, fromDelegator, fromDelegationShares.Sub(shares)) - suite.DelegationSharesEqual(valAddr, toDelegator, shares) -} - -func (suite *KeeperTestSuite) TestTransferDelegation_CannotTransferVesting() { - _, addrs := app.GeneratePrivKeyAddressPairs(4) - valAccAddr, fromDelegator, toDelegator := addrs[0], addrs[1], addrs[2] - valAddr := sdk.ValAddress(valAccAddr) - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(i(1e9))) - suite.CreateVestingAccountWithAddress(fromDelegator, suite.NewBondCoins(i(2e9)), suite.NewBondCoins(i(1e9))) - - suite.CreateNewUnbondedValidator(valAddr, i(1e9)) - suite.CreateDelegation(valAddr, fromDelegator, i(2e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - - _, err := suite.Keeper.TransferDelegation(suite.Ctx, valAddr, fromDelegator, toDelegator, d("1000000001.0")) - suite.ErrorIs(err, sdkerrors.ErrInsufficientFunds) -} diff --git a/x/liquid/module.go b/x/liquid/module.go deleted file mode 100644 index ab65c1cf..00000000 --- a/x/liquid/module.go +++ /dev/null @@ -1,125 +0,0 @@ -package liquid - -import ( - "context" - "encoding/json" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/0glabs/0g-chain/x/liquid/client/cli" - "github.com/0glabs/0g-chain/x/liquid/keeper" - "github.com/0glabs/0g-chain/x/liquid/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name get module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(_ codec.JSONCodec) json.RawMessage { - return []byte("{}") -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(_ codec.JSONCodec, _ client.TxEncodingConfig, _ json.RawMessage) error { - return nil -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// GetTxCmd returns the root tx command for the module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -//____________________________________________________________________________ - -// AppModule app module type -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - } -} - -// Name module name -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// RegisterInvariants register module invariants -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return 1 -} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) -} - -// InitGenesis module init-genesis -func (am AppModule) InitGenesis(_ sdk.Context, _ codec.JSONCodec, _ json.RawMessage) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} - -// ExportGenesis module export genesis -func (am AppModule) ExportGenesis(_ sdk.Context, cdc codec.JSONCodec) json.RawMessage { - return am.DefaultGenesis(cdc) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - -// EndBlock module end-block -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/liquid/spec/01_concepts.md b/x/liquid/spec/01_concepts.md deleted file mode 100644 index e6798dc6..00000000 --- a/x/liquid/spec/01_concepts.md +++ /dev/null @@ -1,7 +0,0 @@ - - -# Concepts - -This module is responsible for the minting and burning of liquid staking receipt tokens, collectively referred to as `bkava`. Delegated kava can be converted to delegator-specific `bkava`. Ie, 100 KAVA delegated to validator `kavavaloper123` can be converted to 100 `bkava-kavavaloper123`. Similarly, 100 `bkava-kavavaloper123` can be converted back to a delegation of 100 KAVA to `kavavaloper123`. In this design, all validators can permissionlessly participate in liquid staking while users retain the delegator specific slashing risk and voting rights of their original validator. Note that because each `bkava` denom is validator specific, this module does not specify a fungibility mechanism for `bkava` denoms. \ No newline at end of file diff --git a/x/liquid/spec/02_state.md b/x/liquid/spec/02_state.md deleted file mode 100644 index cff1c133..00000000 --- a/x/liquid/spec/02_state.md +++ /dev/null @@ -1,16 +0,0 @@ - - -# State - -## Module Account -The liquid module defines a module account with name `liquid` that has `Minter` and `Burner` module account permissions. The associated bech32 account address is `kava1gggszchqvw2l65my03mak6q5qfhz9cn2g0px29`. - -## Genesis state - -The liquid module does not require any module specific genesis state. - -## Store - -The liquid module does not store any module specific data. All `bkava` token receipts are minted directly to the delegators account, and the delegation object is transferred to the liquid module account. \ No newline at end of file diff --git a/x/liquid/spec/03_messages.md b/x/liquid/spec/03_messages.md deleted file mode 100644 index e12b68c0..00000000 --- a/x/liquid/spec/03_messages.md +++ /dev/null @@ -1,79 +0,0 @@ - - -# Messages - -`bkava` is minted using `MsgMintDerivative`. - - -```go -// MsgMintDerivative defines the Msg/MintDerivative request type. -type MsgMintDerivative struct { - // sender is the owner of the delegation to be converted - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // validator is the validator of the delegation to be converted - Validator string `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator,omitempty"` - // amount is the quantity of staked assets to be converted - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} -``` - -### Actions - -* converts an existing delegation into bkava tokens -* delegation is transferred from the sender to a module account -* validator specific bkava are minted and sent to the sender - -### Example: - -```jsonc -{ - // user who owns the delegation - "sender": "kava10wlnqzyss4accfqmyxwx5jy5x9nfkwh6qm7n4t", - // validator the user has delegated to - "validator": "kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42", - // amount of staked ukava to be converted into bkava - "amount": { - "amount": "1000000000", - "denom": "ukava" - } -} -``` - -`bkava` can be burned using `MsgBurnDerivative`. - -```go -// MsgBurnDerivative defines the Msg/BurnDerivative request type. -type MsgBurnDerivative struct { - // sender is the owner of the derivatives to be converted - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // validator is the validator of the derivatives to be converted - Validator string `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator,omitempty"` - // amount is the quantity of derivatives to be converted - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} -``` - -### Actions - -* converts bkava tokens into a delegation -* bkava is burned -* a delegation equal to number of bkava is transferred to user - - -### Example - -```jsonc -{ - // user who owns the bkava - "sender": "kava10wlnqzyss4accfqmyxwx5jy5x9nfkwh6qm7n4t", - // the amount of bkava the user wants to convert back into normal staked kava - "amount": { - "amount": "1234000000", - "denom": "bkava-kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42" - }, - // the validator behind the bkava, this address must match the one embedded in the bkava denom above - "validator": "kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42" -} -``` diff --git a/x/liquid/spec/04_events.md b/x/liquid/spec/04_events.md deleted file mode 100644 index 07d7a086..00000000 --- a/x/liquid/spec/04_events.md +++ /dev/null @@ -1,25 +0,0 @@ - - -# Events - -The `x/liquid` module emits the following events: - -## MsgMintDerivative - -| Type | Attribute Key | Attribute Value | -| --------------- | ----------------- | ------------------ | -| mint_derivative | delegator | `{delegator address}` | -| mint_derivative | validator | `{validator address}` | -| mint_derivative | amount | `{amount}` | -| mint_derivative | shares_transferred| `{shares transferred}`| - -## MsgBurnDerivative - -| Type | Attribute Key | Attribute Value | -| --------------- | ----------------- | ------------------ | -| burn_derivative | delegator | `{delegator address}` | -| burn_derivative | validator | `{validator address}` | -| burn_derivative | amount | `{amount}` | -| burn_derivative | shares_transferred| `{shares transferred}`| \ No newline at end of file diff --git a/x/liquid/spec/05_params.md b/x/liquid/spec/05_params.md deleted file mode 100644 index 5df5c058..00000000 --- a/x/liquid/spec/05_params.md +++ /dev/null @@ -1,7 +0,0 @@ - - -# Parameters - -The liquid module has no parameters. \ No newline at end of file diff --git a/x/liquid/types/codec.go b/x/liquid/types/codec.go deleted file mode 100644 index adaea192..00000000 --- a/x/liquid/types/codec.go +++ /dev/null @@ -1,41 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgMintDerivative{}, "liquid/MsgMintDerivative", nil) - cdc.RegisterConcrete(&MsgBurnDerivative{}, "liquid/MsgBurnDerivative", nil) -} - -// RegisterInterfaces registers proto messages under their interfaces for unmarshalling, -// in addition to registering the msg service for handling tx msgs. -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgMintDerivative{}, - &MsgBurnDerivative{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/liquid/types/common_test.go b/x/liquid/types/common_test.go deleted file mode 100644 index 4cfbb221..00000000 --- a/x/liquid/types/common_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package types_test - -import ( - "os" - "testing" - - "github.com/0glabs/0g-chain/app" -) - -func TestMain(m *testing.M) { - app.SetSDKConfig() - os.Exit(m.Run()) -} diff --git a/x/liquid/types/errors.go b/x/liquid/types/errors.go deleted file mode 100644 index fe75247e..00000000 --- a/x/liquid/types/errors.go +++ /dev/null @@ -1,13 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -var ( - ErrNoValidatorFound = errorsmod.Register(ModuleName, 2, "validator does not exist") - ErrNoDelegatorForAddress = errorsmod.Register(ModuleName, 3, "delegator does not contain delegation") - ErrInvalidDenom = errorsmod.Register(ModuleName, 4, "invalid denom") - ErrNotEnoughDelegationShares = errorsmod.Register(ModuleName, 5, "not enough delegation shares") - ErrRedelegationsNotCompleted = errorsmod.Register(ModuleName, 6, "active redelegations cannot be transferred") - ErrUntransferableShares = errorsmod.Register(ModuleName, 7, "shares cannot be transferred") - ErrSelfDelegationBelowMinimum = errorsmod.Register(ModuleName, 8, "validator's self delegation must be greater than their minimum self delegation") -) diff --git a/x/liquid/types/events.go b/x/liquid/types/events.go deleted file mode 100644 index 27658719..00000000 --- a/x/liquid/types/events.go +++ /dev/null @@ -1,11 +0,0 @@ -package types - -const ( - EventTypeMintDerivative = "mint_derivative" - EventTypeBurnDerivative = "burn_derivative" - - AttributeValueCategory = ModuleName - AttributeKeyDelegator = "delegator" - AttributeKeyValidator = "validator" - AttributeKeySharesTransferred = "shares_transferred" -) diff --git a/x/liquid/types/expected_keepers.go b/x/liquid/types/expected_keepers.go deleted file mode 100644 index 3c059d59..00000000 --- a/x/liquid/types/expected_keepers.go +++ /dev/null @@ -1,57 +0,0 @@ -package types - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -// BankKeeper defines the expected bank keeper -type BankKeeper interface { - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error - - MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error - BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error - UndelegateCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - - IterateTotalSupply(ctx sdk.Context, cb func(sdk.Coin) bool) - GetSupply(ctx sdk.Context, denom string) sdk.Coin -} - -// AccountKeeper defines the expected keeper interface for interacting with account -type AccountKeeper interface { - GetModuleAddress(moduleName string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, name string) authtypes.ModuleAccountI - GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI -} - -// StakingKeeper defines the expected keeper interface for interacting with staking -type StakingKeeper interface { - BondDenom(ctx sdk.Context) (res string) - - GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool) - GetDelegation(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) (delegation stakingtypes.Delegation, found bool) - IterateDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddress, cb func(delegation stakingtypes.Delegation) (stop bool)) - HasReceivingRedelegation(ctx sdk.Context, delAddr sdk.AccAddress, valDstAddr sdk.ValAddress) bool - - ValidateUnbondAmount( - ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, amt sdkmath.Int, - ) (shares sdk.Dec, err error) - - Delegate( - ctx sdk.Context, delAddr sdk.AccAddress, bondAmt sdkmath.Int, tokenSrc stakingtypes.BondStatus, - validator stakingtypes.Validator, subtractAccount bool, - ) (newShares sdk.Dec, err error) - Unbond( - ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, shares sdk.Dec, - ) (amount sdkmath.Int, err error) -} - -type DistributionKeeper interface { - GetDelegatorWithdrawAddr(ctx sdk.Context, delAddr sdk.AccAddress) sdk.AccAddress - WithdrawDelegationRewards(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) (sdk.Coins, error) -} diff --git a/x/liquid/types/key.go b/x/liquid/types/key.go deleted file mode 100644 index a244ec5e..00000000 --- a/x/liquid/types/key.go +++ /dev/null @@ -1,46 +0,0 @@ -package types - -import ( - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // ModuleName The name that will be used throughout the module - ModuleName = "liquid" - - // RouterKey Top level router key - RouterKey = ModuleName - - // ModuleAccountName is the module account's name - ModuleAccountName = ModuleName - - DefaultDerivativeDenom = "bkava" - - DenomSeparator = "-" -) - -func GetLiquidStakingTokenDenom(bondDenom string, valAddr sdk.ValAddress) string { - return fmt.Sprintf("%s%s%s", bondDenom, DenomSeparator, valAddr.String()) -} - -// ParseLiquidStakingTokenDenom extracts a validator address from a derivative denom. -func ParseLiquidStakingTokenDenom(denom string) (sdk.ValAddress, error) { - elements := strings.Split(denom, DenomSeparator) - if len(elements) != 2 { - return nil, fmt.Errorf("cannot parse denom %s", denom) - } - - if elements[0] != DefaultDerivativeDenom { - return nil, fmt.Errorf("invalid denom prefix, expected %s, got %s", DefaultDerivativeDenom, elements[0]) - } - - addr, err := sdk.ValAddressFromBech32(elements[1]) - if err != nil { - return nil, fmt.Errorf("invalid denom validator address: %w", err) - } - - return addr, nil -} diff --git a/x/liquid/types/key_test.go b/x/liquid/types/key_test.go deleted file mode 100644 index b0e3f259..00000000 --- a/x/liquid/types/key_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package types_test - -import ( - "fmt" - "testing" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/liquid/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestParseLiquidStakingTokenDenom(t *testing.T) { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - tests := []struct { - name string - giveDenom string - wantAddress sdk.ValAddress - wantErr error - }{ - { - name: "valid denom", - giveDenom: "bkava-kavavaloper1ze7y9qwdddejmy7jlw4cymqqlt2wh05y6cpt5a", - wantAddress: mustValAddressFromBech32("kavavaloper1ze7y9qwdddejmy7jlw4cymqqlt2wh05y6cpt5a"), - wantErr: nil, - }, - { - name: "invalid prefix", - giveDenom: "ukava-kavavaloper1ze7y9qwdddejmy7jlw4cymqqlt2wh05y6cpt5a", - wantAddress: mustValAddressFromBech32("kavavaloper1ze7y9qwdddejmy7jlw4cymqqlt2wh05y6cpt5a"), - wantErr: fmt.Errorf("invalid denom prefix, expected %s, got %s", types.DefaultDerivativeDenom, "ukava"), - }, - { - name: "invalid validator address", - giveDenom: "bkava-kavavaloper1ze7y9qw", - wantAddress: sdk.ValAddress{}, - wantErr: fmt.Errorf("invalid denom validator address: decoding bech32 failed: invalid checksum"), - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - addr, err := types.ParseLiquidStakingTokenDenom(tt.giveDenom) - - if tt.wantErr != nil { - require.Error(t, err) - require.Contains(t, err.Error(), tt.wantErr.Error()) - } else { - require.NoError(t, err) - require.Equal(t, tt.wantAddress, addr) - } - }) - } -} diff --git a/x/liquid/types/msg.go b/x/liquid/types/msg.go deleted file mode 100644 index 0b94f4a3..00000000 --- a/x/liquid/types/msg.go +++ /dev/null @@ -1,121 +0,0 @@ -package types - -import ( - 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/auth/migrations/legacytx" -) - -const ( - // TypeMsgMintDerivative represents the type string for MsgMintDerivative - TypeMsgMintDerivative = "mint_derivative" - // TypeMsgBurnDerivative represents the type string for MsgBurnDerivative - TypeMsgBurnDerivative = "burn_derivative" -) - -// ensure Msg interface compliance at compile time -var ( - _ sdk.Msg = &MsgMintDerivative{} - _ legacytx.LegacyMsg = &MsgMintDerivative{} - _ sdk.Msg = &MsgBurnDerivative{} - _ legacytx.LegacyMsg = &MsgBurnDerivative{} -) - -// NewMsgMintDerivative returns a new MsgMintDerivative -func NewMsgMintDerivative(sender sdk.AccAddress, validator sdk.ValAddress, amount sdk.Coin) MsgMintDerivative { - return MsgMintDerivative{ - Sender: sender.String(), - Validator: validator.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgMintDerivative) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgMintDerivative) Type() string { return TypeMsgMintDerivative } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgMintDerivative) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - _, err = sdk.ValAddressFromBech32(msg.Validator) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if msg.Amount.IsNil() || !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "'%s'", msg.Amount) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgMintDerivative) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgMintDerivative) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} - -// NewMsgBurnDerivative returns a new MsgBurnDerivative -func NewMsgBurnDerivative(sender sdk.AccAddress, validator sdk.ValAddress, amount sdk.Coin) MsgBurnDerivative { - return MsgBurnDerivative{ - Sender: sender.String(), - Validator: validator.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgBurnDerivative) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgBurnDerivative) Type() string { return TypeMsgBurnDerivative } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgBurnDerivative) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - _, err = sdk.ValAddressFromBech32(msg.Validator) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if msg.Amount.IsNil() || !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "'%s'", msg.Amount) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgBurnDerivative) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgBurnDerivative) GetSigners() []sdk.AccAddress { - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{sender} -} diff --git a/x/liquid/types/msg_test.go b/x/liquid/types/msg_test.go deleted file mode 100644 index 36666293..00000000 --- a/x/liquid/types/msg_test.go +++ /dev/null @@ -1,164 +0,0 @@ -package types_test - -import ( - fmt "fmt" - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/0glabs/0g-chain/x/liquid/types" -) - -func TestMsgMintDerivative_Signing(t *testing.T) { - address := mustAccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - validatorAddress := mustValAddressFromBech32("kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42") - - msg := types.NewMsgMintDerivative( - address, - validatorAddress, - sdk.NewCoin("ukava", sdkmath.NewInt(1e9)), - ) - - // checking for the "type" field ensures the msg is registered on the amino codec - signBytes := []byte( - `{"type":"liquid/MsgMintDerivative","value":{"amount":{"amount":"1000000000","denom":"ukava"},"sender":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","validator":"kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42"}}`, - ) - - assert.Equal(t, []sdk.AccAddress{address}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsgBurnDerivative_Signing(t *testing.T) { - address := mustAccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - validatorAddress := mustValAddressFromBech32("kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42") - - msg := types.NewMsgBurnDerivative( - address, - validatorAddress, - sdk.NewCoin("bkava-kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42", sdkmath.NewInt(1e9)), - ) - - // checking for the "type" field ensures the msg is registered on the amino codec - signBytes := []byte( - `{"type":"liquid/MsgBurnDerivative","value":{"amount":{"amount":"1000000000","denom":"bkava-kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42"},"sender":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","validator":"kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42"}}`, - ) - - assert.Equal(t, []sdk.AccAddress{address}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsg_Validate(t *testing.T) { - validAddress := mustAccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - validValidatorAddress := mustValAddressFromBech32("kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42") - validCoin := sdk.NewInt64Coin("ukava", 1e9) - - type msgArgs struct { - sender string - validator string - amount sdk.Coin - } - tests := []struct { - name string - msgArgs msgArgs - expectedErr error - }{ - { - name: "normal is valid", - msgArgs: msgArgs{ - sender: validAddress.String(), - validator: validValidatorAddress.String(), - amount: validCoin, - }, - }, - { - name: "invalid sender", - msgArgs: msgArgs{ - sender: "invalid", - validator: validValidatorAddress.String(), - amount: validCoin, - }, - expectedErr: sdkerrors.ErrInvalidAddress, - }, - { - name: "invalid short sender", - msgArgs: msgArgs{ - sender: "kava1uexte6", // encoded zero length address - validator: validValidatorAddress.String(), - amount: validCoin, - }, - expectedErr: sdkerrors.ErrInvalidAddress, - }, - { - name: "invalid validator", - msgArgs: msgArgs{ - sender: validAddress.String(), - validator: "invalid", - amount: validCoin, - }, - expectedErr: sdkerrors.ErrInvalidAddress, - }, - { - name: "invalid nil coin", - msgArgs: msgArgs{ - sender: validAddress.String(), - validator: validValidatorAddress.String(), - amount: sdk.Coin{}, - }, - expectedErr: sdkerrors.ErrInvalidCoins, - }, - { - name: "invalid zero coin", - msgArgs: msgArgs{ - sender: validAddress.String(), - validator: validValidatorAddress.String(), - amount: sdk.NewInt64Coin("ukava", 0), - }, - expectedErr: sdkerrors.ErrInvalidCoins, - }, - } - - for _, tc := range tests { - msgs := []sdk.Msg{ - &types.MsgMintDerivative{ - Sender: tc.msgArgs.sender, - Validator: tc.msgArgs.validator, - Amount: tc.msgArgs.amount, - }, - &types.MsgBurnDerivative{ - Sender: tc.msgArgs.sender, - Validator: tc.msgArgs.validator, - Amount: tc.msgArgs.amount, - }, - } - for _, msg := range msgs { - t.Run(fmt.Sprintf("%s/%T", tc.name, msg), func(t *testing.T) { - err := msg.ValidateBasic() - if tc.expectedErr == nil { - require.NoError(t, err) - } else { - require.ErrorIs(t, err, tc.expectedErr, "expected error '%s' not found in actual '%s'", tc.expectedErr, err) - } - }) - } - } -} - -func mustAccAddressFromBech32(address string) sdk.AccAddress { - addr, err := sdk.AccAddressFromBech32(address) - if err != nil { - panic(err) - } - return addr -} - -func mustValAddressFromBech32(address string) sdk.ValAddress { - addr, err := sdk.ValAddressFromBech32(address) - if err != nil { - panic(err) - } - return addr -} diff --git a/x/liquid/types/query.pb.go b/x/liquid/types/query.pb.go deleted file mode 100644 index 6024d4fa..00000000 --- a/x/liquid/types/query.pb.go +++ /dev/null @@ -1,1002 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/liquid/v1beta1/query.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// QueryDelegatedBalanceRequest defines the request type for Query/DelegatedBalance method. -type QueryDelegatedBalanceRequest struct { - // delegator is the address of the account to query - Delegator string `protobuf:"bytes,1,opt,name=delegator,proto3" json:"delegator,omitempty"` -} - -func (m *QueryDelegatedBalanceRequest) Reset() { *m = QueryDelegatedBalanceRequest{} } -func (m *QueryDelegatedBalanceRequest) String() string { return proto.CompactTextString(m) } -func (*QueryDelegatedBalanceRequest) ProtoMessage() {} -func (*QueryDelegatedBalanceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_0d745428489be444, []int{0} -} -func (m *QueryDelegatedBalanceRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDelegatedBalanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDelegatedBalanceRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryDelegatedBalanceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDelegatedBalanceRequest.Merge(m, src) -} -func (m *QueryDelegatedBalanceRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryDelegatedBalanceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDelegatedBalanceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDelegatedBalanceRequest proto.InternalMessageInfo - -// DelegatedBalanceResponse defines the response type for the Query/DelegatedBalance method. -type QueryDelegatedBalanceResponse struct { - // vested is the amount of all delegated coins that have vested (ie not locked) - Vested types.Coin `protobuf:"bytes,1,opt,name=vested,proto3" json:"vested"` - // vesting is the amount of all delegated coins that are still vesting (ie locked) - Vesting types.Coin `protobuf:"bytes,2,opt,name=vesting,proto3" json:"vesting"` -} - -func (m *QueryDelegatedBalanceResponse) Reset() { *m = QueryDelegatedBalanceResponse{} } -func (m *QueryDelegatedBalanceResponse) String() string { return proto.CompactTextString(m) } -func (*QueryDelegatedBalanceResponse) ProtoMessage() {} -func (*QueryDelegatedBalanceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_0d745428489be444, []int{1} -} -func (m *QueryDelegatedBalanceResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDelegatedBalanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDelegatedBalanceResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryDelegatedBalanceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDelegatedBalanceResponse.Merge(m, src) -} -func (m *QueryDelegatedBalanceResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryDelegatedBalanceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDelegatedBalanceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDelegatedBalanceResponse proto.InternalMessageInfo - -// QueryTotalSupplyRequest defines the request type for Query/TotalSupply method. -type QueryTotalSupplyRequest struct { -} - -func (m *QueryTotalSupplyRequest) Reset() { *m = QueryTotalSupplyRequest{} } -func (m *QueryTotalSupplyRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalSupplyRequest) ProtoMessage() {} -func (*QueryTotalSupplyRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_0d745428489be444, []int{2} -} -func (m *QueryTotalSupplyRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalSupplyRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalSupplyRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTotalSupplyRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalSupplyRequest.Merge(m, src) -} -func (m *QueryTotalSupplyRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalSupplyRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalSupplyRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalSupplyRequest proto.InternalMessageInfo - -// TotalSupplyResponse defines the response type for the Query/TotalSupply method. -type QueryTotalSupplyResponse struct { - // Height is the block height at which these totals apply - Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` - // Result is a list of coins supplied to liquid - Result github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=result,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"result"` -} - -func (m *QueryTotalSupplyResponse) Reset() { *m = QueryTotalSupplyResponse{} } -func (m *QueryTotalSupplyResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalSupplyResponse) ProtoMessage() {} -func (*QueryTotalSupplyResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_0d745428489be444, []int{3} -} -func (m *QueryTotalSupplyResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalSupplyResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalSupplyResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTotalSupplyResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalSupplyResponse.Merge(m, src) -} -func (m *QueryTotalSupplyResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalSupplyResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalSupplyResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalSupplyResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryDelegatedBalanceRequest)(nil), "kava.liquid.v1beta1.QueryDelegatedBalanceRequest") - proto.RegisterType((*QueryDelegatedBalanceResponse)(nil), "kava.liquid.v1beta1.QueryDelegatedBalanceResponse") - proto.RegisterType((*QueryTotalSupplyRequest)(nil), "kava.liquid.v1beta1.QueryTotalSupplyRequest") - proto.RegisterType((*QueryTotalSupplyResponse)(nil), "kava.liquid.v1beta1.QueryTotalSupplyResponse") -} - -func init() { proto.RegisterFile("kava/liquid/v1beta1/query.proto", fileDescriptor_0d745428489be444) } - -var fileDescriptor_0d745428489be444 = []byte{ - // 507 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x93, 0x4f, 0x6f, 0xd3, 0x30, - 0x18, 0xc6, 0xe3, 0x0e, 0x8a, 0xe6, 0x5d, 0x90, 0x99, 0x20, 0xad, 0x46, 0x3a, 0xc2, 0x65, 0x93, - 0x68, 0xdc, 0x16, 0x04, 0x82, 0x1b, 0x05, 0x89, 0x33, 0x19, 0xe2, 0xc0, 0xa5, 0x72, 0x12, 0xcb, - 0xb5, 0x96, 0xd9, 0x69, 0xec, 0x54, 0x54, 0x88, 0x0b, 0x9f, 0x00, 0x69, 0x42, 0x7c, 0x07, 0xce, - 0xf0, 0x1d, 0x7a, 0x9c, 0xe0, 0x00, 0x27, 0xfe, 0xb4, 0x7c, 0x10, 0x14, 0xc7, 0x1d, 0x13, 0xeb, - 0xa6, 0x72, 0x8a, 0xed, 0xf7, 0x79, 0x5e, 0xff, 0xfc, 0xbe, 0x6f, 0x60, 0x6b, 0x9f, 0x8c, 0x09, - 0x4e, 0xf9, 0xa8, 0xe0, 0x09, 0x1e, 0x77, 0x23, 0xaa, 0x49, 0x17, 0x8f, 0x0a, 0x9a, 0x4f, 0x82, - 0x2c, 0x97, 0x5a, 0xa2, 0x2b, 0xa5, 0x20, 0xa8, 0x04, 0x81, 0x15, 0x34, 0xbd, 0x58, 0xaa, 0x03, - 0xa9, 0x70, 0x44, 0x14, 0x3d, 0x76, 0xc5, 0x92, 0x8b, 0xca, 0xd4, 0x6c, 0x54, 0xf1, 0x81, 0xd9, - 0xe1, 0x6a, 0x63, 0x43, 0x9b, 0x4c, 0x32, 0x59, 0x9d, 0x97, 0x2b, 0x7b, 0xba, 0xc5, 0xa4, 0x64, - 0x29, 0xc5, 0x24, 0xe3, 0x98, 0x08, 0x21, 0x35, 0xd1, 0x5c, 0x0a, 0xeb, 0xf1, 0x9f, 0xc3, 0xad, - 0xa7, 0x25, 0xd2, 0x63, 0x9a, 0x52, 0x46, 0x34, 0x4d, 0xfa, 0x24, 0x25, 0x22, 0xa6, 0x21, 0x1d, - 0x15, 0x54, 0x69, 0x74, 0x17, 0xae, 0x27, 0x55, 0x48, 0xe6, 0x2e, 0xd8, 0x06, 0x3b, 0xeb, 0x7d, - 0xf7, 0xf3, 0xc7, 0xf6, 0xa6, 0xbd, 0xf8, 0x61, 0x92, 0xe4, 0x54, 0xa9, 0x3d, 0x9d, 0x73, 0xc1, - 0xc2, 0xbf, 0x52, 0xff, 0x10, 0xc0, 0xeb, 0x67, 0x24, 0x56, 0x99, 0x14, 0x8a, 0xa2, 0x7b, 0xb0, - 0x3e, 0xa6, 0x4a, 0xd3, 0xc4, 0xa4, 0xdd, 0xe8, 0x35, 0x02, 0x9b, 0xb3, 0x7c, 0xf9, 0xa2, 0x1c, - 0xc1, 0x23, 0xc9, 0x45, 0xff, 0xc2, 0xf4, 0x7b, 0xcb, 0x09, 0xad, 0x1c, 0xdd, 0x87, 0x97, 0xca, - 0x15, 0x17, 0xcc, 0xad, 0xad, 0xe6, 0x5c, 0xe8, 0xfd, 0x06, 0xbc, 0x66, 0xa0, 0x9e, 0x49, 0x4d, - 0xd2, 0xbd, 0x22, 0xcb, 0xd2, 0x89, 0x7d, 0xa8, 0xff, 0x1e, 0x40, 0xf7, 0x74, 0xcc, 0xb2, 0x5e, - 0x85, 0xf5, 0x21, 0xe5, 0x6c, 0xa8, 0x0d, 0xeb, 0x5a, 0x68, 0x77, 0x28, 0x86, 0xf5, 0x9c, 0xaa, - 0x22, 0xd5, 0x6e, 0x6d, 0x7b, 0xed, 0x7c, 0x92, 0x4e, 0x49, 0xf2, 0xe1, 0x47, 0x6b, 0x87, 0x71, - 0x3d, 0x2c, 0xa2, 0x20, 0x96, 0x07, 0xb6, 0x7b, 0xf6, 0xd3, 0x56, 0xc9, 0x3e, 0xd6, 0x93, 0x8c, - 0x2a, 0x63, 0x50, 0xa1, 0x4d, 0xdd, 0xfb, 0x5a, 0x83, 0x17, 0x0d, 0x19, 0xfa, 0x04, 0xe0, 0xe5, - 0x7f, 0xeb, 0x89, 0xba, 0xc1, 0x92, 0x31, 0x0a, 0xce, 0x6b, 0x6a, 0xb3, 0xf7, 0x3f, 0x96, 0xaa, - 0x04, 0xfe, 0x83, 0x37, 0x5f, 0x7e, 0x1f, 0xd6, 0xee, 0xa0, 0x1e, 0x5e, 0x36, 0xd6, 0xc9, 0xc2, - 0x36, 0x88, 0x2a, 0x1f, 0x7e, 0x75, 0x3c, 0x0b, 0xaf, 0xd1, 0x3b, 0x00, 0x37, 0x4e, 0x94, 0x15, - 0xdd, 0x3a, 0xfb, 0xfe, 0xd3, 0x9d, 0x69, 0xb6, 0x57, 0x54, 0x5b, 0xd0, 0x5d, 0x03, 0x7a, 0x13, - 0xdd, 0x58, 0x0a, 0xaa, 0x4b, 0xc7, 0x40, 0x19, 0x4b, 0xff, 0xc9, 0xf4, 0x97, 0xe7, 0x4c, 0x67, - 0x1e, 0x38, 0x9a, 0x79, 0xe0, 0xe7, 0xcc, 0x03, 0x6f, 0xe7, 0x9e, 0x73, 0x34, 0xf7, 0x9c, 0x6f, - 0x73, 0xcf, 0x79, 0xb1, 0x7b, 0xa2, 0x53, 0x1d, 0x96, 0x92, 0x48, 0xe1, 0x0e, 0x6b, 0xc7, 0x43, - 0xc2, 0x05, 0x7e, 0xb9, 0xc8, 0x6b, 0x1a, 0x16, 0xd5, 0xcd, 0xcf, 0x74, 0xfb, 0x4f, 0x00, 0x00, - 0x00, 0xff, 0xff, 0x23, 0x67, 0xe2, 0xa2, 0xf3, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - // DelegatedBalance returns an account's vesting and vested coins currently delegated to validators. - // It ignores coins in unbonding delegations. - DelegatedBalance(ctx context.Context, in *QueryDelegatedBalanceRequest, opts ...grpc.CallOption) (*QueryDelegatedBalanceResponse, error) - // TotalSupply returns the total sum of all coins currently locked into the liquid module. - TotalSupply(ctx context.Context, in *QueryTotalSupplyRequest, opts ...grpc.CallOption) (*QueryTotalSupplyResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) DelegatedBalance(ctx context.Context, in *QueryDelegatedBalanceRequest, opts ...grpc.CallOption) (*QueryDelegatedBalanceResponse, error) { - out := new(QueryDelegatedBalanceResponse) - err := c.cc.Invoke(ctx, "/kava.liquid.v1beta1.Query/DelegatedBalance", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalSupply(ctx context.Context, in *QueryTotalSupplyRequest, opts ...grpc.CallOption) (*QueryTotalSupplyResponse, error) { - out := new(QueryTotalSupplyResponse) - err := c.cc.Invoke(ctx, "/kava.liquid.v1beta1.Query/TotalSupply", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // DelegatedBalance returns an account's vesting and vested coins currently delegated to validators. - // It ignores coins in unbonding delegations. - DelegatedBalance(context.Context, *QueryDelegatedBalanceRequest) (*QueryDelegatedBalanceResponse, error) - // TotalSupply returns the total sum of all coins currently locked into the liquid module. - TotalSupply(context.Context, *QueryTotalSupplyRequest) (*QueryTotalSupplyResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) DelegatedBalance(ctx context.Context, req *QueryDelegatedBalanceRequest) (*QueryDelegatedBalanceResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method DelegatedBalance not implemented") -} -func (*UnimplementedQueryServer) TotalSupply(ctx context.Context, req *QueryTotalSupplyRequest) (*QueryTotalSupplyResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalSupply not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_DelegatedBalance_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryDelegatedBalanceRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).DelegatedBalance(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.liquid.v1beta1.Query/DelegatedBalance", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).DelegatedBalance(ctx, req.(*QueryDelegatedBalanceRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalSupply_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalSupplyRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalSupply(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.liquid.v1beta1.Query/TotalSupply", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalSupply(ctx, req.(*QueryTotalSupplyRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.liquid.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "DelegatedBalance", - Handler: _Query_DelegatedBalance_Handler, - }, - { - MethodName: "TotalSupply", - Handler: _Query_TotalSupply_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/liquid/v1beta1/query.proto", -} - -func (m *QueryDelegatedBalanceRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryDelegatedBalanceRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDelegatedBalanceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Delegator) > 0 { - i -= len(m.Delegator) - copy(dAtA[i:], m.Delegator) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Delegator))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDelegatedBalanceResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryDelegatedBalanceResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDelegatedBalanceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Vesting.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.Vested.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryTotalSupplyRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryTotalSupplyRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalSupplyRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryTotalSupplyResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryTotalSupplyResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalSupplyResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Result) > 0 { - for iNdEx := len(m.Result) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Result[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if m.Height != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.Height)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryDelegatedBalanceRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Delegator) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDelegatedBalanceResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Vested.Size() - n += 1 + l + sovQuery(uint64(l)) - l = m.Vesting.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryTotalSupplyRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryTotalSupplyResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Height != 0 { - n += 1 + sovQuery(uint64(m.Height)) - } - if len(m.Result) > 0 { - for _, e := range m.Result { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryDelegatedBalanceRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryDelegatedBalanceRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDelegatedBalanceRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Delegator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Delegator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDelegatedBalanceResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryDelegatedBalanceResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDelegatedBalanceResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Vested", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Vested.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Vesting", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Vesting.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTotalSupplyRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTotalSupplyRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalSupplyRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTotalSupplyResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTotalSupplyResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalSupplyResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) - } - m.Height = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Height |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Result = append(m.Result, types.Coin{}) - if err := m.Result[len(m.Result)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/liquid/types/query.pb.gw.go b/x/liquid/types/query.pb.gw.go deleted file mode 100644 index b9134b62..00000000 --- a/x/liquid/types/query.pb.gw.go +++ /dev/null @@ -1,254 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/liquid/v1beta1/query.proto - -/* -Package types is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package types - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join - -func request_Query_DelegatedBalance_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDelegatedBalanceRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["delegator"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "delegator") - } - - protoReq.Delegator, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "delegator", err) - } - - msg, err := client.DelegatedBalance(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_DelegatedBalance_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDelegatedBalanceRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["delegator"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "delegator") - } - - protoReq.Delegator, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "delegator", err) - } - - msg, err := server.DelegatedBalance(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_TotalSupply_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalSupplyRequest - var metadata runtime.ServerMetadata - - msg, err := client.TotalSupply(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TotalSupply_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalSupplyRequest - var metadata runtime.ServerMetadata - - msg, err := server.TotalSupply(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_DelegatedBalance_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_DelegatedBalance_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_DelegatedBalance_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalSupply_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_TotalSupply_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TotalSupply_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_DelegatedBalance_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_DelegatedBalance_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_DelegatedBalance_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalSupply_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_TotalSupply_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TotalSupply_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_DelegatedBalance_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"kava", "liquid", "v1beta1", "delegated_balance", "delegator"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TotalSupply_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "liquid", "v1beta1", "total_supply"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_DelegatedBalance_0 = runtime.ForwardResponseMessage - - forward_Query_TotalSupply_0 = runtime.ForwardResponseMessage -) diff --git a/x/liquid/types/tx.pb.go b/x/liquid/types/tx.pb.go deleted file mode 100644 index 5b90167e..00000000 --- a/x/liquid/types/tx.pb.go +++ /dev/null @@ -1,1188 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/liquid/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// MsgMintDerivative defines the Msg/MintDerivative request type. -type MsgMintDerivative struct { - // sender is the owner of the delegation to be converted - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // validator is the validator of the delegation to be converted - Validator string `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator,omitempty"` - // amount is the quantity of staked assets to be converted - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *MsgMintDerivative) Reset() { *m = MsgMintDerivative{} } -func (m *MsgMintDerivative) String() string { return proto.CompactTextString(m) } -func (*MsgMintDerivative) ProtoMessage() {} -func (*MsgMintDerivative) Descriptor() ([]byte, []int) { - return fileDescriptor_738981106e50f269, []int{0} -} -func (m *MsgMintDerivative) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgMintDerivative) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMintDerivative.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgMintDerivative) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMintDerivative.Merge(m, src) -} -func (m *MsgMintDerivative) XXX_Size() int { - return m.Size() -} -func (m *MsgMintDerivative) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMintDerivative.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMintDerivative proto.InternalMessageInfo - -func (m *MsgMintDerivative) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgMintDerivative) GetValidator() string { - if m != nil { - return m.Validator - } - return "" -} - -func (m *MsgMintDerivative) GetAmount() types.Coin { - if m != nil { - return m.Amount - } - return types.Coin{} -} - -// MsgMintDerivativeResponse defines the Msg/MintDerivative response type. -type MsgMintDerivativeResponse struct { - // received is the amount of staking derivative minted and sent to the sender - Received types.Coin `protobuf:"bytes,1,opt,name=received,proto3" json:"received"` -} - -func (m *MsgMintDerivativeResponse) Reset() { *m = MsgMintDerivativeResponse{} } -func (m *MsgMintDerivativeResponse) String() string { return proto.CompactTextString(m) } -func (*MsgMintDerivativeResponse) ProtoMessage() {} -func (*MsgMintDerivativeResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_738981106e50f269, []int{1} -} -func (m *MsgMintDerivativeResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgMintDerivativeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMintDerivativeResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgMintDerivativeResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMintDerivativeResponse.Merge(m, src) -} -func (m *MsgMintDerivativeResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgMintDerivativeResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMintDerivativeResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMintDerivativeResponse proto.InternalMessageInfo - -func (m *MsgMintDerivativeResponse) GetReceived() types.Coin { - if m != nil { - return m.Received - } - return types.Coin{} -} - -// MsgBurnDerivative defines the Msg/BurnDerivative request type. -type MsgBurnDerivative struct { - // sender is the owner of the derivatives to be converted - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // validator is the validator of the derivatives to be converted - Validator string `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator,omitempty"` - // amount is the quantity of derivatives to be converted - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *MsgBurnDerivative) Reset() { *m = MsgBurnDerivative{} } -func (m *MsgBurnDerivative) String() string { return proto.CompactTextString(m) } -func (*MsgBurnDerivative) ProtoMessage() {} -func (*MsgBurnDerivative) Descriptor() ([]byte, []int) { - return fileDescriptor_738981106e50f269, []int{2} -} -func (m *MsgBurnDerivative) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgBurnDerivative) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgBurnDerivative.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgBurnDerivative) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgBurnDerivative.Merge(m, src) -} -func (m *MsgBurnDerivative) XXX_Size() int { - return m.Size() -} -func (m *MsgBurnDerivative) XXX_DiscardUnknown() { - xxx_messageInfo_MsgBurnDerivative.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgBurnDerivative proto.InternalMessageInfo - -func (m *MsgBurnDerivative) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgBurnDerivative) GetValidator() string { - if m != nil { - return m.Validator - } - return "" -} - -func (m *MsgBurnDerivative) GetAmount() types.Coin { - if m != nil { - return m.Amount - } - return types.Coin{} -} - -// MsgBurnDerivativeResponse defines the Msg/BurnDerivative response type. -type MsgBurnDerivativeResponse struct { - // received is the number of delegation shares sent to the sender - Received github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=received,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"received"` -} - -func (m *MsgBurnDerivativeResponse) Reset() { *m = MsgBurnDerivativeResponse{} } -func (m *MsgBurnDerivativeResponse) String() string { return proto.CompactTextString(m) } -func (*MsgBurnDerivativeResponse) ProtoMessage() {} -func (*MsgBurnDerivativeResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_738981106e50f269, []int{3} -} -func (m *MsgBurnDerivativeResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgBurnDerivativeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgBurnDerivativeResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgBurnDerivativeResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgBurnDerivativeResponse.Merge(m, src) -} -func (m *MsgBurnDerivativeResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgBurnDerivativeResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgBurnDerivativeResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgBurnDerivativeResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgMintDerivative)(nil), "kava.liquid.v1beta1.MsgMintDerivative") - proto.RegisterType((*MsgMintDerivativeResponse)(nil), "kava.liquid.v1beta1.MsgMintDerivativeResponse") - proto.RegisterType((*MsgBurnDerivative)(nil), "kava.liquid.v1beta1.MsgBurnDerivative") - proto.RegisterType((*MsgBurnDerivativeResponse)(nil), "kava.liquid.v1beta1.MsgBurnDerivativeResponse") -} - -func init() { proto.RegisterFile("kava/liquid/v1beta1/tx.proto", fileDescriptor_738981106e50f269) } - -var fileDescriptor_738981106e50f269 = []byte{ - // 429 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x53, 0xbd, 0x6e, 0xdb, 0x30, - 0x10, 0x16, 0x9b, 0xc2, 0xa8, 0x59, 0x20, 0x40, 0xd5, 0x0c, 0xb2, 0x11, 0x28, 0x41, 0x86, 0x20, - 0x1d, 0x44, 0x3a, 0xe9, 0xd0, 0xa1, 0x5d, 0xaa, 0x78, 0xf5, 0xa2, 0x2e, 0x41, 0x97, 0x82, 0x92, - 0x08, 0x8a, 0x88, 0x4d, 0xba, 0x24, 0x25, 0xa4, 0x6f, 0xd1, 0x07, 0xe8, 0x63, 0xe4, 0x21, 0x32, - 0x1a, 0x9e, 0xda, 0x0e, 0x46, 0x61, 0xbf, 0x48, 0x21, 0x89, 0x96, 0xeb, 0x3f, 0xc0, 0x63, 0x27, - 0x89, 0xf7, 0xdd, 0x77, 0xbc, 0xef, 0x3b, 0x1e, 0x3c, 0xbd, 0x27, 0x05, 0xc1, 0x43, 0xfe, 0x35, - 0xe7, 0x29, 0x2e, 0xae, 0x63, 0x6a, 0xc8, 0x35, 0x36, 0x0f, 0x68, 0xac, 0xa4, 0x91, 0xee, 0xeb, - 0x12, 0x45, 0x35, 0x8a, 0x2c, 0xda, 0xf5, 0x13, 0xa9, 0x47, 0x52, 0xe3, 0x98, 0x68, 0xda, 0x50, - 0x12, 0xc9, 0x45, 0x4d, 0xea, 0x76, 0x6a, 0xfc, 0x4b, 0x75, 0xc2, 0xf5, 0xc1, 0x42, 0x27, 0x4c, - 0x32, 0x59, 0xc7, 0xcb, 0xbf, 0x3a, 0x7a, 0xf1, 0x03, 0xc0, 0x57, 0x03, 0xcd, 0x06, 0x5c, 0x98, - 0x3e, 0x55, 0xbc, 0x20, 0x86, 0x17, 0xd4, 0xed, 0xc1, 0x96, 0xa6, 0x22, 0xa5, 0xca, 0x03, 0xe7, - 0xe0, 0xaa, 0x1d, 0x7a, 0xd3, 0xc7, 0xe0, 0xc4, 0x56, 0xfb, 0x98, 0xa6, 0x8a, 0x6a, 0xfd, 0xc9, - 0x28, 0x2e, 0x58, 0x64, 0xf3, 0xdc, 0x53, 0xd8, 0x2e, 0xc8, 0x90, 0xa7, 0xc4, 0x48, 0xe5, 0x3d, - 0x2b, 0x49, 0xd1, 0x2a, 0xe0, 0xbe, 0x83, 0x2d, 0x32, 0x92, 0xb9, 0x30, 0xde, 0xd1, 0x39, 0xb8, - 0x7a, 0x79, 0xd3, 0x41, 0xb6, 0x58, 0xa9, 0x63, 0x29, 0x0e, 0xdd, 0x4a, 0x2e, 0xc2, 0xe7, 0x4f, - 0xb3, 0x33, 0x27, 0xb2, 0xe9, 0x17, 0x77, 0xb0, 0xb3, 0xd5, 0x5d, 0x44, 0xf5, 0x58, 0x0a, 0x4d, - 0xdd, 0xf7, 0xf0, 0x85, 0xa2, 0x09, 0xe5, 0x05, 0x4d, 0xab, 0x3e, 0x0f, 0xa8, 0xdb, 0x10, 0x96, - 0xc2, 0xc3, 0x5c, 0x89, 0xff, 0x51, 0x78, 0x5e, 0x09, 0x5f, 0xef, 0xae, 0x11, 0x7e, 0xb7, 0x21, - 0xbc, 0x1d, 0x7e, 0x28, 0xc9, 0xbf, 0x67, 0x67, 0x97, 0x8c, 0x9b, 0x2c, 0x8f, 0x51, 0x22, 0x47, - 0x76, 0xfa, 0xf6, 0x13, 0xe8, 0xf4, 0x1e, 0x9b, 0x6f, 0x63, 0xaa, 0x51, 0x9f, 0x26, 0xd3, 0xc7, - 0x00, 0xda, 0x46, 0xfa, 0x34, 0x59, 0xb9, 0x72, 0xf3, 0x0b, 0xc0, 0xa3, 0x81, 0x66, 0x6e, 0x06, - 0x8f, 0x37, 0x9e, 0xc4, 0x25, 0xda, 0xf1, 0x1e, 0xd1, 0xd6, 0x70, 0xba, 0xe8, 0xb0, 0xbc, 0x46, - 0x4b, 0x06, 0x8f, 0x37, 0x66, 0xb0, 0xf7, 0xa6, 0xf5, 0xbc, 0xfd, 0x37, 0xed, 0x76, 0x2d, 0xbc, - 0x7d, 0x9a, 0xfb, 0x60, 0x32, 0xf7, 0xc1, 0x9f, 0xb9, 0x0f, 0xbe, 0x2f, 0x7c, 0x67, 0xb2, 0xf0, - 0x9d, 0x9f, 0x0b, 0xdf, 0xf9, 0xfc, 0xe6, 0x1f, 0xd7, 0x7a, 0x6c, 0x48, 0x62, 0x8d, 0x7b, 0x2c, - 0x48, 0x32, 0xc2, 0x05, 0x7e, 0x58, 0x2e, 0x68, 0x65, 0x5e, 0xdc, 0xaa, 0xd6, 0xe6, 0xed, 0xdf, - 0x00, 0x00, 0x00, 0xff, 0xff, 0x66, 0x13, 0x6b, 0x83, 0xbc, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - // MintDerivative defines a method for converting a delegation into staking deriviatives. - MintDerivative(ctx context.Context, in *MsgMintDerivative, opts ...grpc.CallOption) (*MsgMintDerivativeResponse, error) - // BurnDerivative defines a method for converting staking deriviatives into a delegation. - BurnDerivative(ctx context.Context, in *MsgBurnDerivative, opts ...grpc.CallOption) (*MsgBurnDerivativeResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) MintDerivative(ctx context.Context, in *MsgMintDerivative, opts ...grpc.CallOption) (*MsgMintDerivativeResponse, error) { - out := new(MsgMintDerivativeResponse) - err := c.cc.Invoke(ctx, "/kava.liquid.v1beta1.Msg/MintDerivative", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) BurnDerivative(ctx context.Context, in *MsgBurnDerivative, opts ...grpc.CallOption) (*MsgBurnDerivativeResponse, error) { - out := new(MsgBurnDerivativeResponse) - err := c.cc.Invoke(ctx, "/kava.liquid.v1beta1.Msg/BurnDerivative", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // MintDerivative defines a method for converting a delegation into staking deriviatives. - MintDerivative(context.Context, *MsgMintDerivative) (*MsgMintDerivativeResponse, error) - // BurnDerivative defines a method for converting staking deriviatives into a delegation. - BurnDerivative(context.Context, *MsgBurnDerivative) (*MsgBurnDerivativeResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) MintDerivative(ctx context.Context, req *MsgMintDerivative) (*MsgMintDerivativeResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method MintDerivative not implemented") -} -func (*UnimplementedMsgServer) BurnDerivative(ctx context.Context, req *MsgBurnDerivative) (*MsgBurnDerivativeResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method BurnDerivative not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_MintDerivative_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgMintDerivative) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).MintDerivative(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.liquid.v1beta1.Msg/MintDerivative", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).MintDerivative(ctx, req.(*MsgMintDerivative)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_BurnDerivative_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgBurnDerivative) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).BurnDerivative(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.liquid.v1beta1.Msg/BurnDerivative", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).BurnDerivative(ctx, req.(*MsgBurnDerivative)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.liquid.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "MintDerivative", - Handler: _Msg_MintDerivative_Handler, - }, - { - MethodName: "BurnDerivative", - Handler: _Msg_BurnDerivative_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/liquid/v1beta1/tx.proto", -} - -func (m *MsgMintDerivative) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgMintDerivative) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMintDerivative) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Validator) > 0 { - i -= len(m.Validator) - copy(dAtA[i:], m.Validator) - i = encodeVarintTx(dAtA, i, uint64(len(m.Validator))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgMintDerivativeResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgMintDerivativeResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMintDerivativeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Received.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *MsgBurnDerivative) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgBurnDerivative) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgBurnDerivative) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Validator) > 0 { - i -= len(m.Validator) - copy(dAtA[i:], m.Validator) - i = encodeVarintTx(dAtA, i, uint64(len(m.Validator))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgBurnDerivativeResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgBurnDerivativeResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgBurnDerivativeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Received.Size() - i -= size - if _, err := m.Received.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgMintDerivative) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Validator) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgMintDerivativeResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Received.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgBurnDerivative) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Validator) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgBurnDerivativeResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Received.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgMintDerivative) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgMintDerivative: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgMintDerivative: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Validator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgMintDerivativeResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgMintDerivativeResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgMintDerivativeResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Received", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Received.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgBurnDerivative) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgBurnDerivative: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgBurnDerivative: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Validator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgBurnDerivativeResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgBurnDerivativeResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgBurnDerivativeResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Received", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Received.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/router/client/cli/tx.go b/x/router/client/cli/tx.go deleted file mode 100644 index 51b30ecc..00000000 --- a/x/router/client/cli/tx.go +++ /dev/null @@ -1,175 +0,0 @@ -package cli - -import ( - "fmt" - - "github.com/spf13/cobra" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/0glabs/0g-chain/x/router/types" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - liquidTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "router transactions subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - getCmdMintDeposit(), - getCmdDelegateMintDeposit(), - getCmdWithdrawBurn(), - getCmdWithdrawBurnUndelegate(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - liquidTxCmd.AddCommand(cmds...) - - return liquidTxCmd -} - -func getCmdMintDeposit() *cobra.Command { - return &cobra.Command{ - Use: "mint-deposit [validator-addr] [amount]", - Short: "mints staking derivative from a delegation and deposits them to earn", - Args: cobra.ExactArgs(2), - Example: fmt.Sprintf( - `%s tx %s mint-deposit kavavaloper16lnfpgn6llvn4fstg5nfrljj6aaxyee9z59jqd 10000000ukava --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - valAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - coin, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - msg := types.NewMsgMintDeposit(clientCtx.GetFromAddress(), valAddr, coin) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} - -func getCmdDelegateMintDeposit() *cobra.Command { - return &cobra.Command{ - Use: "delegate-mint-deposit [validator-addr] [amount]", - Short: "delegates tokens, mints staking derivative from a them, and deposits them to earn", - Args: cobra.ExactArgs(2), - Example: fmt.Sprintf( - `%s tx %s delegate-mint-deposit kavavaloper16lnfpgn6llvn4fstg5nfrljj6aaxyee9z59jqd 10000000ukava --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - valAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - coin, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - msg := types.NewMsgDelegateMintDeposit(clientCtx.GetFromAddress(), valAddr, coin) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} - -func getCmdWithdrawBurn() *cobra.Command { - return &cobra.Command{ - Use: "withdraw-burn [validator-addr] [amount]", - Short: "withdraws staking derivatives from earn and burns them to redeem a delegation", - Example: fmt.Sprintf( - `%s tx %s withdraw-burn kavavaloper16lnfpgn6llvn4fstg5nfrljj6aaxyee9z59jqd 10000000ukava --from `, version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - valAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - amount, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - msg := types.NewMsgWithdrawBurn(clientCtx.GetFromAddress(), valAddr, amount) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} - -func getCmdWithdrawBurnUndelegate() *cobra.Command { - return &cobra.Command{ - Use: "withdraw-burn-undelegate [validator-addr] [amount]", - Short: "withdraws staking derivatives from earn, burns them to redeem a delegation, then unstakes the delegation", - Example: fmt.Sprintf( - `%s tx %s withdraw-burn-undelegate kavavaloper16lnfpgn6llvn4fstg5nfrljj6aaxyee9z59jqd 10000000ukava --from `, version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - valAddr, err := sdk.ValAddressFromBech32(args[0]) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - amount, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - msg := types.NewMsgWithdrawBurnUndelegate(clientCtx.GetFromAddress(), valAddr, amount) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} diff --git a/x/router/keeper/keeper.go b/x/router/keeper/keeper.go deleted file mode 100644 index d9dc08ed..00000000 --- a/x/router/keeper/keeper.go +++ /dev/null @@ -1,26 +0,0 @@ -package keeper - -import ( - "github.com/0glabs/0g-chain/x/router/types" -) - -// Keeper is the keeper for the module -type Keeper struct { - earnKeeper types.EarnKeeper - liquidKeeper types.LiquidKeeper - stakingKeeper types.StakingKeeper -} - -// NewKeeper creates a new keeper -func NewKeeper( - earnKeeper types.EarnKeeper, - liquidKeeper types.LiquidKeeper, - stakingKeeper types.StakingKeeper, -) Keeper { - - return Keeper{ - earnKeeper: earnKeeper, - liquidKeeper: liquidKeeper, - stakingKeeper: stakingKeeper, - } -} diff --git a/x/router/keeper/msg_server.go b/x/router/keeper/msg_server.go deleted file mode 100644 index 3b623f08..00000000 --- a/x/router/keeper/msg_server.go +++ /dev/null @@ -1,202 +0,0 @@ -package keeper - -import ( - "context" - "time" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - earntypes "github.com/0glabs/0g-chain/x/earn/types" - "github.com/0glabs/0g-chain/x/router/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the module's MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -// MintDeposit converts a delegation into staking derivatives and deposits it all into an earn vault -func (m msgServer) MintDeposit(goCtx context.Context, msg *types.MsgMintDeposit) (*types.MsgMintDepositResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - val, err := sdk.ValAddressFromBech32(msg.Validator) - if err != nil { - return nil, err - } - - derivative, err := m.keeper.liquidKeeper.MintDerivative(ctx, depositor, val, msg.Amount) - if err != nil { - return nil, err - } - err = m.keeper.earnKeeper.Deposit(ctx, depositor, derivative, earntypes.STRATEGY_TYPE_SAVINGS) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.String()), - ), - ) - return &types.MsgMintDepositResponse{}, nil -} - -// DelegateMintDeposit delegates tokens to a validator, then converts them into staking derivatives, -// then deposits to an earn vault. -func (m msgServer) DelegateMintDeposit(goCtx context.Context, msg *types.MsgDelegateMintDeposit) (*types.MsgDelegateMintDepositResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - valAddr, err := sdk.ValAddressFromBech32(msg.Validator) - if err != nil { - return nil, err - } - validator, found := m.keeper.stakingKeeper.GetValidator(ctx, valAddr) - if !found { - return nil, stakingtypes.ErrNoValidatorFound - } - bondDenom := m.keeper.stakingKeeper.BondDenom(ctx) - if msg.Amount.Denom != bondDenom { - return nil, errorsmod.Wrapf( - sdkerrors.ErrInvalidRequest, "invalid coin denomination: got %s, expected %s", msg.Amount.Denom, bondDenom, - ) - } - newShares, err := m.keeper.stakingKeeper.Delegate(ctx, depositor, msg.Amount.Amount, stakingtypes.Unbonded, validator, true) - if err != nil { - return nil, err - } - - derivativeMinted, err := m.keeper.liquidKeeper.MintDerivative(ctx, depositor, valAddr, msg.Amount) - if err != nil { - return nil, err - } - - err = m.keeper.earnKeeper.Deposit(ctx, depositor, derivativeMinted, earntypes.STRATEGY_TYPE_SAVINGS) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - stakingtypes.EventTypeDelegate, - sdk.NewAttribute(stakingtypes.AttributeKeyValidator, valAddr.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), - sdk.NewAttribute(stakingtypes.AttributeKeyNewShares, newShares.String()), - ), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.String()), - ), - }) - - return &types.MsgDelegateMintDepositResponse{}, nil -} - -// WithdrawBurn removes staking derivatives from an earn vault and converts them back to a staking delegation. -func (m msgServer) WithdrawBurn(goCtx context.Context, msg *types.MsgWithdrawBurn) (*types.MsgWithdrawBurnResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositor, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - return nil, err - } - val, err := sdk.ValAddressFromBech32(msg.Validator) - if err != nil { - return nil, err - } - - tokenAmount, err := m.keeper.liquidKeeper.DerivativeFromTokens(ctx, val, msg.Amount) - if err != nil { - return nil, err - } - - withdrawnAmount, err := m.keeper.earnKeeper.Withdraw(ctx, depositor, tokenAmount, earntypes.STRATEGY_TYPE_SAVINGS) - if err != nil { - return nil, err - } - - _, err = m.keeper.liquidKeeper.BurnDerivative(ctx, depositor, val, withdrawnAmount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.String()), - ), - ) - - return &types.MsgWithdrawBurnResponse{}, nil -} - -// WithdrawBurnUndelegate removes staking derivatives from an earn vault, converts them to a staking delegation, -// then undelegates them from their validator. -func (m msgServer) WithdrawBurnUndelegate(goCtx context.Context, msg *types.MsgWithdrawBurnUndelegate) (*types.MsgWithdrawBurnUndelegateResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositor, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - return nil, err - } - val, err := sdk.ValAddressFromBech32(msg.Validator) - if err != nil { - return nil, err - } - - tokenAmount, err := m.keeper.liquidKeeper.DerivativeFromTokens(ctx, val, msg.Amount) - if err != nil { - return nil, err - } - - withdrawnAmount, err := m.keeper.earnKeeper.Withdraw(ctx, depositor, tokenAmount, earntypes.STRATEGY_TYPE_SAVINGS) - if err != nil { - return nil, err - } - - sharesReturned, err := m.keeper.liquidKeeper.BurnDerivative(ctx, depositor, val, withdrawnAmount) - if err != nil { - return nil, err - } - - completionTime, err := m.keeper.stakingKeeper.Undelegate(ctx, depositor, val, sharesReturned) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvents(sdk.Events{ - sdk.NewEvent( - stakingtypes.EventTypeUnbond, - sdk.NewAttribute(stakingtypes.AttributeKeyValidator, val.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), - sdk.NewAttribute(stakingtypes.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)), - ), - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.String()), - ), - }) - return &types.MsgWithdrawBurnUndelegateResponse{}, nil -} diff --git a/x/router/keeper/msg_server_test.go b/x/router/keeper/msg_server_test.go deleted file mode 100644 index 5b0afa63..00000000 --- a/x/router/keeper/msg_server_test.go +++ /dev/null @@ -1,322 +0,0 @@ -package keeper_test - -import ( - "fmt" - "testing" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/app" - earntypes "github.com/0glabs/0g-chain/x/earn/types" - "github.com/0glabs/0g-chain/x/router/keeper" - "github.com/0glabs/0g-chain/x/router/testutil" - "github.com/0glabs/0g-chain/x/router/types" -) - -type msgServerTestSuite struct { - testutil.Suite - - msgServer types.MsgServer -} - -func (suite *msgServerTestSuite) SetupTest() { - suite.Suite.SetupTest() - - suite.msgServer = keeper.NewMsgServerImpl(suite.Keeper) -} - -func TestMsgServerTestSuite(t *testing.T) { - suite.Run(t, new(msgServerTestSuite)) -} - -func (suite *msgServerTestSuite) TestMintDeposit_Events() { - user, valAddr, delegation := suite.setupValidatorAndDelegation() - suite.setupEarnForDeposits(valAddr) - - msg := types.NewMsgMintDeposit( - user, - valAddr, - suite.NewBondCoin(delegation), - ) - _, err := suite.msgServer.MintDeposit(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - - suite.EventsContains(suite.Ctx.EventManager().Events(), - sdk.NewEvent(sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, user.String()), - ), - ) -} - -func (suite *msgServerTestSuite) TestDelegateMintDeposit_Events() { - user, valAddr, balance := suite.setupValidator() - suite.setupEarnForDeposits(valAddr) - - msg := types.NewMsgDelegateMintDeposit( - user, - valAddr, - suite.NewBondCoin(balance), - ) - _, err := suite.msgServer.DelegateMintDeposit(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - - suite.EventsContains(suite.Ctx.EventManager().Events(), - sdk.NewEvent(sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, user.String()), - ), - ) - expectedShares := sdk.NewDecFromInt(msg.Amount.Amount) // no slashes so shares equal staked tokens - suite.EventsContains(suite.Ctx.EventManager().Events(), - sdk.NewEvent( - stakingtypes.EventTypeDelegate, - sdk.NewAttribute(stakingtypes.AttributeKeyValidator, msg.Validator), - sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), - sdk.NewAttribute(stakingtypes.AttributeKeyNewShares, expectedShares.String()), - ), - ) -} - -func (suite *msgServerTestSuite) TestWithdrawBurn_Events() { - user, valAddr, delegated := suite.setupDerivatives() - // clear events from setup - suite.Ctx = suite.Ctx.WithEventManager(sdk.NewEventManager()) - - msg := types.NewMsgWithdrawBurn( - user, - valAddr, - // in this setup where the validator is not slashed, the derivative amount is equal to the staked balance - suite.NewBondCoin(delegated.Amount), - ) - _, err := suite.msgServer.WithdrawBurn(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - - suite.EventsContains(suite.Ctx.EventManager().Events(), - sdk.NewEvent(sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, user.String()), - ), - ) -} - -func (suite *msgServerTestSuite) TestWithdrawBurnUndelegate_Events() { - user, valAddr, delegated := suite.setupDerivatives() - // clear events from setup - suite.Ctx = suite.Ctx.WithEventManager(sdk.NewEventManager()) - - msg := types.NewMsgWithdrawBurnUndelegate( - user, - valAddr, - // in this setup where the validator is not slashed, the derivative amount is equal to the staked balance - suite.NewBondCoin(delegated.Amount), - ) - _, err := suite.msgServer.WithdrawBurnUndelegate(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - - suite.EventsContains(suite.Ctx.EventManager().Events(), - sdk.NewEvent(sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, user.String()), - ), - ) - unbondingTime := suite.StakingKeeper.UnbondingTime(suite.Ctx) - completionTime := suite.Ctx.BlockTime().Add(unbondingTime) - suite.EventsContains(suite.Ctx.EventManager().Events(), - sdk.NewEvent( - stakingtypes.EventTypeUnbond, - sdk.NewAttribute(stakingtypes.AttributeKeyValidator, msg.Validator), - sdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()), - sdk.NewAttribute(stakingtypes.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)), - ), - ) -} - -func (suite *msgServerTestSuite) TestMintDepositAndWithdrawBurn_TransferEntireBalance() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, user := addrs[0], addrs[1] - valAddr := sdk.ValAddress(valAccAddr) - - derivativeDenom := suite.setupEarnForDeposits(valAddr) - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(sdkmath.NewInt(1e9))) - vesting := sdkmath.NewInt(1000) - suite.CreateVestingAccountWithAddress(user, - suite.NewBondCoins(sdkmath.NewInt(1e9).Add(vesting)), - suite.NewBondCoins(vesting), - ) - - // Create a slashed validator, where the delegator owns fractional tokens. - suite.CreateNewUnbondedValidator(valAddr, sdkmath.NewInt(1e9)) - suite.CreateDelegation(valAddr, user, sdkmath.NewInt(1e9)) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - suite.SlashValidator(valAddr, sdk.MustNewDecFromStr("0.666666666666666667")) - - // Query the full staked balance and convert it all to derivatives - // user technically 333_333_333.333333333333333333 staked tokens without rounding - delegation := suite.QueryStaking_Delegation(valAddr, user) - suite.Equal(sdkmath.NewInt(333_333_333), delegation.Balance.Amount) - - msgDeposit := types.NewMsgMintDeposit( - user, - valAddr, - delegation.Balance, - ) - _, err := suite.msgServer.MintDeposit(sdk.WrapSDKContext(suite.Ctx), msgDeposit) - suite.Require().NoError(err) - - // There should be no extractable balance left in delegation - suite.DelegationBalanceLessThan(valAddr, user, sdkmath.NewInt(1)) - // All derivative coins should be deposited to earn - suite.AccountBalanceOfEqual(user, derivativeDenom, sdk.ZeroInt()) - // Earn vault has all minted derivatives - suite.VaultAccountValueEqual(user, sdk.NewInt64Coin(derivativeDenom, 999_999_998)) // 2 lost in conversion - - // Query the full kava balance of the earn deposit and convert all to a delegation - deposit := suite.QueryEarn_VaultValue(user, "bkava") - suite.Equal(suite.NewBondCoins(sdkmath.NewInt(333_333_332)), deposit.Value) // 1 lost due to lost shares - - msgWithdraw := types.NewMsgWithdrawBurn( - user, - valAddr, - deposit.Value[0], - ) - _, err = suite.msgServer.WithdrawBurn(sdk.WrapSDKContext(suite.Ctx), msgWithdraw) - suite.Require().NoError(err) - - // There should be no earn deposit left (earn removes dust amounts) - suite.VaultAccountSharesEqual(user, nil) - // All derivative coins should be converted to a delegation - suite.AccountBalanceOfEqual(user, derivativeDenom, sdk.ZeroInt()) - // The user should get back most of their original deposited balance - suite.DelegationBalanceInDeltaBelow(valAddr, user, sdkmath.NewInt(333_333_332), sdkmath.NewInt(2)) -} - -func (suite *msgServerTestSuite) TestDelegateMintDepositAndWithdrawBurnUndelegate_TransferEntireBalance() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, user := addrs[0], addrs[1] - valAddr := sdk.ValAddress(valAccAddr) - - derivativeDenom := suite.setupEarnForDeposits(valAddr) - - valBalance := sdkmath.NewInt(1e9) - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(valBalance)) - - // Create a slashed validator, where a future delegator will own fractional tokens. - suite.CreateNewUnbondedValidator(valAddr, valBalance) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - suite.SlashValidator(valAddr, sdk.MustNewDecFromStr("0.4")) // tokens remaining 600_000_000 - - userBalance := sdkmath.NewInt(100e6) - vesting := sdkmath.NewInt(1000) - suite.CreateVestingAccountWithAddress(user, - suite.NewBondCoins(userBalance.Add(vesting)), - suite.NewBondCoins(vesting), - ) - - // Query the full vested balance and convert it all to derivatives - balance := suite.QueryBank_SpendableBalance(user) - suite.Equal(suite.NewBondCoins(userBalance), balance) - - // When delegation is created it will have 166_666_666.666666666666666666 shares - // newShares = validatorShares * newTokens/validatorTokens, truncated to 18 decimals - msgDeposit := types.NewMsgDelegateMintDeposit( - user, - valAddr, - balance[0], - ) - _, err := suite.msgServer.DelegateMintDeposit(sdk.WrapSDKContext(suite.Ctx), msgDeposit) - suite.Require().NoError(err) - - // All spendable balance should be withdrawn - suite.AccountSpendableBalanceEqual(user, sdk.NewCoins()) - // Since shares are newly created, the exact amount should be converted to derivatives, leaving none behind - suite.DelegationSharesEqual(valAddr, user, sdk.ZeroDec()) - // All derivative coins should be deposited to earn - suite.AccountBalanceOfEqual(user, derivativeDenom, sdk.ZeroInt()) - - suite.VaultAccountValueEqual(user, sdk.NewInt64Coin(derivativeDenom, 166_666_666)) - - // Query the full kava balance of the earn deposit and convert all to a delegation - deposit := suite.QueryEarn_VaultValue(user, "bkava") - suite.Equal(suite.NewBondCoins(sdkmath.NewInt(99_999_999)), deposit.Value) // 1 lost due to truncating shares to derivatives - - msgWithdraw := types.NewMsgWithdrawBurnUndelegate( - user, - valAddr, - deposit.Value[0], - ) - _, err = suite.msgServer.WithdrawBurnUndelegate(sdk.WrapSDKContext(suite.Ctx), msgWithdraw) - suite.Require().NoError(err) - - // There should be no earn deposit left (earn removes dust amounts) - suite.VaultAccountSharesEqual(user, nil) - // All derivative coins should be converted to a delegation - suite.AccountBalanceOfEqual(user, derivativeDenom, sdk.ZeroInt()) - // There should be zero shares left because undelegate removes all created by burn. - suite.AccountBalanceOfEqual(user, derivativeDenom, sdk.ZeroInt()) - // User should have most of their original balance back in an unbonding delegation - suite.UnbondingDelegationInDeltaBelow(valAddr, user, userBalance, sdkmath.NewInt(2)) -} - -func (suite *msgServerTestSuite) setupValidator() (sdk.AccAddress, sdk.ValAddress, sdkmath.Int) { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, user := addrs[0], addrs[1] - valAddr := sdk.ValAddress(valAccAddr) - - balance := sdkmath.NewInt(1e9) - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(balance)) - suite.CreateAccountWithAddress(user, suite.NewBondCoins(balance)) - - suite.CreateNewUnbondedValidator(valAddr, balance) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - return user, valAddr, balance -} - -func (suite *msgServerTestSuite) setupValidatorAndDelegation() (sdk.AccAddress, sdk.ValAddress, sdkmath.Int) { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, user := addrs[0], addrs[1] - valAddr := sdk.ValAddress(valAccAddr) - - balance := sdkmath.NewInt(1e9) - - suite.CreateAccountWithAddress(valAccAddr, suite.NewBondCoins(balance)) - suite.CreateAccountWithAddress(user, suite.NewBondCoins(balance)) - - suite.CreateNewUnbondedValidator(valAddr, balance) - suite.CreateDelegation(valAddr, user, balance) - staking.EndBlocker(suite.Ctx, suite.StakingKeeper) - return user, valAddr, balance -} - -func (suite *msgServerTestSuite) setupEarnForDeposits(valAddr sdk.ValAddress) string { - suite.CreateVault("bkava", earntypes.StrategyTypes{earntypes.STRATEGY_TYPE_SAVINGS}, false, nil) - derivativeDenom := fmt.Sprintf("bkava-%s", valAddr) - suite.SetSavingsSupportedDenoms([]string{derivativeDenom}) - return derivativeDenom -} - -func (suite *msgServerTestSuite) setupDerivatives() (sdk.AccAddress, sdk.ValAddress, sdk.Coin) { - user, valAddr, delegation := suite.setupValidatorAndDelegation() - suite.setupEarnForDeposits(valAddr) - - msg := types.NewMsgMintDeposit( - user, - valAddr, - suite.NewBondCoin(delegation), - ) - _, err := suite.msgServer.MintDeposit(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - - derivativeDenom := fmt.Sprintf("bkava-%s", valAddr) - derivatives, err := suite.EarnKeeper.GetVaultAccountValue(suite.Ctx, derivativeDenom, user) - suite.Require().NoError(err) - - return user, valAddr, derivatives -} diff --git a/x/router/module.go b/x/router/module.go deleted file mode 100644 index ad53acd0..00000000 --- a/x/router/module.go +++ /dev/null @@ -1,118 +0,0 @@ -package router - -import ( - "encoding/json" - - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/0glabs/0g-chain/x/router/client/cli" - "github.com/0glabs/0g-chain/x/router/keeper" - "github.com/0glabs/0g-chain/x/router/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name get module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(_ codec.JSONCodec) json.RawMessage { - return []byte("{}") -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(_ codec.JSONCodec, _ client.TxEncodingConfig, _ json.RawMessage) error { - return nil -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(_ client.Context, _ *runtime.ServeMux) { -} - -// GetTxCmd returns the root tx command for the module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return nil -} - -//____________________________________________________________________________ - -// AppModule app module type -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - } -} - -// Name module name -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// RegisterInvariants register module invariants -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return 1 -} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) -} - -// InitGenesis module init-genesis -func (am AppModule) InitGenesis(_ sdk.Context, _ codec.JSONCodec, _ json.RawMessage) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} - -// ExportGenesis module export genesis -func (am AppModule) ExportGenesis(_ sdk.Context, cdc codec.JSONCodec) json.RawMessage { - return am.DefaultGenesis(cdc) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - -// EndBlock module end-block -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/router/testutil/suite.go b/x/router/testutil/suite.go deleted file mode 100644 index 2f4449fe..00000000 --- a/x/router/testutil/suite.go +++ /dev/null @@ -1,365 +0,0 @@ -package testutil - -import ( - "fmt" - "reflect" - - sdkmath "cosmossdk.io/math" - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/suite" - - "github.com/0glabs/0g-chain/app" - earnkeeper "github.com/0glabs/0g-chain/x/earn/keeper" - earntypes "github.com/0glabs/0g-chain/x/earn/types" - "github.com/0glabs/0g-chain/x/router/keeper" - savingstypes "github.com/0glabs/0g-chain/x/savings/types" -) - -// Test suite used for all keeper tests -type Suite struct { - suite.Suite - App app.TestApp - Ctx sdk.Context - Keeper keeper.Keeper - BankKeeper bankkeeper.Keeper - StakingKeeper *stakingkeeper.Keeper - EarnKeeper earnkeeper.Keeper -} - -// The default state used by each test -func (suite *Suite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - tApp.InitializeFromGenesisStates() - - suite.App = tApp - suite.Ctx = ctx - suite.Keeper = tApp.GetRouterKeeper() - suite.StakingKeeper = tApp.GetStakingKeeper() - suite.BankKeeper = tApp.GetBankKeeper() - suite.EarnKeeper = tApp.GetEarnKeeper() -} - -// CreateAccount creates a new account from the provided balance and address -func (suite *Suite) CreateAccountWithAddress(addr sdk.AccAddress, initialBalance sdk.Coins) authtypes.AccountI { - ak := suite.App.GetAccountKeeper() - - acc := ak.NewAccountWithAddress(suite.Ctx, addr) - ak.SetAccount(suite.Ctx, acc) - - err := suite.App.FundAccount(suite.Ctx, acc.GetAddress(), initialBalance) - suite.Require().NoError(err) - - return acc -} - -// CreateVestingAccount creates a new vesting account. `vestingBalance` should be a fraction of `initialBalance`. -func (suite *Suite) CreateVestingAccountWithAddress(addr sdk.AccAddress, initialBalance sdk.Coins, vestingBalance sdk.Coins) authtypes.AccountI { - if vestingBalance.IsAnyGT(initialBalance) { - panic("vesting balance must be less than initial balance") - } - acc := suite.CreateAccountWithAddress(addr, initialBalance) - bacc := acc.(*authtypes.BaseAccount) - - periods := vestingtypes.Periods{ - vestingtypes.Period{ - Length: 31556952, - Amount: vestingBalance, - }, - } - vacc := vestingtypes.NewPeriodicVestingAccount(bacc, vestingBalance, suite.Ctx.BlockTime().Unix(), periods) - suite.App.GetAccountKeeper().SetAccount(suite.Ctx, vacc) - return vacc -} - -// AddCoinsToModule adds coins to the a module account, creating it if it doesn't exist. -func (suite *Suite) AddCoinsToModule(module string, amount sdk.Coins) { - err := suite.App.FundModuleAccount(suite.Ctx, module, amount) - suite.Require().NoError(err) -} - -// AccountBalanceEqual checks if an account has the specified coins. -func (suite *Suite) AccountBalanceEqual(addr sdk.AccAddress, coins sdk.Coins) { - balance := suite.BankKeeper.GetAllBalances(suite.Ctx, addr) - suite.Equalf(coins, balance, "expected account balance to equal coins %s, but got %s", coins, balance) -} - -// AccountBalanceOfEqual checks if an account has the specified amount of one denom. -func (suite *Suite) AccountBalanceOfEqual(addr sdk.AccAddress, denom string, amount sdkmath.Int) { - balance := suite.BankKeeper.GetBalance(suite.Ctx, addr, denom).Amount - suite.Equalf(amount, balance, "expected account balance to have %[1]s%[2]s, but got %[3]s%[2]s", amount, denom, balance) -} - -// AccountSpendableBalanceEqual checks if an account has the specified coins unlocked. -func (suite *Suite) AccountSpendableBalanceEqual(addr sdk.AccAddress, amount sdk.Coins) { - balance := suite.BankKeeper.SpendableCoins(suite.Ctx, addr) - expectedAmt := amount - if expectedAmt == nil { - expectedAmt = sdk.NewCoins() - } - suite.Equalf(expectedAmt, balance, "expected account spendable balance to equal coins %s, but got %s", amount, balance) -} - -func (suite *Suite) QueryBank_SpendableBalance(user sdk.AccAddress) sdk.Coins { - res, err := suite.BankKeeper.SpendableBalances( - sdk.WrapSDKContext(suite.Ctx), - &banktypes.QuerySpendableBalancesRequest{ - Address: user.String(), - }, - ) - suite.Require().NoError(err) - return *&res.Balances -} - -func (suite *Suite) deliverMsgCreateValidator(ctx sdk.Context, address sdk.ValAddress, selfDelegation sdk.Coin) error { - msg, err := stakingtypes.NewMsgCreateValidator( - address, - ed25519.GenPrivKey().PubKey(), - selfDelegation, - stakingtypes.Description{}, - stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - sdkmath.NewInt(1e6), - ) - if err != nil { - return err - } - - msgServer := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - _, err = msgServer.CreateValidator(sdk.WrapSDKContext(suite.Ctx), msg) - return err -} - -// NewBondCoin creates a Coin with the current staking denom. -func (suite *Suite) NewBondCoin(amount sdkmath.Int) sdk.Coin { - stakingDenom := suite.StakingKeeper.BondDenom(suite.Ctx) - return sdk.NewCoin(stakingDenom, amount) -} - -// NewBondCoins creates Coins with the current staking denom. -func (suite *Suite) NewBondCoins(amount sdkmath.Int) sdk.Coins { - return sdk.NewCoins(suite.NewBondCoin(amount)) -} - -// CreateNewUnbondedValidator creates a new validator in the staking module. -// New validators are unbonded until the end blocker is run. -func (suite *Suite) CreateNewUnbondedValidator(addr sdk.ValAddress, selfDelegation sdkmath.Int) stakingtypes.Validator { - // Create a validator - err := suite.deliverMsgCreateValidator(suite.Ctx, addr, suite.NewBondCoin(selfDelegation)) - suite.Require().NoError(err) - - // New validators are created in an unbonded state. Note if the end blocker is run later this validator could become bonded. - - validator, found := suite.StakingKeeper.GetValidator(suite.Ctx, addr) - suite.Require().True(found) - return validator -} - -// SlashValidator burns tokens staked in a validator. new_tokens = old_tokens * (1-slashFraction) -func (suite *Suite) SlashValidator(addr sdk.ValAddress, slashFraction sdk.Dec) { - validator, found := suite.StakingKeeper.GetValidator(suite.Ctx, addr) - suite.Require().True(found) - consAddr, err := validator.GetConsAddr() - suite.Require().NoError(err) - - // Assume infraction was at current height. Note unbonding delegations and redelegations are only slashed if created after - // the infraction height so none will be slashed. - infractionHeight := suite.Ctx.BlockHeight() - - power := suite.StakingKeeper.TokensToConsensusPower(suite.Ctx, validator.GetTokens()) - - suite.StakingKeeper.Slash(suite.Ctx, consAddr, infractionHeight, power, slashFraction) -} - -// CreateDelegation delegates tokens to a validator. -func (suite *Suite) CreateDelegation(valAddr sdk.ValAddress, delegator sdk.AccAddress, amount sdkmath.Int) sdk.Dec { - stakingDenom := suite.StakingKeeper.BondDenom(suite.Ctx) - msg := stakingtypes.NewMsgDelegate( - delegator, - valAddr, - sdk.NewCoin(stakingDenom, amount), - ) - - msgServer := stakingkeeper.NewMsgServerImpl(suite.StakingKeeper) - _, err := msgServer.Delegate(sdk.WrapSDKContext(suite.Ctx), msg) - suite.Require().NoError(err) - - del, found := suite.StakingKeeper.GetDelegation(suite.Ctx, delegator, valAddr) - suite.Require().True(found) - return del.Shares -} - -// DelegationSharesEqual checks if a delegation has the specified shares. -// It expects delegations with zero shares to not be stored in state. -func (suite *Suite) DelegationSharesEqual(valAddr sdk.ValAddress, delegator sdk.AccAddress, shares sdk.Dec) bool { - del, found := suite.StakingKeeper.GetDelegation(suite.Ctx, delegator, valAddr) - - if shares.IsZero() { - return suite.Falsef(found, "expected delegator to not be found, got %s shares", del.Shares) - } else { - res := suite.True(found, "expected delegator to be found") - return res && suite.Truef(shares.Equal(del.Shares), "expected %s delegator shares but got %s", shares, del.Shares) - } -} - -// DelegationBalanceLessThan checks if a delegation's staked token balance is less the specified amount. -// It treats not found delegations as having zero shares. -func (suite *Suite) DelegationBalanceLessThan(valAddr sdk.ValAddress, delegator sdk.AccAddress, max sdkmath.Int) bool { - shares := sdk.ZeroDec() - del, found := suite.StakingKeeper.GetDelegation(suite.Ctx, delegator, valAddr) - if found { - shares = del.Shares - } - - val, found := suite.StakingKeeper.GetValidator(suite.Ctx, valAddr) - suite.Require().Truef(found, "expected validator to be found") - - tokens := val.TokensFromShares(shares).TruncateInt() - - return suite.Truef(tokens.LT(max), "expected delegation balance to be less than %s, got %s", max, tokens) -} - -// DelegationBalanceInDeltaBelow checks if a delegation's staked token balance is between `expected` and `expected - delta` inclusive. -// It treats not found delegations as having zero shares. -func (suite *Suite) DelegationBalanceInDeltaBelow(valAddr sdk.ValAddress, delegator sdk.AccAddress, expected, delta sdkmath.Int) bool { - shares := sdk.ZeroDec() - del, found := suite.StakingKeeper.GetDelegation(suite.Ctx, delegator, valAddr) - if found { - shares = del.Shares - } - - val, found := suite.StakingKeeper.GetValidator(suite.Ctx, valAddr) - suite.Require().Truef(found, "expected validator to be found") - - tokens := val.TokensFromShares(shares).TruncateInt() - - lte := suite.Truef(tokens.LTE(expected), "expected delegation balance to be less than or equal to %s, got %s", expected, tokens) - gte := suite.Truef(tokens.GTE(expected.Sub(delta)), "expected delegation balance to be greater than or equal to %s, got %s", expected.Sub(delta), tokens) - return lte && gte -} - -// UnbondingDelegationInDeltaBelow checks if the total balance in an unbonding delegation is between `expected` and `expected - delta` inclusive. -func (suite *Suite) UnbondingDelegationInDeltaBelow(valAddr sdk.ValAddress, delegator sdk.AccAddress, expected, delta sdkmath.Int) bool { - tokens := sdk.ZeroInt() - ubd, found := suite.StakingKeeper.GetUnbondingDelegation(suite.Ctx, delegator, valAddr) - if found { - for _, entry := range ubd.Entries { - tokens = tokens.Add(entry.Balance) - } - } - - lte := suite.Truef(tokens.LTE(expected), "expected unbonding delegation balance to be less than or equal to %s, got %s", expected, tokens) - gte := suite.Truef(tokens.GTE(expected.Sub(delta)), "expected unbonding delegation balance to be greater than or equal to %s, got %s", expected.Sub(delta), tokens) - return lte && gte -} - -func (suite *Suite) QueryStaking_Delegation(valAddr sdk.ValAddress, delegator sdk.AccAddress) stakingtypes.DelegationResponse { - stakingQuery := stakingkeeper.Querier{Keeper: suite.StakingKeeper} - res, err := stakingQuery.Delegation( - sdk.WrapSDKContext(suite.Ctx), - &stakingtypes.QueryDelegationRequest{ - DelegatorAddr: delegator.String(), - ValidatorAddr: valAddr.String(), - }, - ) - suite.Require().NoError(err) - return *res.DelegationResponse -} - -// EventsContains asserts that the expected event is in the provided events -func (suite *Suite) EventsContains(events sdk.Events, expectedEvent sdk.Event) { - foundMatch := false - for _, event := range events { - if event.Type == expectedEvent.Type { - if reflect.DeepEqual(attrsToMap(expectedEvent.Attributes), attrsToMap(event.Attributes)) { - foundMatch = true - } - } - } - - suite.True(foundMatch, fmt.Sprintf("event of type %s not found or did not match", expectedEvent.Type)) -} - -func attrsToMap(attrs []abci.EventAttribute) []sdk.Attribute { - out := []sdk.Attribute{} - - for _, attr := range attrs { - out = append(out, sdk.NewAttribute(string(attr.Key), string(attr.Value))) - } - - return out -} - -// CreateVault adds a new earn vault to the earn keeper parameters -func (suite *Suite) CreateVault( - vaultDenom string, - vaultStrategies earntypes.StrategyTypes, - isPrivateVault bool, - allowedDepositors []sdk.AccAddress, -) { - vault := earntypes.NewAllowedVault(vaultDenom, vaultStrategies, isPrivateVault, allowedDepositors) - - allowedVaults := suite.EarnKeeper.GetAllowedVaults(suite.Ctx) - allowedVaults = append(allowedVaults, vault) - - params := earntypes.NewParams(allowedVaults) - - suite.EarnKeeper.SetParams( - suite.Ctx, - params, - ) -} - -// SetSavingsSupportedDenoms overwrites the list of supported denoms in the savings module params. -func (suite *Suite) SetSavingsSupportedDenoms(denoms []string) { - sk := suite.App.GetSavingsKeeper() - sk.SetParams(suite.Ctx, savingstypes.NewParams(denoms)) -} - -// VaultAccountValueEqual asserts that the vault account value matches the provided coin amount. -func (suite *Suite) VaultAccountValueEqual(acc sdk.AccAddress, coin sdk.Coin) { - - accVaultBal, err := suite.EarnKeeper.GetVaultAccountValue(suite.Ctx, coin.Denom, acc) - suite.Require().NoError(err) - - suite.Require().Truef( - coin.Equal(accVaultBal), - "expected account vault balance to equal %s, but got %s", - coin, accVaultBal, - ) -} - -// VaultAccountSharesEqual asserts that the vault account shares match the provided values. -func (suite *Suite) VaultAccountSharesEqual(acc sdk.AccAddress, shares earntypes.VaultShares) { // TODO - - accVaultShares, found := suite.EarnKeeper.GetVaultAccountShares(suite.Ctx, acc) - if !found { - suite.Empty(shares) - } else { - suite.Equal(shares, accVaultShares) - } -} - -func (suite *Suite) QueryEarn_VaultValue(depositor sdk.AccAddress, vaultDenom string) earntypes.DepositResponse { - earnQuery := earnkeeper.NewQueryServerImpl(suite.EarnKeeper) - res, err := earnQuery.Deposits( - sdk.WrapSDKContext(suite.Ctx), - &earntypes.QueryDepositsRequest{ - Depositor: depositor.String(), - Denom: vaultDenom, - }, - ) - suite.Require().NoError(err) - suite.Require().Equalf(1, len(res.Deposits), "while earn supports one vault per denom, deposits response should be length 1") - return res.Deposits[0] -} diff --git a/x/router/types/codec.go b/x/router/types/codec.go deleted file mode 100644 index dfd5046c..00000000 --- a/x/router/types/codec.go +++ /dev/null @@ -1,46 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgMintDeposit{}, "router/MsgMintDeposit", nil) - cdc.RegisterConcrete(&MsgDelegateMintDeposit{}, "router/MsgDelegateMintDeposit", nil) - cdc.RegisterConcrete(&MsgWithdrawBurn{}, "router/MsgWithdrawBurn", nil) - cdc.RegisterConcrete(&MsgWithdrawBurnUndelegate{}, "router/MsgWithdrawBurnUndelegate", nil) -} - -// RegisterInterfaces registers proto messages under their interfaces for unmarshalling, -// in addition to registering the msg service for handling tx msgs -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgMintDeposit{}, - &MsgDelegateMintDeposit{}, - &MsgWithdrawBurn{}, - &MsgWithdrawBurnUndelegate{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - // ModuleCdc represents the legacy amino codec for the module - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/router/types/common_test.go b/x/router/types/common_test.go deleted file mode 100644 index 4cfbb221..00000000 --- a/x/router/types/common_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package types_test - -import ( - "os" - "testing" - - "github.com/0glabs/0g-chain/app" -) - -func TestMain(m *testing.M) { - app.SetSDKConfig() - os.Exit(m.Run()) -} diff --git a/x/router/types/expected_keepers.go b/x/router/types/expected_keepers.go deleted file mode 100644 index 3ed14c71..00000000 --- a/x/router/types/expected_keepers.go +++ /dev/null @@ -1,35 +0,0 @@ -package types - -import ( - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - earntypes "github.com/0glabs/0g-chain/x/earn/types" -) - -type StakingKeeper interface { - BondDenom(ctx sdk.Context) (res string) - GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool) - - Delegate( - ctx sdk.Context, delAddr sdk.AccAddress, bondAmt sdkmath.Int, tokenSrc stakingtypes.BondStatus, - validator stakingtypes.Validator, subtractAccount bool, - ) (newShares sdk.Dec, err error) - Undelegate( - ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, sharesAmount sdk.Dec, - ) (time.Time, error) -} - -type LiquidKeeper interface { - DerivativeFromTokens(ctx sdk.Context, valAddr sdk.ValAddress, amount sdk.Coin) (sdk.Coin, error) - MintDerivative(ctx sdk.Context, delegatorAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) (sdk.Coin, error) - BurnDerivative(ctx sdk.Context, delegatorAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) (sdk.Dec, error) -} - -type EarnKeeper interface { - Deposit(ctx sdk.Context, depositor sdk.AccAddress, amount sdk.Coin, depositStrategy earntypes.StrategyType) error - Withdraw(ctx sdk.Context, from sdk.AccAddress, wantAmount sdk.Coin, withdrawStrategy earntypes.StrategyType) (sdk.Coin, error) -} diff --git a/x/router/types/keys.go b/x/router/types/keys.go deleted file mode 100644 index dbde25a7..00000000 --- a/x/router/types/keys.go +++ /dev/null @@ -1,9 +0,0 @@ -package types - -const ( - // ModuleName name that will be used throughout the module - ModuleName = "router" - - // RouterKey top level router key - RouterKey = ModuleName -) diff --git a/x/router/types/msg.go b/x/router/types/msg.go deleted file mode 100644 index 93170853..00000000 --- a/x/router/types/msg.go +++ /dev/null @@ -1,202 +0,0 @@ -package types - -import ( - 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/auth/migrations/legacytx" -) - -const ( - // TypeMsgMintDeposit defines the type for MsgMintDeposit - TypeMsgMintDeposit = "mint_deposit" - // TypeMsgDelegateMintDeposit defines the type for MsgDelegateMintDeposit - TypeMsgDelegateMintDeposit = "delegate_mint_deposit" - // TypeMsgWithdrawBurn defines the type for MsgWithdrawBurn - TypeMsgWithdrawBurn = "withdraw_burn" - // TypeMsgWithdrawBurnUndelegate defines the type for MsgWithdrawBurnUndelegate - TypeMsgWithdrawBurnUndelegate = "withdraw_burn_undelegate" -) - -var ( - _ sdk.Msg = &MsgMintDeposit{} - _ legacytx.LegacyMsg = &MsgMintDeposit{} - _ sdk.Msg = &MsgDelegateMintDeposit{} - _ legacytx.LegacyMsg = &MsgDelegateMintDeposit{} - _ sdk.Msg = &MsgWithdrawBurn{} - _ legacytx.LegacyMsg = &MsgWithdrawBurn{} - _ sdk.Msg = &MsgWithdrawBurnUndelegate{} - _ legacytx.LegacyMsg = &MsgWithdrawBurnUndelegate{} -) - -// NewMsgMintDeposit returns a new MsgMintDeposit. -func NewMsgMintDeposit(depositor sdk.AccAddress, validator sdk.ValAddress, amount sdk.Coin) *MsgMintDeposit { - return &MsgMintDeposit{ - Depositor: depositor.String(), - Validator: validator.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgMintDeposit) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgMintDeposit) Type() string { return TypeMsgMintDeposit } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgMintDeposit) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Depositor); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid depositor address: %s", err) - } - - if _, err := sdk.ValAddressFromBech32(msg.Validator); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid validator address: %s", err) - } - - if msg.Amount.IsNil() || !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "'%s'", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgMintDeposit) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgMintDeposit) GetSigners() []sdk.AccAddress { - depositor, _ := sdk.AccAddressFromBech32(msg.Depositor) - return []sdk.AccAddress{depositor} -} - -// NewMsgDelegateMintDeposit returns a new MsgDelegateMintDeposit. -func NewMsgDelegateMintDeposit(depositor sdk.AccAddress, validator sdk.ValAddress, amount sdk.Coin) *MsgDelegateMintDeposit { - return &MsgDelegateMintDeposit{ - Depositor: depositor.String(), - Validator: validator.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgDelegateMintDeposit) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgDelegateMintDeposit) Type() string { return TypeMsgDelegateMintDeposit } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgDelegateMintDeposit) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Depositor); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid depositor address: %s", err) - } - - if _, err := sdk.ValAddressFromBech32(msg.Validator); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid validator address: %s", err) - } - - if msg.Amount.IsNil() || !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "'%s'", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgDelegateMintDeposit) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgDelegateMintDeposit) GetSigners() []sdk.AccAddress { - depositor, _ := sdk.AccAddressFromBech32(msg.Depositor) - return []sdk.AccAddress{depositor} -} - -// NewMsgWithdrawBurn returns a new MsgWithdrawBurn. -func NewMsgWithdrawBurn(from sdk.AccAddress, validator sdk.ValAddress, amount sdk.Coin) *MsgWithdrawBurn { - return &MsgWithdrawBurn{ - From: from.String(), - Validator: validator.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgWithdrawBurn) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgWithdrawBurn) Type() string { return TypeMsgWithdrawBurn } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgWithdrawBurn) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.From); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid from address: %s", err) - } - - if _, err := sdk.ValAddressFromBech32(msg.Validator); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid validator address: %s", err) - } - - if msg.Amount.IsNil() || !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "'%s'", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgWithdrawBurn) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgWithdrawBurn) GetSigners() []sdk.AccAddress { - from, _ := sdk.AccAddressFromBech32(msg.From) - return []sdk.AccAddress{from} -} - -// NewMsgWithdrawBurnUndelegate returns a new MsgWithdrawBurnUndelegate. -func NewMsgWithdrawBurnUndelegate(from sdk.AccAddress, validator sdk.ValAddress, amount sdk.Coin) *MsgWithdrawBurnUndelegate { - return &MsgWithdrawBurnUndelegate{ - From: from.String(), - Validator: validator.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgWithdrawBurnUndelegate) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgWithdrawBurnUndelegate) Type() string { return TypeMsgWithdrawBurnUndelegate } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgWithdrawBurnUndelegate) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.From); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid from address: %s", err) - } - - if _, err := sdk.ValAddressFromBech32(msg.Validator); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid validator address: %s", err) - } - - if msg.Amount.IsNil() || !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "'%s'", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgWithdrawBurnUndelegate) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgWithdrawBurnUndelegate) GetSigners() []sdk.AccAddress { - from, _ := sdk.AccAddressFromBech32(msg.From) - return []sdk.AccAddress{from} -} diff --git a/x/router/types/msg_test.go b/x/router/types/msg_test.go deleted file mode 100644 index 4108207f..00000000 --- a/x/router/types/msg_test.go +++ /dev/null @@ -1,208 +0,0 @@ -package types_test - -import ( - fmt "fmt" - "testing" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/0glabs/0g-chain/x/router/types" -) - -func TestMsgMintDeposit_Signing(t *testing.T) { - address := mustAccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - validatorAddress := mustValAddressFromBech32("kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42") - - msg := types.NewMsgMintDeposit( - address, - validatorAddress, - sdk.NewCoin("ukava", sdkmath.NewInt(1e9)), - ) - - // checking for the "type" field ensures the msg is registered on the amino codec - signBytes := []byte( - `{"type":"router/MsgMintDeposit","value":{"amount":{"amount":"1000000000","denom":"ukava"},"depositor":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","validator":"kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42"}}`, - ) - - assert.Equal(t, []sdk.AccAddress{address}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsgDelegateMintDeposit_Signing(t *testing.T) { - address := mustAccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - validatorAddress := mustValAddressFromBech32("kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42") - - msg := types.NewMsgDelegateMintDeposit( - address, - validatorAddress, - sdk.NewCoin("ukava", sdkmath.NewInt(1e9)), - ) - - // checking for the "type" field ensures the msg is registered on the amino codec - signBytes := []byte( - `{"type":"router/MsgDelegateMintDeposit","value":{"amount":{"amount":"1000000000","denom":"ukava"},"depositor":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","validator":"kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42"}}`, - ) - - assert.Equal(t, []sdk.AccAddress{address}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsgWithdrawBurn_Signing(t *testing.T) { - address := mustAccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - validatorAddress := mustValAddressFromBech32("kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42") - - msg := types.NewMsgWithdrawBurn( - address, - validatorAddress, - sdk.NewCoin("ukava", sdkmath.NewInt(1e9)), - ) - - // checking for the "type" field ensures the msg is registered on the amino codec - signBytes := []byte( - `{"type":"router/MsgWithdrawBurn","value":{"amount":{"amount":"1000000000","denom":"ukava"},"from":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","validator":"kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42"}}`, - ) - - assert.Equal(t, []sdk.AccAddress{address}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsgWithdrawBurnUndelegate_Signing(t *testing.T) { - address := mustAccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - validatorAddress := mustValAddressFromBech32("kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42") - - msg := types.NewMsgWithdrawBurnUndelegate( - address, - validatorAddress, - sdk.NewCoin("ukava", sdkmath.NewInt(1e9)), - ) - - // checking for the "type" field ensures the msg is registered on the amino codec - signBytes := []byte( - `{"type":"router/MsgWithdrawBurnUndelegate","value":{"amount":{"amount":"1000000000","denom":"ukava"},"from":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","validator":"kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42"}}`, - ) - - assert.Equal(t, []sdk.AccAddress{address}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsg_Validate(t *testing.T) { - validAddress := "kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d" - validValidatorAddress := "kavavaloper1ypjp0m04pyp73hwgtc0dgkx0e9rrydeckewa42" - validCoin := sdk.NewInt64Coin("ukava", 1e9) - - type msgArgs struct { - depositor string - validator string - amount sdk.Coin - } - tests := []struct { - name string - msgArgs msgArgs - expectedErr error - }{ - { - name: "normal multiplier is valid", - msgArgs: msgArgs{ - depositor: validAddress, - validator: validValidatorAddress, - amount: validCoin, - }, - }, - { - name: "invalid depositor", - msgArgs: msgArgs{ - depositor: "invalid", - validator: validValidatorAddress, - amount: validCoin, - }, - expectedErr: sdkerrors.ErrInvalidAddress, - }, - { - name: "empty depositor", - msgArgs: msgArgs{ - depositor: "", - validator: validValidatorAddress, - amount: validCoin, - }, - expectedErr: sdkerrors.ErrInvalidAddress, - }, - { - name: "invalid validator", - msgArgs: msgArgs{ - depositor: validAddress, - validator: "invalid", - amount: validCoin, - }, - expectedErr: sdkerrors.ErrInvalidAddress, - }, - { - name: "nil coin", - msgArgs: msgArgs{ - depositor: validAddress, - validator: validValidatorAddress, - amount: sdk.Coin{}, - }, - expectedErr: sdkerrors.ErrInvalidCoins, - }, - { - name: "zero coin", - msgArgs: msgArgs{ - depositor: validAddress, - validator: validValidatorAddress, - amount: sdk.NewCoin("ukava", sdk.ZeroInt()), - }, - expectedErr: sdkerrors.ErrInvalidCoins, - }, - { - name: "negative coin", - msgArgs: msgArgs{ - depositor: validAddress, - validator: validValidatorAddress, - amount: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(-1)}, - }, - expectedErr: sdkerrors.ErrInvalidCoins, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - msgMintDeposit := types.MsgMintDeposit{tc.msgArgs.depositor, tc.msgArgs.validator, tc.msgArgs.amount} - msgDelegateMintDeposit := types.MsgDelegateMintDeposit{tc.msgArgs.depositor, tc.msgArgs.validator, tc.msgArgs.amount} - - msgWithdrawBurn := types.MsgWithdrawBurn{tc.msgArgs.depositor, tc.msgArgs.validator, tc.msgArgs.amount} - msgWithdrawBurnUndelegate := types.MsgWithdrawBurnUndelegate{tc.msgArgs.depositor, tc.msgArgs.validator, tc.msgArgs.amount} - - msgs := []sdk.Msg{&msgMintDeposit, &msgDelegateMintDeposit, &msgWithdrawBurn, &msgWithdrawBurnUndelegate} - for _, msg := range msgs { - t.Run(fmt.Sprintf("%T", msg), func(t *testing.T) { - err := msg.ValidateBasic() - if tc.expectedErr == nil { - require.NoError(t, err) - } else { - require.ErrorIs(t, err, tc.expectedErr, "expected error '%s' not found in actual '%s'", tc.expectedErr, err) - } - }) - } - }) - } -} - -func mustAccAddressFromBech32(address string) sdk.AccAddress { - addr, err := sdk.AccAddressFromBech32(address) - if err != nil { - panic(err) - } - return addr -} - -func mustValAddressFromBech32(address string) sdk.ValAddress { - addr, err := sdk.ValAddressFromBech32(address) - if err != nil { - panic(err) - } - return addr -} diff --git a/x/router/types/tx.pb.go b/x/router/types/tx.pb.go deleted file mode 100644 index 5cc769b7..00000000 --- a/x/router/types/tx.pb.go +++ /dev/null @@ -1,1882 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/router/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// MsgMintDeposit converts a delegation into staking derivatives and deposits it all into an earn vault. -type MsgMintDeposit struct { - // depositor represents the owner of the delegation to convert - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - // validator is the validator for the depositor's delegation - Validator string `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator,omitempty"` - // amount is the delegation balance to convert - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *MsgMintDeposit) Reset() { *m = MsgMintDeposit{} } -func (m *MsgMintDeposit) String() string { return proto.CompactTextString(m) } -func (*MsgMintDeposit) ProtoMessage() {} -func (*MsgMintDeposit) Descriptor() ([]byte, []int) { - return fileDescriptor_63015631bbbf9425, []int{0} -} -func (m *MsgMintDeposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgMintDeposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMintDeposit.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgMintDeposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMintDeposit.Merge(m, src) -} -func (m *MsgMintDeposit) XXX_Size() int { - return m.Size() -} -func (m *MsgMintDeposit) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMintDeposit.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMintDeposit proto.InternalMessageInfo - -// MsgMintDepositResponse defines the Msg/MsgMintDeposit response type. -type MsgMintDepositResponse struct { -} - -func (m *MsgMintDepositResponse) Reset() { *m = MsgMintDepositResponse{} } -func (m *MsgMintDepositResponse) String() string { return proto.CompactTextString(m) } -func (*MsgMintDepositResponse) ProtoMessage() {} -func (*MsgMintDepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63015631bbbf9425, []int{1} -} -func (m *MsgMintDepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgMintDepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMintDepositResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgMintDepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMintDepositResponse.Merge(m, src) -} -func (m *MsgMintDepositResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgMintDepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMintDepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMintDepositResponse proto.InternalMessageInfo - -// MsgDelegateMintDeposit delegates tokens to a validator, then converts them into staking derivatives, -// then deposits to an earn vault. -type MsgDelegateMintDeposit struct { - // depositor represents the owner of the tokens to delegate - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - // validator is the address of the validator to delegate to - Validator string `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator,omitempty"` - // amount is the tokens to delegate - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *MsgDelegateMintDeposit) Reset() { *m = MsgDelegateMintDeposit{} } -func (m *MsgDelegateMintDeposit) String() string { return proto.CompactTextString(m) } -func (*MsgDelegateMintDeposit) ProtoMessage() {} -func (*MsgDelegateMintDeposit) Descriptor() ([]byte, []int) { - return fileDescriptor_63015631bbbf9425, []int{2} -} -func (m *MsgDelegateMintDeposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDelegateMintDeposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDelegateMintDeposit.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgDelegateMintDeposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDelegateMintDeposit.Merge(m, src) -} -func (m *MsgDelegateMintDeposit) XXX_Size() int { - return m.Size() -} -func (m *MsgDelegateMintDeposit) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDelegateMintDeposit.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDelegateMintDeposit proto.InternalMessageInfo - -// MsgDelegateMintDepositResponse defines the Msg/MsgDelegateMintDeposit response type. -type MsgDelegateMintDepositResponse struct { -} - -func (m *MsgDelegateMintDepositResponse) Reset() { *m = MsgDelegateMintDepositResponse{} } -func (m *MsgDelegateMintDepositResponse) String() string { return proto.CompactTextString(m) } -func (*MsgDelegateMintDepositResponse) ProtoMessage() {} -func (*MsgDelegateMintDepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63015631bbbf9425, []int{3} -} -func (m *MsgDelegateMintDepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDelegateMintDepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDelegateMintDepositResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgDelegateMintDepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDelegateMintDepositResponse.Merge(m, src) -} -func (m *MsgDelegateMintDepositResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgDelegateMintDepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDelegateMintDepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDelegateMintDepositResponse proto.InternalMessageInfo - -// MsgWithdrawBurn removes staking derivatives from an earn vault and converts them back to a staking delegation. -type MsgWithdrawBurn struct { - // from is the owner of the earn vault to withdraw from - From string `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"` - // validator is the address to select the derivative denom to withdraw - Validator string `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator,omitempty"` - // amount is the staked token equivalent to withdraw - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *MsgWithdrawBurn) Reset() { *m = MsgWithdrawBurn{} } -func (m *MsgWithdrawBurn) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawBurn) ProtoMessage() {} -func (*MsgWithdrawBurn) Descriptor() ([]byte, []int) { - return fileDescriptor_63015631bbbf9425, []int{4} -} -func (m *MsgWithdrawBurn) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawBurn) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawBurn.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgWithdrawBurn) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawBurn.Merge(m, src) -} -func (m *MsgWithdrawBurn) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawBurn) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawBurn.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawBurn proto.InternalMessageInfo - -// MsgWithdrawBurnResponse defines the Msg/MsgWithdrawBurn response type. -type MsgWithdrawBurnResponse struct { -} - -func (m *MsgWithdrawBurnResponse) Reset() { *m = MsgWithdrawBurnResponse{} } -func (m *MsgWithdrawBurnResponse) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawBurnResponse) ProtoMessage() {} -func (*MsgWithdrawBurnResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63015631bbbf9425, []int{5} -} -func (m *MsgWithdrawBurnResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawBurnResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawBurnResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgWithdrawBurnResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawBurnResponse.Merge(m, src) -} -func (m *MsgWithdrawBurnResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawBurnResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawBurnResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawBurnResponse proto.InternalMessageInfo - -// MsgWithdrawBurnUndelegate removes staking derivatives from an earn vault, converts them to a staking delegation, -// then undelegates them from their validator. -type MsgWithdrawBurnUndelegate struct { - // from is the owner of the earn vault to withdraw from - From string `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"` - // validator is the address to select the derivative denom to withdraw - Validator string `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator,omitempty"` - // amount is the staked token equivalent to withdraw - Amount types.Coin `protobuf:"bytes,3,opt,name=amount,proto3" json:"amount"` -} - -func (m *MsgWithdrawBurnUndelegate) Reset() { *m = MsgWithdrawBurnUndelegate{} } -func (m *MsgWithdrawBurnUndelegate) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawBurnUndelegate) ProtoMessage() {} -func (*MsgWithdrawBurnUndelegate) Descriptor() ([]byte, []int) { - return fileDescriptor_63015631bbbf9425, []int{6} -} -func (m *MsgWithdrawBurnUndelegate) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawBurnUndelegate) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawBurnUndelegate.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgWithdrawBurnUndelegate) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawBurnUndelegate.Merge(m, src) -} -func (m *MsgWithdrawBurnUndelegate) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawBurnUndelegate) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawBurnUndelegate.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawBurnUndelegate proto.InternalMessageInfo - -// MsgWithdrawBurnUndelegateResponse defines the Msg/MsgWithdrawBurnUndelegate response type. -type MsgWithdrawBurnUndelegateResponse struct { -} - -func (m *MsgWithdrawBurnUndelegateResponse) Reset() { *m = MsgWithdrawBurnUndelegateResponse{} } -func (m *MsgWithdrawBurnUndelegateResponse) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawBurnUndelegateResponse) ProtoMessage() {} -func (*MsgWithdrawBurnUndelegateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_63015631bbbf9425, []int{7} -} -func (m *MsgWithdrawBurnUndelegateResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawBurnUndelegateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawBurnUndelegateResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgWithdrawBurnUndelegateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawBurnUndelegateResponse.Merge(m, src) -} -func (m *MsgWithdrawBurnUndelegateResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawBurnUndelegateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawBurnUndelegateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawBurnUndelegateResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgMintDeposit)(nil), "kava.router.v1beta1.MsgMintDeposit") - proto.RegisterType((*MsgMintDepositResponse)(nil), "kava.router.v1beta1.MsgMintDepositResponse") - proto.RegisterType((*MsgDelegateMintDeposit)(nil), "kava.router.v1beta1.MsgDelegateMintDeposit") - proto.RegisterType((*MsgDelegateMintDepositResponse)(nil), "kava.router.v1beta1.MsgDelegateMintDepositResponse") - proto.RegisterType((*MsgWithdrawBurn)(nil), "kava.router.v1beta1.MsgWithdrawBurn") - proto.RegisterType((*MsgWithdrawBurnResponse)(nil), "kava.router.v1beta1.MsgWithdrawBurnResponse") - proto.RegisterType((*MsgWithdrawBurnUndelegate)(nil), "kava.router.v1beta1.MsgWithdrawBurnUndelegate") - proto.RegisterType((*MsgWithdrawBurnUndelegateResponse)(nil), "kava.router.v1beta1.MsgWithdrawBurnUndelegateResponse") -} - -func init() { proto.RegisterFile("kava/router/v1beta1/tx.proto", fileDescriptor_63015631bbbf9425) } - -var fileDescriptor_63015631bbbf9425 = []byte{ - // 478 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x54, 0x4d, 0x6b, 0x53, 0x41, - 0x14, 0x7d, 0x63, 0x4a, 0x21, 0xb7, 0xa2, 0xf0, 0x5a, 0x6a, 0xf2, 0x28, 0x63, 0x4c, 0x5d, 0x54, - 0x6c, 0x67, 0xfa, 0x01, 0x75, 0x6d, 0x2c, 0xb8, 0xca, 0x26, 0x22, 0x82, 0x9b, 0x32, 0x2f, 0x6f, - 0x9c, 0x0c, 0x26, 0x33, 0x61, 0x66, 0x92, 0xd6, 0x9d, 0x3f, 0xc1, 0x95, 0x5b, 0xdd, 0xf9, 0x07, - 0xfc, 0x0d, 0x92, 0x65, 0x71, 0xe5, 0x4a, 0x34, 0xf9, 0x23, 0xf2, 0xf2, 0x3e, 0xd2, 0x94, 0x3c, - 0x4c, 0x17, 0x85, 0xee, 0x66, 0xee, 0x39, 0xf7, 0xde, 0x73, 0xe0, 0xcc, 0xc0, 0xd6, 0x7b, 0x36, - 0x64, 0xd4, 0xe8, 0x81, 0xe3, 0x86, 0x0e, 0x0f, 0x42, 0xee, 0xd8, 0x01, 0x75, 0xe7, 0xa4, 0x6f, - 0xb4, 0xd3, 0xfe, 0x7a, 0x8c, 0x92, 0x04, 0x25, 0x29, 0x1a, 0xe0, 0xb6, 0xb6, 0x3d, 0x6d, 0x69, - 0xc8, 0x2c, 0xcf, 0x5b, 0xda, 0x5a, 0xaa, 0xa4, 0x29, 0xa8, 0x26, 0xf8, 0xe9, 0xf4, 0x46, 0x93, - 0x4b, 0x0a, 0x6d, 0x08, 0x2d, 0x74, 0x52, 0x8f, 0x4f, 0x49, 0xb5, 0xfe, 0x05, 0xc1, 0xbd, 0xa6, - 0x15, 0x4d, 0xa9, 0xdc, 0x09, 0xef, 0x6b, 0x2b, 0x9d, 0x7f, 0x0c, 0xe5, 0x28, 0x39, 0x6a, 0x53, - 0x41, 0x35, 0xb4, 0x53, 0x6e, 0x54, 0x7e, 0x7e, 0xdf, 0xdb, 0x48, 0xa7, 0x3d, 0x8f, 0x22, 0xc3, - 0xad, 0x7d, 0xe5, 0x8c, 0x54, 0xa2, 0x35, 0xa3, 0xfa, 0x5b, 0x50, 0x1e, 0xb2, 0xae, 0x8c, 0x58, - 0xdc, 0x77, 0x27, 0xee, 0x6b, 0xcd, 0x0a, 0xfe, 0x33, 0x58, 0x65, 0x3d, 0x3d, 0x50, 0xae, 0x52, - 0xaa, 0xa1, 0x9d, 0xb5, 0xc3, 0x2a, 0x49, 0xe7, 0xc5, 0x56, 0x32, 0x7f, 0xe4, 0x85, 0x96, 0xaa, - 0xb1, 0x32, 0xfa, 0xfd, 0xd0, 0x6b, 0xa5, 0xf4, 0x7a, 0x05, 0x36, 0xe7, 0x05, 0xb6, 0xb8, 0xed, - 0x6b, 0x65, 0x79, 0xfd, 0x1b, 0x9a, 0x42, 0x27, 0xbc, 0xcb, 0x05, 0x73, 0xfc, 0x16, 0x7b, 0xa8, - 0x01, 0x5e, 0x2c, 0x34, 0xf7, 0xf2, 0x19, 0xc1, 0xfd, 0xa6, 0x15, 0x6f, 0xa4, 0xeb, 0x44, 0x86, - 0x9d, 0x35, 0x06, 0x46, 0xf9, 0xbb, 0xb0, 0xf2, 0xce, 0xe8, 0xde, 0x7f, 0xf5, 0x4f, 0x59, 0x37, - 0x25, 0xbd, 0x0a, 0x0f, 0xae, 0xe8, 0xca, 0x35, 0x7f, 0x45, 0x50, 0xbd, 0x82, 0xbd, 0x56, 0x51, - 0x6a, 0xf2, 0x76, 0xa8, 0xdf, 0x86, 0x47, 0x85, 0x0a, 0x33, 0x1f, 0x87, 0x3f, 0x4a, 0x50, 0x6a, - 0x5a, 0xe1, 0x9f, 0xc2, 0xda, 0xe5, 0x0c, 0x6d, 0x93, 0x05, 0x2f, 0x90, 0xcc, 0x67, 0x31, 0x78, - 0xba, 0x04, 0x29, 0x5b, 0xe4, 0x9f, 0xc1, 0xfa, 0xa2, 0xb0, 0x16, 0xce, 0x58, 0x40, 0x0e, 0x8e, - 0xae, 0x41, 0xce, 0x17, 0x87, 0x70, 0x77, 0x2e, 0x59, 0x8f, 0x8b, 0x86, 0x5c, 0x66, 0x05, 0xbb, - 0xcb, 0xb0, 0xf2, 0x1d, 0x1f, 0x11, 0x6c, 0x16, 0x44, 0x81, 0x2c, 0x33, 0x68, 0xc6, 0x0f, 0x8e, - 0xaf, 0xc7, 0xcf, 0x24, 0x34, 0x5e, 0x8e, 0xfe, 0x62, 0x6f, 0x34, 0xc6, 0xe8, 0x62, 0x8c, 0xd1, - 0x9f, 0x31, 0x46, 0x9f, 0x26, 0xd8, 0xbb, 0x98, 0x60, 0xef, 0xd7, 0x04, 0x7b, 0x6f, 0x9f, 0x08, - 0xe9, 0x3a, 0x83, 0x90, 0xb4, 0x75, 0x8f, 0xee, 0x8b, 0x2e, 0x0b, 0x2d, 0xdd, 0x17, 0x7b, 0xed, - 0x0e, 0x93, 0x8a, 0x9e, 0x67, 0xdf, 0xb0, 0xfb, 0xd0, 0xe7, 0x36, 0x5c, 0x9d, 0x7e, 0x8e, 0x47, - 0xff, 0x02, 0x00, 0x00, 0xff, 0xff, 0xc1, 0x38, 0x34, 0x6e, 0xa2, 0x05, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - // MintDeposit converts a delegation into staking derivatives and deposits it all into an earn vault. - MintDeposit(ctx context.Context, in *MsgMintDeposit, opts ...grpc.CallOption) (*MsgMintDepositResponse, error) - // DelegateMintDeposit delegates tokens to a validator, then converts them into staking derivatives, - // then deposits to an earn vault. - DelegateMintDeposit(ctx context.Context, in *MsgDelegateMintDeposit, opts ...grpc.CallOption) (*MsgDelegateMintDepositResponse, error) - // WithdrawBurn removes staking derivatives from an earn vault and converts them back to a staking delegation. - WithdrawBurn(ctx context.Context, in *MsgWithdrawBurn, opts ...grpc.CallOption) (*MsgWithdrawBurnResponse, error) - // WithdrawBurnUndelegate removes staking derivatives from an earn vault, converts them to a staking delegation, - // then undelegates them from their validator. - WithdrawBurnUndelegate(ctx context.Context, in *MsgWithdrawBurnUndelegate, opts ...grpc.CallOption) (*MsgWithdrawBurnUndelegateResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) MintDeposit(ctx context.Context, in *MsgMintDeposit, opts ...grpc.CallOption) (*MsgMintDepositResponse, error) { - out := new(MsgMintDepositResponse) - err := c.cc.Invoke(ctx, "/kava.router.v1beta1.Msg/MintDeposit", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) DelegateMintDeposit(ctx context.Context, in *MsgDelegateMintDeposit, opts ...grpc.CallOption) (*MsgDelegateMintDepositResponse, error) { - out := new(MsgDelegateMintDepositResponse) - err := c.cc.Invoke(ctx, "/kava.router.v1beta1.Msg/DelegateMintDeposit", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) WithdrawBurn(ctx context.Context, in *MsgWithdrawBurn, opts ...grpc.CallOption) (*MsgWithdrawBurnResponse, error) { - out := new(MsgWithdrawBurnResponse) - err := c.cc.Invoke(ctx, "/kava.router.v1beta1.Msg/WithdrawBurn", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) WithdrawBurnUndelegate(ctx context.Context, in *MsgWithdrawBurnUndelegate, opts ...grpc.CallOption) (*MsgWithdrawBurnUndelegateResponse, error) { - out := new(MsgWithdrawBurnUndelegateResponse) - err := c.cc.Invoke(ctx, "/kava.router.v1beta1.Msg/WithdrawBurnUndelegate", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // MintDeposit converts a delegation into staking derivatives and deposits it all into an earn vault. - MintDeposit(context.Context, *MsgMintDeposit) (*MsgMintDepositResponse, error) - // DelegateMintDeposit delegates tokens to a validator, then converts them into staking derivatives, - // then deposits to an earn vault. - DelegateMintDeposit(context.Context, *MsgDelegateMintDeposit) (*MsgDelegateMintDepositResponse, error) - // WithdrawBurn removes staking derivatives from an earn vault and converts them back to a staking delegation. - WithdrawBurn(context.Context, *MsgWithdrawBurn) (*MsgWithdrawBurnResponse, error) - // WithdrawBurnUndelegate removes staking derivatives from an earn vault, converts them to a staking delegation, - // then undelegates them from their validator. - WithdrawBurnUndelegate(context.Context, *MsgWithdrawBurnUndelegate) (*MsgWithdrawBurnUndelegateResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) MintDeposit(ctx context.Context, req *MsgMintDeposit) (*MsgMintDepositResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method MintDeposit not implemented") -} -func (*UnimplementedMsgServer) DelegateMintDeposit(ctx context.Context, req *MsgDelegateMintDeposit) (*MsgDelegateMintDepositResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method DelegateMintDeposit not implemented") -} -func (*UnimplementedMsgServer) WithdrawBurn(ctx context.Context, req *MsgWithdrawBurn) (*MsgWithdrawBurnResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method WithdrawBurn not implemented") -} -func (*UnimplementedMsgServer) WithdrawBurnUndelegate(ctx context.Context, req *MsgWithdrawBurnUndelegate) (*MsgWithdrawBurnUndelegateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method WithdrawBurnUndelegate not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_MintDeposit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgMintDeposit) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).MintDeposit(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.router.v1beta1.Msg/MintDeposit", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).MintDeposit(ctx, req.(*MsgMintDeposit)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_DelegateMintDeposit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgDelegateMintDeposit) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).DelegateMintDeposit(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.router.v1beta1.Msg/DelegateMintDeposit", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).DelegateMintDeposit(ctx, req.(*MsgDelegateMintDeposit)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_WithdrawBurn_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgWithdrawBurn) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).WithdrawBurn(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.router.v1beta1.Msg/WithdrawBurn", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).WithdrawBurn(ctx, req.(*MsgWithdrawBurn)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_WithdrawBurnUndelegate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgWithdrawBurnUndelegate) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).WithdrawBurnUndelegate(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.router.v1beta1.Msg/WithdrawBurnUndelegate", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).WithdrawBurnUndelegate(ctx, req.(*MsgWithdrawBurnUndelegate)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.router.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "MintDeposit", - Handler: _Msg_MintDeposit_Handler, - }, - { - MethodName: "DelegateMintDeposit", - Handler: _Msg_DelegateMintDeposit_Handler, - }, - { - MethodName: "WithdrawBurn", - Handler: _Msg_WithdrawBurn_Handler, - }, - { - MethodName: "WithdrawBurnUndelegate", - Handler: _Msg_WithdrawBurnUndelegate_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/router/v1beta1/tx.proto", -} - -func (m *MsgMintDeposit) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgMintDeposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMintDeposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Validator) > 0 { - i -= len(m.Validator) - copy(dAtA[i:], m.Validator) - i = encodeVarintTx(dAtA, i, uint64(len(m.Validator))) - i-- - dAtA[i] = 0x12 - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgMintDepositResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgMintDepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMintDepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgDelegateMintDeposit) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgDelegateMintDeposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDelegateMintDeposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Validator) > 0 { - i -= len(m.Validator) - copy(dAtA[i:], m.Validator) - i = encodeVarintTx(dAtA, i, uint64(len(m.Validator))) - i-- - dAtA[i] = 0x12 - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgDelegateMintDepositResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgDelegateMintDepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDelegateMintDepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawBurn) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgWithdrawBurn) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawBurn) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Validator) > 0 { - i -= len(m.Validator) - copy(dAtA[i:], m.Validator) - i = encodeVarintTx(dAtA, i, uint64(len(m.Validator))) - i-- - dAtA[i] = 0x12 - } - if len(m.From) > 0 { - i -= len(m.From) - copy(dAtA[i:], m.From) - i = encodeVarintTx(dAtA, i, uint64(len(m.From))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawBurnResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgWithdrawBurnResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawBurnResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawBurnUndelegate) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgWithdrawBurnUndelegate) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawBurnUndelegate) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Validator) > 0 { - i -= len(m.Validator) - copy(dAtA[i:], m.Validator) - i = encodeVarintTx(dAtA, i, uint64(len(m.Validator))) - i-- - dAtA[i] = 0x12 - } - if len(m.From) > 0 { - i -= len(m.From) - copy(dAtA[i:], m.From) - i = encodeVarintTx(dAtA, i, uint64(len(m.From))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawBurnUndelegateResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgWithdrawBurnUndelegateResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawBurnUndelegateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgMintDeposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Validator) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgMintDepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgDelegateMintDeposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Validator) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgDelegateMintDepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgWithdrawBurn) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.From) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Validator) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgWithdrawBurnResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgWithdrawBurnUndelegate) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.From) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Validator) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgWithdrawBurnUndelegateResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgMintDeposit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgMintDeposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgMintDeposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Validator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgMintDepositResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgMintDepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgMintDepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDelegateMintDeposit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDelegateMintDeposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDelegateMintDeposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Validator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDelegateMintDepositResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDelegateMintDepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDelegateMintDepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawBurn) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawBurn: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawBurn: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.From = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Validator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawBurnResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawBurnResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawBurnResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawBurnUndelegate) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawBurnUndelegate: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawBurnUndelegate: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.From = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Validator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Validator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawBurnUndelegateResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawBurnUndelegateResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawBurnUndelegateResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/savings/client/cli/query.go b/x/savings/client/cli/query.go deleted file mode 100644 index 2044602c..00000000 --- a/x/savings/client/cli/query.go +++ /dev/null @@ -1,158 +0,0 @@ -package cli - -import ( - "context" - "fmt" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/0glabs/0g-chain/x/savings/types" -) - -// flags for cli queries -const ( - flagDenom = "denom" - flagOwner = "owner" -) - -// GetQueryCmd returns the cli query commands for this module -func GetQueryCmd() *cobra.Command { - savingsQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the savings module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - GetCmdQueryParams(), - queryDepositsCmd(), - GetCmdTotalSupply(), - } - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - savingsQueryCmd.AddCommand(cmds...) - - return savingsQueryCmd -} - -// GetCmdQueryParams queries the savings module parameters -func GetCmdQueryParams() *cobra.Command { - return &cobra.Command{ - Use: "params", - Short: "get the savings module parameters", - Long: "Get the current global savings module parameters.", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.Params(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - } -} - -func queryDepositsCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "deposits", - Short: "query savings module deposits with optional filters", - Long: "query for all savings module deposits or a specific deposit using flags", - Example: fmt.Sprintf(`%[1]s q %[2]s deposits -%[1]s q %[2]s deposits --owner kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny --denom bnb -%[1]s q %[2]s deposits --denom ukava -%[1]s q %[2]s deposits --denom btcb`, version.AppName, types.ModuleName), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - ownerBech, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - denom, err := cmd.Flags().GetString(flagDenom) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - req := &types.QueryDepositsRequest{ - Denom: denom, - Pagination: pageReq, - } - - if len(ownerBech) != 0 { - depositOwner, err := sdk.AccAddressFromBech32(ownerBech) - if err != nil { - return err - } - req.Owner = depositOwner.String() - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.Deposits(context.Background(), req) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddPaginationFlagsToCmd(cmd, "deposits") - - cmd.Flags().String(flagOwner, "", "(optional) filter for deposits by owner address") - cmd.Flags().String(flagDenom, "", "(optional) filter for deposits by denom") - - return cmd -} - -// GetCmdTotalSupply returns the command that queries total supply locked into savings module -func GetCmdTotalSupply() *cobra.Command { - return &cobra.Command{ - Use: "total-supply", - Short: "get total supply locked into savings module", - Long: "Get the sum of all denoms locked into the savings module.", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.TotalSupply(context.Background(), &types.QueryTotalSupplyRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } -} diff --git a/x/savings/client/cli/tx.go b/x/savings/client/cli/tx.go deleted file mode 100644 index 13a94524..00000000 --- a/x/savings/client/cli/tx.go +++ /dev/null @@ -1,91 +0,0 @@ -package cli - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/0glabs/0g-chain/x/savings/types" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - savingsTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "savings transactions subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - getCmdDeposit(), - getCmdWithdraw(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - savingsTxCmd.AddCommand(cmds...) - - return savingsTxCmd -} - -func getCmdDeposit() *cobra.Command { - return &cobra.Command{ - Use: "deposit [amount]", - Short: "deposit coins to savings", - Example: fmt.Sprintf( - `%s tx %s deposit 10000000ukava,100000000usdx --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - amount, err := sdk.ParseCoinsNormalized(args[0]) - if err != nil { - return err - } - msg := types.NewMsgDeposit(clientCtx.GetFromAddress(), amount) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} - -func getCmdWithdraw() *cobra.Command { - return &cobra.Command{ - Use: "withdraw [amount]", - Short: "withdraw coins from savings", - Example: fmt.Sprintf( - `%s tx %s withdraw 10000000ukava,100000000usdx --from `, version.AppName, types.ModuleName, - ), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - amount, err := sdk.ParseCoinsNormalized(args[0]) - if err != nil { - return err - } - msg := types.NewMsgWithdraw(clientCtx.GetFromAddress(), amount) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - } -} diff --git a/x/savings/genesis.go b/x/savings/genesis.go deleted file mode 100644 index e40cc493..00000000 --- a/x/savings/genesis.go +++ /dev/null @@ -1,36 +0,0 @@ -package savings - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/savings/keeper" - "github.com/0glabs/0g-chain/x/savings/types" -) - -// InitGenesis initializes genesis state -func InitGenesis(ctx sdk.Context, k keeper.Keeper, ak types.AccountKeeper, gs types.GenesisState) { - if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) - } - - k.SetParams(ctx, gs.Params) - - for _, deposit := range gs.Deposits { - k.SetDeposit(ctx, deposit) - } - - // check if the module account exists - SavingsModuleAccount := ak.GetModuleAccount(ctx, types.ModuleAccountName) - if SavingsModuleAccount == nil { - panic(fmt.Sprintf("%s module account has not been set", SavingsModuleAccount)) - } -} - -// ExportGenesis returns a GenesisState for a given context and keeper -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { - params := k.GetParams(ctx) - deposits := k.GetAllDeposits(ctx) - return types.NewGenesisState(params, deposits) -} diff --git a/x/savings/genesis_test.go b/x/savings/genesis_test.go deleted file mode 100644 index 312420c7..00000000 --- a/x/savings/genesis_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package savings_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/savings" - "github.com/0glabs/0g-chain/x/savings/keeper" - "github.com/0glabs/0g-chain/x/savings/types" -) - -type GenesisTestSuite struct { - suite.Suite - - app app.TestApp - genTime time.Time - ctx sdk.Context - keeper keeper.Keeper - addrs []sdk.AccAddress -} - -func (suite *GenesisTestSuite) SetupTest() { - tApp := app.NewTestApp() - suite.genTime = tmtime.Canonical(time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC)) - suite.ctx = tApp.NewContext(true, tmproto.Header{Height: 1, Time: suite.genTime}) - suite.keeper = tApp.GetSavingsKeeper() - suite.app = tApp - - _, addrs := app.GeneratePrivKeyAddressPairs(3) - suite.addrs = addrs -} - -func (suite *GenesisTestSuite) TestInitExportGenesis() { - params := types.NewParams( - []string{"btc", "ukava", "bnb"}, - ) - - depositAmt := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e8))) - - deposits := types.Deposits{ - types.NewDeposit( - suite.addrs[0], - depositAmt, // 100 ukava - ), - } - savingsGenesis := types.NewGenesisState(params, deposits) - - authBuilder := app.NewAuthBankGenesisBuilder(). - WithSimpleModuleAccount(types.ModuleAccountName, depositAmt) - - cdc := suite.app.AppCodec() - suite.NotPanics( - func() { - suite.app.InitializeFromGenesisStatesWithTime( - suite.genTime, - authBuilder.BuildMarshalled(cdc), - app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(&savingsGenesis)}, - ) - }, - ) - - expectedDeposits := suite.keeper.GetAllDeposits(suite.ctx) - expectedGenesis := savingsGenesis - expectedGenesis.Deposits = expectedDeposits - exportedGenesis := savings.ExportGenesis(suite.ctx, suite.keeper) - suite.Equal(expectedGenesis, exportedGenesis) -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(GenesisTestSuite)) -} diff --git a/x/savings/keeper/deposit.go b/x/savings/keeper/deposit.go deleted file mode 100644 index c8eb4758..00000000 --- a/x/savings/keeper/deposit.go +++ /dev/null @@ -1,89 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/savings/types" -) - -// Deposit deposit -func (k Keeper) Deposit(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error { - err := k.ValidateDeposit(ctx, coins) - if err != nil { - return err - } - - err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, depositor, types.ModuleAccountName, coins) - if err != nil { - return err - } - - currDeposit, foundDeposit := k.GetDeposit(ctx, depositor) - - deposit := types.NewDeposit(depositor, coins) - if foundDeposit { - deposit.Amount = deposit.Amount.Add(currDeposit.Amount...) - k.BeforeSavingsDepositModified(ctx, deposit, setDifference(getDenoms(coins), getDenoms(deposit.Amount))) - - } - - k.SetDeposit(ctx, deposit) - - if !foundDeposit { - k.AfterSavingsDepositCreated(ctx, deposit) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeSavingsDeposit, - sdk.NewAttribute(sdk.AttributeKeyAmount, coins.String()), - sdk.NewAttribute(types.AttributeKeyDepositor, deposit.Depositor.String()), - ), - ) - - return nil -} - -// ValidateDeposit validates a deposit -func (k Keeper) ValidateDeposit(ctx sdk.Context, coins sdk.Coins) error { - for _, coin := range coins { - supported := k.IsDenomSupported(ctx, coin.Denom) - if !supported { - return errorsmod.Wrapf(types.ErrInvalidDepositDenom, ": %s", coin.Denom) - } - } - - return nil -} - -// GetTotalDeposited returns the total amount deposited for the deposit denom -func (k Keeper) GetTotalDeposited(ctx sdk.Context, depositDenom string) (total sdkmath.Int) { - macc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) - return k.bankKeeper.GetBalance(ctx, macc.GetAddress(), depositDenom).Amount -} - -// Set setDifference: A - B -func setDifference(a, b []string) (diff []string) { - m := make(map[string]bool) - - for _, item := range b { - m[item] = true - } - - for _, item := range a { - if _, ok := m[item]; !ok { - diff = append(diff, item) - } - } - return -} - -func getDenoms(coins sdk.Coins) []string { - denoms := []string{} - for _, coin := range coins { - denoms = append(denoms, coin.Denom) - } - return denoms -} diff --git a/x/savings/keeper/deposit_test.go b/x/savings/keeper/deposit_test.go deleted file mode 100644 index 64b76232..00000000 --- a/x/savings/keeper/deposit_test.go +++ /dev/null @@ -1,214 +0,0 @@ -package keeper_test - -import ( - "fmt" - "strings" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/savings/types" -) - -func (suite *KeeperTestSuite) TestDeposit() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, delegator := addrs[0], addrs[1] - - valAddr := sdk.ValAddress(valAccAddr) - initialBalance := sdkmath.NewInt(1e9) - - bkavaDenom := fmt.Sprintf("bkava-%s", valAddr.String()) - invalidBkavaDenom := fmt.Sprintf("bkava-%s", sdk.ValAddress(addrs[2]).String()) - - type args struct { - allowedDenoms []string - depositor sdk.AccAddress - initialDepositorBalance sdk.Coins - depositAmount sdk.Coins - numberDeposits int - expectedAccountBalance sdk.Coins - expectedModAccountBalance sdk.Coins - expectedDepositCoins sdk.Coins - } - type errArgs struct { - expectPass bool - contains string - } - type depositTest struct { - name string - args args - errArgs errArgs - } - testCases := []depositTest{ - { - "valid", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava"}, - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - numberDeposits: 1, - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(900)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - expectedDepositCoins: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid multi deposit", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava"}, - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - numberDeposits: 2, - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(800)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - expectedDepositCoins: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "valid bkava", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava", "bkava"}, - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(100))), - numberDeposits: 1, - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(900)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(100))), - expectedDepositCoins: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(100))), - }, - errArgs{ - expectPass: true, - contains: "", - }, - }, - { - "invalid deposit denom", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava"}, - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin("fake", sdkmath.NewInt(100))), - numberDeposits: 1, - expectedAccountBalance: sdk.Coins{}, - expectedModAccountBalance: sdk.Coins{}, - expectedDepositCoins: sdk.Coins{}, - }, - errArgs{ - expectPass: false, - contains: "invalid deposit denom", - }, - }, - { - "invalid bkava", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava", "bkava"}, - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin(invalidBkavaDenom, sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin(invalidBkavaDenom, sdkmath.NewInt(100))), - numberDeposits: 1, - expectedAccountBalance: sdk.Coins{}, - expectedModAccountBalance: sdk.Coins{}, - expectedDepositCoins: sdk.Coins{}, - }, - errArgs{ - expectPass: false, - contains: "invalid deposit denom", - }, - }, - { - "insufficient funds", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava"}, - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(10000))), - numberDeposits: 1, - expectedAccountBalance: sdk.Coins{}, - expectedModAccountBalance: sdk.Coins{}, - expectedDepositCoins: sdk.Coins{}, - }, - errArgs{ - expectPass: false, - contains: "insufficient funds", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - // create new app with one funded account - - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{tc.args.initialDepositorBalance}, - []sdk.AccAddress{tc.args.depositor}, - ) - savingsGS := types.NewGenesisState( - types.NewParams(tc.args.allowedDenoms), - types.Deposits{}, - ) - - stakingParams := stakingtypes.DefaultParams() - stakingParams.BondDenom = "ukava" - - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&savingsGS)}, - app.GenesisState{stakingtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(stakingtypes.NewGenesisState(stakingParams, nil, nil))}, - ) - keeper := tApp.GetSavingsKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - - // Create validator and delegate for bkava - suite.CreateAccountWithAddress(valAccAddr, cs(c("ukava", 100e10))) - suite.CreateAccountWithAddress(delegator, cs(c("ukava", 100e10))) - - suite.CreateNewUnbondedValidator(valAddr, initialBalance) - suite.CreateDelegation(valAddr, delegator, initialBalance) - staking.EndBlocker(suite.ctx, suite.app.GetStakingKeeper()) - - // run the test - var err error - for i := 0; i < tc.args.numberDeposits; i++ { - err = suite.keeper.Deposit(suite.ctx, tc.args.depositor, tc.args.depositAmount) - } - - // verify results - if tc.errArgs.expectPass { - suite.Require().NoError(err) - acc := suite.getAccount(tc.args.depositor) - suite.Require().Equal(tc.args.expectedAccountBalance, suite.getAccountCoins(acc)) - mAcc := suite.getModuleAccount(types.ModuleAccountName) - suite.Require().Equal(tc.args.expectedModAccountBalance, suite.getAccountCoins(mAcc)) - dep, f := suite.keeper.GetDeposit(suite.ctx, tc.args.depositor) - suite.Require().True(f) - suite.Require().Equal(tc.args.expectedDepositCoins, dep.Amount) - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} - -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } diff --git a/x/savings/keeper/diff_test.go b/x/savings/keeper/diff_test.go deleted file mode 100644 index a032a06c..00000000 --- a/x/savings/keeper/diff_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestSetDiff(t *testing.T) { - tests := []struct { - name string - setA []string - setB []string - expected []string - }{ - {"empty", []string{}, []string{}, []string(nil)}, - {"diff equal sets", []string{"busd", "usdx"}, []string{"busd", "usdx"}, []string(nil)}, - {"diff set empty", []string{"bnb", "ukava", "usdx"}, []string{}, []string{"bnb", "ukava", "usdx"}}, - {"input set empty", []string{}, []string{"bnb", "ukava", "usdx"}, []string(nil)}, - {"diff set with common elements", []string{"bnb", "btcb", "usdx", "xrpb"}, []string{"bnb", "usdx"}, []string{"btcb", "xrpb"}}, - {"diff set with all common elements", []string{"bnb", "usdx"}, []string{"bnb", "btcb", "usdx", "xrpb"}, []string(nil)}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - require.Equal(t, tt.expected, setDifference(tt.setA, tt.setB)) - }) - } -} diff --git a/x/savings/keeper/grpc_query.go b/x/savings/keeper/grpc_query.go deleted file mode 100644 index 189b0361..00000000 --- a/x/savings/keeper/grpc_query.go +++ /dev/null @@ -1,142 +0,0 @@ -package keeper - -import ( - "context" - "strings" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/client" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/types/query" - - "github.com/0glabs/0g-chain/x/savings/types" -) - -type queryServer struct { - keeper Keeper -} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(k Keeper) types.QueryServer { - return &queryServer{keeper: k} -} - -var _ types.QueryServer = queryServer{} - -// Params implements the gRPC service handler for querying x/savings parameters. -func (s queryServer) Params(c context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(c) - params := s.keeper.GetParams(sdkCtx) - - return &types.QueryParamsResponse{Params: params}, nil -} - -func (s queryServer) Deposits(ctx context.Context, req *types.QueryDepositsRequest) (*types.QueryDepositsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - hasDenom := len(req.Denom) > 0 - hasOwner := len(req.Owner) > 0 - - var owner sdk.AccAddress - var err error - if hasOwner { - owner, err = sdk.AccAddressFromBech32(req.Owner) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - } - - var deposits types.Deposits - switch { - case hasOwner && hasDenom: - deposit, found := s.keeper.GetDeposit(sdkCtx, owner) - if found { - for _, coin := range deposit.Amount { - if coin.Denom == req.Denom { - deposits = append(deposits, deposit) - } - } - } - case hasOwner: - deposit, found := s.keeper.GetDeposit(sdkCtx, owner) - if found { - deposits = append(deposits, deposit) - } - case hasDenom: - s.keeper.IterateDeposits(sdkCtx, func(deposit types.Deposit) (stop bool) { - if deposit.Amount.AmountOf(req.Denom).IsPositive() { - deposits = append(deposits, deposit) - } - return false - }) - default: - s.keeper.IterateDeposits(sdkCtx, func(deposit types.Deposit) (stop bool) { - deposits = append(deposits, deposit) - return false - }) - } - - page, limit, err := query.ParsePagination(req.Pagination) - if err != nil { - return nil, err - } - - start, end := client.Paginate(len(deposits), page, limit, 100) - if start < 0 || end < 0 { - deposits = types.Deposits{} - } else { - deposits = deposits[start:end] - } - - return &types.QueryDepositsResponse{ - Deposits: deposits, - Pagination: nil, - }, nil -} - -func (s queryServer) TotalSupply(ctx context.Context, req *types.QueryTotalSupplyRequest) (*types.QueryTotalSupplyResponse, error) { - sdkCtx := sdk.UnwrapSDKContext(ctx) - totalSupply := sdk.NewCoins() - liquidStakedDerivatives := sdk.NewCoins() - - s.keeper.IterateDeposits(sdkCtx, func(deposit types.Deposit) (stop bool) { - for _, c := range deposit.Amount { - // separate out bkava denoms - if strings.HasPrefix(c.Denom, bkavaPrefix) { - liquidStakedDerivatives = liquidStakedDerivatives.Add(c) - } else { - totalSupply = totalSupply.Add(c) - } - } - return false - }) - - // determine underlying value of bkava denoms - if len(liquidStakedDerivatives) > 0 { - underlyingValue, err := s.keeper.liquidKeeper.GetStakedTokensForDerivatives( - sdkCtx, - liquidStakedDerivatives, - ) - if err != nil { - return nil, err - } - totalSupply = totalSupply.Add(sdk.NewCoin(bkavaDenom, underlyingValue.Amount)) - } - - return &types.QueryTotalSupplyResponse{ - Height: sdkCtx.BlockHeight(), - Result: totalSupply, - }, nil -} diff --git a/x/savings/keeper/grpcquery_test.go b/x/savings/keeper/grpcquery_test.go deleted file mode 100644 index b6087e1a..00000000 --- a/x/savings/keeper/grpcquery_test.go +++ /dev/null @@ -1,354 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - tmprototypes "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/app" - liquidtypes "github.com/0glabs/0g-chain/x/liquid/types" - "github.com/0glabs/0g-chain/x/savings/keeper" - "github.com/0glabs/0g-chain/x/savings/types" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" -) - -var dep = types.NewDeposit - -const ( - bkava1 = "bkava-kavavaloper15gqc744d05xacn4n6w2furuads9fu4pqn6zxlu" - bkava2 = "bkava-kavavaloper15qdefkmwswysgg4qxgqpqr35k3m49pkx8yhpte" -) - -type grpcQueryTestSuite struct { - suite.Suite - - tApp app.TestApp - ctx sdk.Context - keeper keeper.Keeper - queryServer types.QueryServer - addrs []sdk.AccAddress -} - -func (suite *grpcQueryTestSuite) SetupTest() { - suite.tApp = app.NewTestApp() - _, addrs := app.GeneratePrivKeyAddressPairs(2) - - suite.addrs = addrs - - suite.ctx = suite.tApp.NewContext(true, tmprototypes.Header{}). - WithBlockTime(time.Now().UTC()) - suite.keeper = suite.tApp.GetSavingsKeeper() - suite.queryServer = keeper.NewQueryServerImpl(suite.keeper) - - err := suite.tApp.FundModuleAccount( - suite.ctx, - types.ModuleAccountName, - cs( - c("usdx", 10000000000), - c("busd", 10000000000), - ), - ) - suite.Require().NoError(err) - - savingsGenesis := types.GenesisState{ - Params: types.NewParams([]string{"bnb", "busd", bkava1, bkava2}), - } - savingsGenState := app.GenesisState{types.ModuleName: suite.tApp.AppCodec().MustMarshalJSON(&savingsGenesis)} - - suite.tApp.InitializeFromGenesisStates( - savingsGenState, - app.NewFundedGenStateWithSameCoins( - suite.tApp.AppCodec(), - cs( - c("bnb", 10000000000), - c("busd", 20000000000), - ), - addrs, - ), - ) -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryParams() { - res, err := suite.queryServer.Params(sdk.WrapSDKContext(suite.ctx), &types.QueryParamsRequest{}) - suite.Require().NoError(err) - - var expected types.GenesisState - savingsGenesis := types.GenesisState{ - Params: types.NewParams([]string{"bnb", "busd", bkava1, bkava2}), - } - savingsGenState := app.GenesisState{types.ModuleName: suite.tApp.AppCodec().MustMarshalJSON(&savingsGenesis)} - suite.tApp.AppCodec().MustUnmarshalJSON(savingsGenState[types.ModuleName], &expected) - - suite.Equal(expected.Params, res.Params, "params should equal test genesis state") -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryDeposits() { - suite.addDeposits([]types.Deposit{ - dep(suite.addrs[0], cs(c("bnb", 100000000))), - dep(suite.addrs[1], cs(c("bnb", 20000000))), - dep(suite.addrs[0], cs(c("busd", 20000000))), - dep(suite.addrs[0], cs(c("busd", 8000000))), - }) - - tests := []struct { - giveName string - giveRequest *types.QueryDepositsRequest - wantDepositCounts int - shouldError bool - errorSubstr string - }{ - { - "empty query", - &types.QueryDepositsRequest{}, - 2, - false, - "", - }, - { - "owner", - &types.QueryDepositsRequest{ - Owner: suite.addrs[0].String(), - }, - // Excludes the second address - 1, - false, - "", - }, - { - "invalid owner", - &types.QueryDepositsRequest{ - Owner: "invalid address", - }, - // No deposits - 0, - true, - "decoding bech32 failed", - }, - { - "owner and denom", - &types.QueryDepositsRequest{ - Owner: suite.addrs[0].String(), - Denom: "bnb", - }, - // Only the first one - 1, - false, - "", - }, - { - "owner and invalid denom empty response", - &types.QueryDepositsRequest{ - Owner: suite.addrs[0].String(), - Denom: "invalid denom", - }, - 0, - false, - "", - }, - { - "denom", - &types.QueryDepositsRequest{ - Denom: "bnb", - }, - 2, - false, - "", - }, - } - - for _, tt := range tests { - suite.Run(tt.giveName, func() { - res, err := suite.queryServer.Deposits(sdk.WrapSDKContext(suite.ctx), tt.giveRequest) - - if tt.shouldError { - suite.Error(err) - suite.Contains(err.Error(), tt.errorSubstr) - } else { - suite.NoError(err) - suite.Equal(tt.wantDepositCounts, len(res.Deposits)) - } - }) - } -} - -func (suite *grpcQueryTestSuite) TestGrpcQueryTotalSupply() { - testCases := []struct { - name string - deposits types.Deposits - expectedSupply sdk.Coins - }{ - { - name: "returns zeros when there's no supply", - deposits: []types.Deposit{}, - expectedSupply: sdk.NewCoins(), - }, - { - name: "returns supply of one denom deposited from multiple accounts", - deposits: []types.Deposit{ - dep(suite.addrs[0], sdk.NewCoins(c("busd", 1e6))), - dep(suite.addrs[1], sdk.NewCoins(c("busd", 1e6))), - }, - expectedSupply: sdk.NewCoins(c("busd", 2e6)), - }, - { - name: "returns supply of multiple denoms deposited from single account", - deposits: []types.Deposit{ - dep(suite.addrs[0], sdk.NewCoins(c("busd", 1e6), c("bnb", 1e6))), - }, - expectedSupply: sdk.NewCoins(c("busd", 1e6), c("bnb", 1e6)), - }, - { - name: "returns supply of multiple denoms deposited from multiple accounts", - deposits: []types.Deposit{ - dep(suite.addrs[0], sdk.NewCoins(c("busd", 1e6), c("bnb", 1e6))), - dep(suite.addrs[1], sdk.NewCoins(c("busd", 1e6), c("bnb", 1e6))), - }, - expectedSupply: sdk.NewCoins(c("busd", 2e6), c("bnb", 2e6)), - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - // setup deposits - suite.addDeposits(tc.deposits) - - res, err := suite.queryServer.TotalSupply( - sdk.WrapSDKContext(suite.ctx), - &types.QueryTotalSupplyRequest{}, - ) - suite.Require().NoError(err) - suite.Require().Equal(tc.expectedSupply, res.Result) - }) - } - - suite.Run("aggregates bkava denoms, accounting for slashing", func() { - suite.SetupTest() - - address1, derivatives1, _ := suite.createAccountWithDerivatives(bkava1, sdkmath.NewInt(1e9)) - address2, derivatives2, _ := suite.createAccountWithDerivatives(bkava2, sdkmath.NewInt(1e9)) - - // bond validators - staking.EndBlocker(suite.ctx, suite.tApp.GetStakingKeeper()) - // slash val2 - its shares are now 80% as valuable! - err := suite.slashValidator(sdk.ValAddress(address2), sdk.MustNewDecFromStr("0.2")) - suite.Require().NoError(err) - - suite.addDeposits( - types.Deposits{ - dep(address1, cs(derivatives1)), - dep(address2, cs(derivatives2)), - }, - ) - - expectedSupply := sdk.NewCoins( - sdk.NewCoin( - "bkava", - sdkmath.NewIntFromUint64(1e9). // derivative 1 - Add(sdkmath.NewInt(1e9).MulRaw(80).QuoRaw(100))), // derivative 2: original value * 80% - ) - - res, err := suite.queryServer.TotalSupply( - sdk.WrapSDKContext(suite.ctx), - &types.QueryTotalSupplyRequest{}, - ) - suite.Require().NoError(err) - suite.Require().Equal(expectedSupply, res.Result) - }) -} - -func (suite *grpcQueryTestSuite) addDeposits(deposits types.Deposits) { - for _, dep := range deposits { - suite.NotPanics(func() { - err := suite.keeper.Deposit(suite.ctx, dep.Depositor, dep.Amount) - suite.Require().NoError(err) - }) - } -} - -// createUnbondedValidator creates an unbonded validator with the given amount of self-delegation. -func (suite *grpcQueryTestSuite) createUnbondedValidator(address sdk.ValAddress, selfDelegation sdk.Coin, minSelfDelegation sdkmath.Int) error { - msg, err := stakingtypes.NewMsgCreateValidator( - address, - ed25519.GenPrivKey().PubKey(), - selfDelegation, - stakingtypes.Description{}, - stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - minSelfDelegation, - ) - if err != nil { - return err - } - - msgServer := stakingkeeper.NewMsgServerImpl(suite.tApp.GetStakingKeeper()) - _, err = msgServer.CreateValidator(sdk.WrapSDKContext(suite.ctx), msg) - return err -} - -// createAccountWithDerivatives creates an account with the given amount and denom of derivative token. -// Internally, it creates a validator account and mints derivatives from the validator's self delegation. -func (suite *grpcQueryTestSuite) createAccountWithDerivatives(denom string, amount sdkmath.Int) (sdk.AccAddress, sdk.Coin, sdk.Coins) { - bondDenom := suite.tApp.GetStakingKeeper().BondDenom(suite.ctx) - valAddress, err := liquidtypes.ParseLiquidStakingTokenDenom(denom) - suite.Require().NoError(err) - address := sdk.AccAddress(valAddress) - - remainingSelfDelegation := sdkmath.NewInt(1e6) - selfDelegation := sdk.NewCoin( - bondDenom, - amount.Add(remainingSelfDelegation), - ) - - // create & fund account - // ak := suite.tApp.GetAccountKeeper() - // acc := ak.NewAccountWithAddress(suite.ctx, address) - // ak.SetAccount(suite.ctx, acc) - err = suite.tApp.FundAccount(suite.ctx, address, sdk.NewCoins(selfDelegation)) - suite.Require().NoError(err) - - err = suite.createUnbondedValidator(valAddress, selfDelegation, remainingSelfDelegation) - suite.Require().NoError(err) - - toConvert := sdk.NewCoin(bondDenom, amount) - derivatives, err := suite.tApp.GetLiquidKeeper().MintDerivative(suite.ctx, - address, - valAddress, - toConvert, - ) - suite.Require().NoError(err) - - fullBalance := suite.tApp.GetBankKeeper().GetAllBalances(suite.ctx, address) - - return address, derivatives, fullBalance -} - -// slashValidator slashes the validator with the given address by the given percentage. -func (suite *grpcQueryTestSuite) slashValidator(address sdk.ValAddress, slashFraction sdk.Dec) error { - stakingKeeper := suite.tApp.GetStakingKeeper() - - validator, found := stakingKeeper.GetValidator(suite.ctx, address) - suite.Require().True(found) - consAddr, err := validator.GetConsAddr() - suite.Require().NoError(err) - - // Assume infraction was at current height. Note unbonding delegations and redelegations are only slashed if created after - // the infraction height so none will be slashed. - infractionHeight := suite.ctx.BlockHeight() - - power := stakingKeeper.TokensToConsensusPower(suite.ctx, validator.GetTokens()) - - stakingKeeper.Slash(suite.ctx, consAddr, infractionHeight, power, slashFraction) - return nil -} - -func TestGrpcQueryTestSuite(t *testing.T) { - suite.Run(t, new(grpcQueryTestSuite)) -} diff --git a/x/savings/keeper/hooks.go b/x/savings/keeper/hooks.go deleted file mode 100644 index ba05b1b7..00000000 --- a/x/savings/keeper/hooks.go +++ /dev/null @@ -1,24 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/savings/types" -) - -// Implements StakingHooks interface -var _ types.SavingsHooks = Keeper{} - -// AfterSavingsDepositCreated - call hook if registered -func (k Keeper) AfterSavingsDepositCreated(ctx sdk.Context, deposit types.Deposit) { - if k.hooks != nil { - k.hooks.AfterSavingsDepositCreated(ctx, deposit) - } -} - -// BeforeSavingsDepositModified - call hook if registered -func (k Keeper) BeforeSavingsDepositModified(ctx sdk.Context, deposit types.Deposit, incomingDenoms []string) { - if k.hooks != nil { - k.hooks.BeforeSavingsDepositModified(ctx, deposit, incomingDenoms) - } -} diff --git a/x/savings/keeper/invariants.go b/x/savings/keeper/invariants.go deleted file mode 100644 index 096557ee..00000000 --- a/x/savings/keeper/invariants.go +++ /dev/null @@ -1,67 +0,0 @@ -package keeper - -import ( - "github.com/0glabs/0g-chain/x/savings/types" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// RegisterInvariants registers the savings module invariants -func RegisterInvariants(ir sdk.InvariantRegistry, k Keeper) { - ir.RegisterRoute(types.ModuleName, "deposits", DepositsInvariant(k)) - ir.RegisterRoute(types.ModuleName, "solvency", SolvencyInvariant(k)) -} - -// AllInvariants runs all invariants of the savings module -func AllInvariants(k Keeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - if res, stop := DepositsInvariant(k)(ctx); stop { - return res, stop - } - - res, stop := SolvencyInvariant(k)(ctx) - return res, stop - } -} - -// DepositsInvariant iterates all deposits and asserts that they are valid -func DepositsInvariant(k Keeper) sdk.Invariant { - broken := false - message := sdk.FormatInvariant(types.ModuleName, "validate deposits broken", "deposit invalid") - - return func(ctx sdk.Context) (string, bool) { - k.IterateDeposits(ctx, func(deposit types.Deposit) bool { - if err := deposit.Validate(); err != nil { - broken = true - return true - } - if !deposit.Amount.IsAllPositive() { - broken = true - return true - } - return false - }) - - return message, broken - } -} - -// SolvencyInvariant iterates all deposits and ensures the total amount matches the module account coins -func SolvencyInvariant(k Keeper) sdk.Invariant { - message := sdk.FormatInvariant(types.ModuleName, "module solvency broken", "total deposited amount does not match module account") - - return func(ctx sdk.Context) (string, bool) { - balance := k.GetSavingsModuleAccountBalances(ctx) - - deposited := sdk.Coins{} - k.IterateDeposits(ctx, func(deposit types.Deposit) bool { - for _, coin := range deposit.Amount { - deposited = deposited.Add(coin) - } - return false - }) - - broken := !deposited.IsEqual(balance) - return message, broken - } -} diff --git a/x/savings/keeper/invariants_test.go b/x/savings/keeper/invariants_test.go deleted file mode 100644 index 23693b0d..00000000 --- a/x/savings/keeper/invariants_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package keeper_test - -import ( - "testing" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/savings/keeper" - "github.com/0glabs/0g-chain/x/savings/types" -) - -type invariantTestSuite struct { - suite.Suite - - tApp app.TestApp - ctx sdk.Context - keeper keeper.Keeper - bankKeeper bankkeeper.Keeper - addrs []sdk.AccAddress - invariants map[string]map[string]sdk.Invariant -} - -func (suite *invariantTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - _, addrs := app.GeneratePrivKeyAddressPairs(1) - suite.addrs = addrs - - suite.tApp = tApp - suite.ctx = ctx - suite.keeper = tApp.GetSavingsKeeper() - suite.bankKeeper = tApp.GetBankKeeper() - - suite.invariants = make(map[string]map[string]sdk.Invariant) - keeper.RegisterInvariants(suite, suite.keeper) -} - -func (suite *invariantTestSuite) RegisterRoute(moduleName string, route string, invariant sdk.Invariant) { - _, exists := suite.invariants[moduleName] - - if !exists { - suite.invariants[moduleName] = make(map[string]sdk.Invariant) - } - - suite.invariants[moduleName][route] = invariant -} - -func (suite *invariantTestSuite) SetupValidState() { - depositAmt := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(2e8))) - - suite.keeper.SetDeposit(suite.ctx, types.NewDeposit( - suite.addrs[0], - depositAmt, - )) - - err := suite.tApp.FundModuleAccount(suite.ctx, types.ModuleName, depositAmt) - suite.Require().NoError(err) -} - -func (suite *invariantTestSuite) runInvariant(route string, invariant func(k keeper.Keeper) sdk.Invariant) (string, bool) { - ctx := suite.ctx - registeredInvariant := suite.invariants[types.ModuleName][route] - suite.Require().NotNil(registeredInvariant) - - // direct call - dMessage, dBroken := invariant(suite.keeper)(ctx) - // registered call - rMessage, rBroken := registeredInvariant(ctx) - // all call - aMessage, aBroken := keeper.AllInvariants(suite.keeper)(ctx) - - // require matching values for direct call and registered call - suite.Require().Equal(dMessage, rMessage, "expected registered invariant message to match") - suite.Require().Equal(dBroken, rBroken, "expected registered invariant broken to match") - // require matching values for direct call and all invariants call if broken - suite.Require().Equal(dBroken, aBroken, "expected all invariant broken to match") - if dBroken { - suite.Require().Equal(dMessage, aMessage, "expected all invariant message to match") - } - - // return message, broken - return dMessage, dBroken -} - -func (suite *invariantTestSuite) TestDepositsInvariant() { - message, broken := suite.runInvariant("deposits", keeper.DepositsInvariant) - suite.Equal("savings: validate deposits broken invariant\ndeposit invalid\n", message) - suite.Equal(false, broken) - - suite.SetupValidState() - message, broken = suite.runInvariant("deposits", keeper.DepositsInvariant) - suite.Equal("savings: validate deposits broken invariant\ndeposit invalid\n", message) - suite.Equal(false, broken) - - // broken with invalid deposit - suite.keeper.SetDeposit(suite.ctx, types.NewDeposit( - suite.addrs[0], - sdk.Coins{}, - )) - - message, broken = suite.runInvariant("deposits", keeper.DepositsInvariant) - suite.Equal("savings: validate deposits broken invariant\ndeposit invalid\n", message) - suite.Equal(true, broken) -} - -func (suite *invariantTestSuite) TestSolvencyInvariant() { - message, broken := suite.runInvariant("solvency", keeper.SolvencyInvariant) - suite.Equal("savings: module solvency broken invariant\ntotal deposited amount does not match module account\n", message) - suite.Equal(false, broken) - - suite.SetupValidState() - message, broken = suite.runInvariant("solvency", keeper.SolvencyInvariant) - suite.Equal("savings: module solvency broken invariant\ntotal deposited amount does not match module account\n", message) - suite.Equal(false, broken) - - // broken when deposits are greater than module balance - suite.keeper.SetDeposit(suite.ctx, types.NewDeposit( - suite.addrs[0], - sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(3e8))), - )) - - message, broken = suite.runInvariant("solvency", keeper.SolvencyInvariant) - suite.Equal("savings: module solvency broken invariant\ntotal deposited amount does not match module account\n", message) - suite.Equal(true, broken) - - // broken when deposits are less than the module balance - suite.keeper.SetDeposit(suite.ctx, types.NewDeposit( - suite.addrs[0], - sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e8))), - )) - - message, broken = suite.runInvariant("solvency", keeper.SolvencyInvariant) - suite.Equal("savings: module solvency broken invariant\ntotal deposited amount does not match module account\n", message) - suite.Equal(true, broken) -} - -func TestInvariantTestSuite(t *testing.T) { - suite.Run(t, new(invariantTestSuite)) -} diff --git a/x/savings/keeper/keeper.go b/x/savings/keeper/keeper.go deleted file mode 100644 index 287d33a0..00000000 --- a/x/savings/keeper/keeper.go +++ /dev/null @@ -1,113 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/cometbft/cometbft/libs/log" - "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" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - - "github.com/0glabs/0g-chain/x/savings/types" -) - -// Keeper struct for savings module -type Keeper struct { - key storetypes.StoreKey - cdc codec.Codec - paramSubspace paramtypes.Subspace - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - liquidKeeper types.LiquidKeeper - hooks types.SavingsHooks -} - -// NewKeeper returns a new keeper for the savings module. -func NewKeeper( - cdc codec.Codec, key storetypes.StoreKey, paramstore paramtypes.Subspace, - ak types.AccountKeeper, bk types.BankKeeper, lk types.LiquidKeeper, -) Keeper { - if !paramstore.HasKeyTable() { - paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) - } - - return Keeper{ - cdc: cdc, - key: key, - paramSubspace: paramstore, - accountKeeper: ak, - bankKeeper: bk, - liquidKeeper: lk, - hooks: nil, - } -} - -// SetHooks adds hooks to the keeper. -func (k *Keeper) SetHooks(hooks types.MultiSavingsHooks) *Keeper { - if k.hooks != nil { - panic("cannot set savings hooks twice") - } - k.hooks = hooks - return k -} - -// GetSavingsModuleAccountBalances returns the savings module account balances -func (k Keeper) GetSavingsModuleAccountBalances(ctx sdk.Context) sdk.Coins { - savingMacc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) - return k.bankKeeper.GetAllBalances(ctx, savingMacc.GetAddress()) -} - -// GetDeposit returns a deposit from the store for a particular depositor address, deposit denom -func (k Keeper) GetDeposit(ctx sdk.Context, depositor sdk.AccAddress) (types.Deposit, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositsKeyPrefix) - bz := store.Get(depositor.Bytes()) - if len(bz) == 0 { - return types.Deposit{}, false - } - var deposit types.Deposit - k.cdc.MustUnmarshal(bz, &deposit) - return deposit, true -} - -// SetDeposit sets the input deposit in the store -func (k Keeper) SetDeposit(ctx sdk.Context, deposit types.Deposit) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositsKeyPrefix) - bz := k.cdc.MustMarshal(&deposit) - store.Set(deposit.Depositor.Bytes(), bz) -} - -// DeleteDeposit deletes a deposit from the store -func (k Keeper) DeleteDeposit(ctx sdk.Context, deposit types.Deposit) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositsKeyPrefix) - store.Delete(deposit.Depositor.Bytes()) -} - -// IterateDeposits iterates over all deposit objects in the store and performs a callback function -func (k Keeper) IterateDeposits(ctx sdk.Context, cb func(deposit types.Deposit) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositsKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var deposit types.Deposit - k.cdc.MustUnmarshal(iterator.Value(), &deposit) - if cb(deposit) { - break - } - } -} - -// GetAllDeposits returns all Deposits from the store -func (k Keeper) GetAllDeposits(ctx sdk.Context) (deposits types.Deposits) { - k.IterateDeposits(ctx, func(deposit types.Deposit) bool { - deposits = append(deposits, deposit) - return false - }) - return -} - -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) -} diff --git a/x/savings/keeper/keeper_test.go b/x/savings/keeper/keeper_test.go deleted file mode 100644 index 3bf01699..00000000 --- a/x/savings/keeper/keeper_test.go +++ /dev/null @@ -1,194 +0,0 @@ -package keeper_test - -import ( - "fmt" - "testing" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/savings/keeper" - "github.com/0glabs/0g-chain/x/savings/types" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" -) - -// Test suite used for all keeper tests -type KeeperTestSuite struct { - suite.Suite - keeper keeper.Keeper - app app.TestApp - ctx sdk.Context - addrs []sdk.AccAddress -} - -// The default state used by each test -func (suite *KeeperTestSuite) SetupTest() { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - tApp.InitializeFromGenesisStates() - _, addrs := app.GeneratePrivKeyAddressPairs(1) - keeper := tApp.GetSavingsKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - suite.addrs = addrs - - stakingParams := stakingtypes.DefaultParams() - stakingParams.BondDenom = "ukava" - suite.app.GetStakingKeeper().SetParams(suite.ctx, stakingParams) -} - -func (suite *KeeperTestSuite) TestGetSetDeleteDeposit() { - dep := types.NewDeposit(sdk.AccAddress("test"), sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100)))) - - _, f := suite.keeper.GetDeposit(suite.ctx, sdk.AccAddress("test")) - suite.Require().False(f) - - suite.keeper.SetDeposit(suite.ctx, dep) - - testDeposit, f := suite.keeper.GetDeposit(suite.ctx, sdk.AccAddress("test")) - suite.Require().True(f) - suite.Require().Equal(dep, testDeposit) - - suite.Require().NotPanics(func() { suite.keeper.DeleteDeposit(suite.ctx, dep) }) - _, f = suite.keeper.GetDeposit(suite.ctx, sdk.AccAddress("test")) - suite.Require().False(f) -} - -func (suite *KeeperTestSuite) TestIterateDeposits() { - for i := 0; i < 5; i++ { - dep := types.NewDeposit(sdk.AccAddress("test"+fmt.Sprint(i)), sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100)))) - suite.Require().NotPanics(func() { suite.keeper.SetDeposit(suite.ctx, dep) }) - } - var deposits []types.Deposit - suite.keeper.IterateDeposits(suite.ctx, func(d types.Deposit) bool { - deposits = append(deposits, d) - return false - }) - suite.Require().Equal(5, len(deposits)) -} - -func (suite *KeeperTestSuite) getAccountCoins(acc authtypes.AccountI) sdk.Coins { - bk := suite.app.GetBankKeeper() - return bk.GetAllBalances(suite.ctx, acc.GetAddress()) -} - -func (suite *KeeperTestSuite) getAccount(addr sdk.AccAddress) authtypes.AccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetAccount(suite.ctx, addr) -} - -func (suite *KeeperTestSuite) getAccountAtCtx(addr sdk.AccAddress, ctx sdk.Context) authtypes.AccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetAccount(ctx, addr) -} - -func (suite *KeeperTestSuite) getModuleAccount(name string) authtypes.ModuleAccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetModuleAccount(suite.ctx, name) -} - -func (suite *KeeperTestSuite) getModuleAccountAtCtx(name string, ctx sdk.Context) authtypes.ModuleAccountI { - ak := suite.app.GetAccountKeeper() - return ak.GetModuleAccount(ctx, name) -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(KeeperTestSuite)) -} - -// CreateAccount creates a new account from the provided balance and address -func (suite *KeeperTestSuite) CreateAccountWithAddress(addr sdk.AccAddress, initialBalance sdk.Coins) authtypes.AccountI { - ak := suite.app.GetAccountKeeper() - - acc := ak.NewAccountWithAddress(suite.ctx, addr) - ak.SetAccount(suite.ctx, acc) - - err := suite.app.FundAccount(suite.ctx, acc.GetAddress(), initialBalance) - suite.Require().NoError(err) - - return acc -} - -// CreateVestingAccount creates a new vesting account. `vestingBalance` should be a fraction of `initialBalance`. -func (suite *KeeperTestSuite) CreateVestingAccountWithAddress(addr sdk.AccAddress, initialBalance sdk.Coins, vestingBalance sdk.Coins) authtypes.AccountI { - if vestingBalance.IsAnyGT(initialBalance) { - panic("vesting balance must be less than initial balance") - } - acc := suite.CreateAccountWithAddress(addr, initialBalance) - bacc := acc.(*authtypes.BaseAccount) - - periods := vestingtypes.Periods{ - vestingtypes.Period{ - Length: 31556952, - Amount: vestingBalance, - }, - } - vacc := vestingtypes.NewPeriodicVestingAccount(bacc, vestingBalance, suite.ctx.BlockTime().Unix(), periods) - suite.app.GetAccountKeeper().SetAccount(suite.ctx, vacc) - return vacc -} - -func (suite *KeeperTestSuite) deliverMsgCreateValidator(ctx sdk.Context, address sdk.ValAddress, selfDelegation sdk.Coin) error { - msg, err := stakingtypes.NewMsgCreateValidator( - address, - ed25519.GenPrivKey().PubKey(), - selfDelegation, - stakingtypes.Description{}, - stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - sdkmath.NewInt(1e6), - ) - if err != nil { - return err - } - - msgServer := stakingkeeper.NewMsgServerImpl(suite.app.GetStakingKeeper()) - _, err = msgServer.CreateValidator(sdk.WrapSDKContext(suite.ctx), msg) - return err -} - -// CreateNewUnbondedValidator creates a new validator in the staking module. -// New validators are unbonded until the end blocker is run. -func (suite *KeeperTestSuite) CreateNewUnbondedValidator(addr sdk.ValAddress, selfDelegation sdkmath.Int) stakingtypes.Validator { - // Create a validator - err := suite.deliverMsgCreateValidator(suite.ctx, addr, sdk.NewCoin("ukava", selfDelegation)) - suite.Require().NoError(err) - - // New validators are created in an unbonded state. Note if the end blocker is run later this validator could become bonded. - - validator, found := suite.app.GetStakingKeeper().GetValidator(suite.ctx, addr) - suite.Require().True(found) - return validator -} - -// CreateDelegation delegates tokens to a validator. -func (suite *KeeperTestSuite) CreateDelegation(valAddr sdk.ValAddress, delegator sdk.AccAddress, amount sdkmath.Int) sdk.Dec { - sk := suite.app.GetStakingKeeper() - - stakingDenom := sk.BondDenom(suite.ctx) - msg := stakingtypes.NewMsgDelegate( - delegator, - valAddr, - sdk.NewCoin(stakingDenom, amount), - ) - - msgServer := stakingkeeper.NewMsgServerImpl(sk) - _, err := msgServer.Delegate(sdk.WrapSDKContext(suite.ctx), msg) - suite.Require().NoError(err) - - del, found := sk.GetDelegation(suite.ctx, delegator, valAddr) - suite.Require().True(found) - return del.Shares -} diff --git a/x/savings/keeper/msg_server.go b/x/savings/keeper/msg_server.go deleted file mode 100644 index 1b146629..00000000 --- a/x/savings/keeper/msg_server.go +++ /dev/null @@ -1,67 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/savings/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the savings MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -func (k msgServer) Deposit(goCtx context.Context, msg *types.MsgDeposit) (*types.MsgDepositResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - - err = k.keeper.Deposit(ctx, depositor, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Depositor), - ), - ) - return &types.MsgDepositResponse{}, nil -} - -func (k msgServer) Withdraw(goCtx context.Context, msg *types.MsgWithdraw) (*types.MsgWithdrawResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - - err = k.keeper.Withdraw(ctx, depositor, msg.Amount) - if err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Depositor), - ), - ) - return &types.MsgWithdrawResponse{}, nil -} diff --git a/x/savings/keeper/params.go b/x/savings/keeper/params.go deleted file mode 100644 index 5ba6ece9..00000000 --- a/x/savings/keeper/params.go +++ /dev/null @@ -1,43 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - liquidtypes "github.com/0glabs/0g-chain/x/liquid/types" - "github.com/0glabs/0g-chain/x/savings/types" -) - -const ( - bkavaDenom = "bkava" - bkavaPrefix = bkavaDenom + "-" -) - -// GetParams returns the params from the store -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - var p types.Params - k.paramSubspace.GetParamSet(ctx, &p) - return p -} - -// SetParams sets params on the store -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSubspace.SetParamSet(ctx, ¶ms) -} - -// IsDenomSupported returns a boolean indicating if a denom is supported -func (k Keeper) IsDenomSupported(ctx sdk.Context, denom string) bool { - p := k.GetParams(ctx) - for _, supportedDenom := range p.SupportedDenoms { - if supportedDenom == denom { - return true - } - - if supportedDenom == liquidtypes.DefaultDerivativeDenom { - if k.liquidKeeper.IsDerivativeDenom(ctx, denom) { - return true - } - } - } - - return false -} diff --git a/x/savings/keeper/params_test.go b/x/savings/keeper/params_test.go deleted file mode 100644 index 0ec5351c..00000000 --- a/x/savings/keeper/params_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package keeper_test - -import ( - "github.com/0glabs/0g-chain/x/savings/types" -) - -func (suite *KeeperTestSuite) TestGetSetParams() { - params := suite.keeper.GetParams(suite.ctx) - suite.Require().Equal( - types.Params{SupportedDenoms: []string(nil)}, - params, - ) - - newParams := types.NewParams([]string{"btc", "test"}) - suite.keeper.SetParams(suite.ctx, newParams) - - fetchedParams := suite.keeper.GetParams(suite.ctx) - suite.Require().Equal(newParams, fetchedParams) -} diff --git a/x/savings/keeper/withdraw.go b/x/savings/keeper/withdraw.go deleted file mode 100644 index a175ac40..00000000 --- a/x/savings/keeper/withdraw.go +++ /dev/null @@ -1,63 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/savings/types" -) - -// Withdraw returns some or all of a deposit back to original depositor -func (k Keeper) Withdraw(ctx sdk.Context, depositor sdk.AccAddress, coins sdk.Coins) error { - deposit, found := k.GetDeposit(ctx, depositor) - if !found { - return errorsmod.Wrap(types.ErrNoDepositFound, fmt.Sprintf(" for address: %s", depositor.String())) - } - - amount, err := k.CalculateWithdrawAmount(deposit.Amount, coins) - if err != nil { - return err - } - - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, depositor, amount) - if err != nil { - return err - } - - deposit.Amount = deposit.Amount.Sub(amount...) - if deposit.Amount.Empty() { - k.DeleteDeposit(ctx, deposit) - } else { - k.SetDeposit(ctx, deposit) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeSavingsWithdrawal, - sdk.NewAttribute(sdk.AttributeKeyAmount, amount.String()), - sdk.NewAttribute(types.AttributeKeyDepositor, depositor.String()), - ), - ) - return nil -} - -// CalculateWithdrawAmount enables full withdraw of deposited coins by adjusting withdraw amount -// to equal total deposit amount if the requested withdraw amount > current deposit amount -func (k Keeper) CalculateWithdrawAmount(available sdk.Coins, request sdk.Coins) (sdk.Coins, error) { - result := sdk.Coins{} - - if !request.DenomsSubsetOf(available) { - return result, types.ErrInvalidWithdrawDenom - } - - for _, coin := range request { - if coin.Amount.GT(available.AmountOf(coin.Denom)) { - result = append(result, sdk.NewCoin(coin.Denom, available.AmountOf(coin.Denom))) - } else { - result = append(result, coin) - } - } - return result, nil -} diff --git a/x/savings/keeper/withdraw_test.go b/x/savings/keeper/withdraw_test.go deleted file mode 100644 index 3aec0356..00000000 --- a/x/savings/keeper/withdraw_test.go +++ /dev/null @@ -1,202 +0,0 @@ -package keeper_test - -import ( - "fmt" - "strings" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/savings/types" -) - -func (suite *KeeperTestSuite) TestWithdraw() { - _, addrs := app.GeneratePrivKeyAddressPairs(5) - valAccAddr, delegator := addrs[0], addrs[1] - - valAddr := sdk.ValAddress(valAccAddr) - initialBalance := sdkmath.NewInt(1e9) - - bkavaDenom := fmt.Sprintf("bkava-%s", valAddr.String()) - - type args struct { - allowedDenoms []string - depositor sdk.AccAddress - initialDepositorBalance sdk.Coins - depositAmount sdk.Coins - withdrawAmount sdk.Coins - expectedAccountBalance sdk.Coins - expectedModAccountBalance sdk.Coins - expectedDepositCoins sdk.Coins - } - type errArgs struct { - expectPass bool - expectDelete bool - contains string - } - type withdrawTest struct { - name string - args args - errArgs errArgs - } - testCases := []withdrawTest{ - { - "valid: partial withdraw", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava"}, - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - withdrawAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(900)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - expectedDepositCoins: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(100))), - }, - errArgs{ - expectPass: true, - expectDelete: false, - contains: "", - }, - }, - { - "valid: partial bkava", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava", "bkava"}, - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(200))), - withdrawAmount: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(100))), - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(900)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(100))), - expectedDepositCoins: sdk.NewCoins(sdk.NewCoin(bkavaDenom, sdkmath.NewInt(100))), - }, - errArgs{ - expectPass: true, - expectDelete: false, - contains: "", - }, - }, - { - "valid: full withdraw", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava"}, - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - withdrawAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.Coins{}, - expectedDepositCoins: sdk.Coins{}, - }, - errArgs{ - expectPass: true, - expectDelete: true, - contains: "", - }, - }, - { - "valid: withdraw exceeds deposit but is adjusted to match max deposit", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava"}, - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - withdrawAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(300))), - expectedAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - expectedModAccountBalance: sdk.Coins{}, - expectedDepositCoins: sdk.Coins{}, - }, - errArgs{ - expectPass: true, - expectDelete: true, - contains: "", - }, - }, - { - "invalid: withdraw non-supplied coin type", - args{ - allowedDenoms: []string{"bnb", "btcb", "ukava"}, - depositor: sdk.AccAddress(crypto.AddressHash([]byte("test"))), - initialDepositorBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(1000)), sdk.NewCoin("btcb", sdkmath.NewInt(1000))), - depositAmount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - withdrawAmount: sdk.NewCoins(sdk.NewCoin("btcb", sdkmath.NewInt(200))), - expectedAccountBalance: sdk.Coins{}, - expectedModAccountBalance: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(200))), - expectedDepositCoins: sdk.Coins{}, - }, - errArgs{ - expectPass: false, - expectDelete: false, - contains: "invalid withdraw denom", - }, - }, - } - for _, tc := range testCases { - suite.Run(tc.name, func() { - // Initialize test app and set context - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - authGS := app.NewFundedGenStateWithCoins( - tApp.AppCodec(), - []sdk.Coins{tc.args.initialDepositorBalance}, - []sdk.AccAddress{tc.args.depositor}, - ) - savingsGS := types.NewGenesisState( - types.NewParams(tc.args.allowedDenoms), - types.Deposits{}, - ) - - stakingParams := stakingtypes.DefaultParams() - stakingParams.BondDenom = "ukava" - - tApp.InitializeFromGenesisStates(authGS, - app.GenesisState{types.ModuleName: tApp.AppCodec().MustMarshalJSON(&savingsGS)}, - app.GenesisState{stakingtypes.ModuleName: tApp.AppCodec().MustMarshalJSON(stakingtypes.NewGenesisState(stakingParams, nil, nil))}, - ) - keeper := tApp.GetSavingsKeeper() - suite.app = tApp - suite.ctx = ctx - suite.keeper = keeper - bankKeeper := tApp.GetBankKeeper() - - // Create validator and delegate for bkava - suite.CreateAccountWithAddress(valAccAddr, cs(c("ukava", 100e10))) - suite.CreateAccountWithAddress(delegator, cs(c("ukava", 100e10))) - - suite.CreateNewUnbondedValidator(valAddr, initialBalance) - suite.CreateDelegation(valAddr, delegator, initialBalance) - staking.EndBlocker(suite.ctx, suite.app.GetStakingKeeper()) - - err := suite.keeper.Deposit(suite.ctx, tc.args.depositor, tc.args.depositAmount) - suite.Require().NoError(err) - - err = suite.keeper.Withdraw(suite.ctx, tc.args.depositor, tc.args.withdrawAmount) - if tc.errArgs.expectPass { - suite.Require().NoError(err) - // Check depositor's account balance - acc := suite.getAccount(tc.args.depositor) - suite.Require().Equal(tc.args.expectedAccountBalance, bankKeeper.GetAllBalances(ctx, acc.GetAddress())) - // Check savings module account balance - mAcc := suite.getModuleAccount(types.ModuleAccountName) - suite.Require().True(tc.args.expectedModAccountBalance.IsEqual(bankKeeper.GetAllBalances(ctx, mAcc.GetAddress()))) - // Check deposit - testDeposit, f := suite.keeper.GetDeposit(suite.ctx, tc.args.depositor) - if tc.errArgs.expectDelete { - suite.Require().False(f) - } else { - suite.Require().True(f) - suite.Require().Equal(tc.args.expectedDepositCoins, testDeposit.Amount) - } - } else { - suite.Require().Error(err) - suite.Require().True(strings.Contains(err.Error(), tc.errArgs.contains)) - } - }) - } -} diff --git a/x/savings/module.go b/x/savings/module.go deleted file mode 100644 index ebc0f3d1..00000000 --- a/x/savings/module.go +++ /dev/null @@ -1,146 +0,0 @@ -package savings - -import ( - "context" - "encoding/json" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/0glabs/0g-chain/x/savings/client/cli" - "github.com/0glabs/0g-chain/x/savings/keeper" - "github.com/0glabs/0g-chain/x/savings/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name get module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - gs := types.DefaultGenesisState() - return cdc.MustMarshalJSON(&gs) -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - err := cdc.UnmarshalJSON(bz, &gs) - if err != nil { - return err - } - return gs.Validate() -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the gov module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// GetTxCmd returns the root tx command for the module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -//____________________________________________________________________________ - -// AppModule app module type -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper authkeeper.AccountKeeper - bankKeeper types.BankKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, accountKeeper authkeeper.AccountKeeper, bankKeeper types.BankKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - } -} - -// Name module name -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// RegisterInvariants register module invariants -func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { - keeper.RegisterInvariants(ir, am.keeper) -} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return 1 -} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) -} - -// InitGenesis module init-genesis -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { - var genState types.GenesisState - // Initialize global index to index in genesis state - cdc.MustUnmarshalJSON(gs, &genState) - - InitGenesis(ctx, am.keeper, am.accountKeeper, genState) - - return []abci.ValidatorUpdate{} -} - -// ExportGenesis module export genesis -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(&gs) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) { -} - -// EndBlock module end-block -func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/savings/types/codec.go b/x/savings/types/codec.go deleted file mode 100644 index 44048a87..00000000 --- a/x/savings/types/codec.go +++ /dev/null @@ -1,40 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the -// savings module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgDeposit{}, "savings/MsgDeposit", nil) - cdc.RegisterConcrete(&MsgWithdraw{}, "savings/MsgWithdraw", nil) -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgDeposit{}, - &MsgWithdraw{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/savings/types/deposit.go b/x/savings/types/deposit.go deleted file mode 100644 index a7632c8c..00000000 --- a/x/savings/types/deposit.go +++ /dev/null @@ -1,46 +0,0 @@ -package types - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// NewDeposit returns a new deposit -func NewDeposit(depositor sdk.AccAddress, amount sdk.Coins) Deposit { - return Deposit{ - Depositor: depositor, - Amount: amount, - } -} - -// Validate deposit validation -func (d Deposit) Validate() error { - if d.Depositor.Empty() { - return fmt.Errorf("depositor cannot be empty") - } - if !d.Amount.IsValid() { - return fmt.Errorf("invalid deposit coins: %s", d.Amount) - } - - return nil -} - -// Deposits is a slice of Deposit -type Deposits []Deposit - -// Validate validates Deposits -func (ds Deposits) Validate() error { - depositDupMap := make(map[string]Deposit) - for _, d := range ds { - if err := d.Validate(); err != nil { - return err - } - dup, ok := depositDupMap[d.Depositor.String()] - if ok { - return fmt.Errorf("duplicate depositor: %s\n%s", d, dup) - } - depositDupMap[d.Depositor.String()] = d - } - return nil -} diff --git a/x/savings/types/errors.go b/x/savings/types/errors.go deleted file mode 100644 index bcaa8efb..00000000 --- a/x/savings/types/errors.go +++ /dev/null @@ -1,16 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -// DONTCOVER - -var ( - // ErrEmptyInput error for empty input - ErrEmptyInput = errorsmod.Register(ModuleName, 2, "input must not be empty") - // ErrNoDepositFound error when no deposit is found for an address - ErrNoDepositFound = errorsmod.Register(ModuleName, 3, "no deposit found") - // ErrInvalidDepositDenom error for invalid deposit denom - ErrInvalidDepositDenom = errorsmod.Register(ModuleName, 4, "invalid deposit denom") - // ErrInvalidWithdrawDenom error for invalid withdraw denoms - ErrInvalidWithdrawDenom = errorsmod.Register(ModuleName, 5, "invalid withdraw denom") -) diff --git a/x/savings/types/events.go b/x/savings/types/events.go deleted file mode 100644 index 2f30ebe1..00000000 --- a/x/savings/types/events.go +++ /dev/null @@ -1,10 +0,0 @@ -package types - -const ( - EventTypeSavingsDeposit = "deposit_savings" - EventTypeSavingsWithdrawal = "withdraw_savings" - - AttributeValueCategory = ModuleName - AttributeKeyAmount = "amount" - AttributeKeyDepositor = "depositor" -) diff --git a/x/savings/types/expected_keepers.go b/x/savings/types/expected_keepers.go deleted file mode 100644 index 7072936c..00000000 --- a/x/savings/types/expected_keepers.go +++ /dev/null @@ -1,38 +0,0 @@ -package types // noalias - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// BankKeeper defines the expected bank keeper -type BankKeeper interface { - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - - GetSupply(ctx sdk.Context, denom string) sdk.Coin - GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins -} - -// AccountKeeper defines the expected keeper interface for interacting with account -type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI - SetAccount(ctx sdk.Context, acc authtypes.AccountI) - - GetModuleAddress(name string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, name string) authtypes.ModuleAccountI -} - -// SavingsHooks event hooks for other keepers to run code in response to Savings modifications -type SavingsHooks interface { - AfterSavingsDepositCreated(ctx sdk.Context, deposit Deposit) - BeforeSavingsDepositModified(ctx sdk.Context, deposit Deposit, incomingDenoms []string) -} - -type LiquidKeeper interface { - GetStakedTokensForDerivatives(ctx sdk.Context, derivatives sdk.Coins) (sdk.Coin, error) - IsDerivativeDenom(ctx sdk.Context, denom string) bool -} diff --git a/x/savings/types/genesis.go b/x/savings/types/genesis.go deleted file mode 100644 index c0027ad0..00000000 --- a/x/savings/types/genesis.go +++ /dev/null @@ -1,27 +0,0 @@ -package types - -// NewGenesisState creates a new genesis state for the savings module -func NewGenesisState(p Params, deposits Deposits) GenesisState { - return GenesisState{ - Params: p, - Deposits: deposits, - } -} - -// DefaultGenesisState defines default GenesisState for savings -func DefaultGenesisState() GenesisState { - return NewGenesisState( - DefaultParams(), - Deposits{}, - ) -} - -// Validate performs basic validation of genesis data returning an -// error for any failed validation criteria. -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - - return gs.Deposits.Validate() -} diff --git a/x/savings/types/genesis.pb.go b/x/savings/types/genesis.pb.go deleted file mode 100644 index 156a7dad..00000000 --- a/x/savings/types/genesis.pb.go +++ /dev/null @@ -1,389 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/savings/v1beta1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// GenesisState defines the savings module's genesis state. -type GenesisState struct { - // params defines all the parameters of the module. - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - Deposits Deposits `protobuf:"bytes,2,rep,name=deposits,proto3,castrepeated=Deposits" json:"deposits"` -} - -func (m *GenesisState) Reset() { *m = GenesisState{} } -func (m *GenesisState) String() string { return proto.CompactTextString(m) } -func (*GenesisState) ProtoMessage() {} -func (*GenesisState) Descriptor() ([]byte, []int) { - return fileDescriptor_f5dcde4d417fcec8, []int{0} -} -func (m *GenesisState) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisState) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisState.Merge(m, src) -} -func (m *GenesisState) XXX_Size() int { - return m.Size() -} -func (m *GenesisState) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisState.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisState proto.InternalMessageInfo - -func (m *GenesisState) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -func (m *GenesisState) GetDeposits() Deposits { - if m != nil { - return m.Deposits - } - return nil -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "kava.savings.v1beta1.GenesisState") -} - -func init() { - proto.RegisterFile("kava/savings/v1beta1/genesis.proto", fileDescriptor_f5dcde4d417fcec8) -} - -var fileDescriptor_f5dcde4d417fcec8 = []byte{ - // 252 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xca, 0x4e, 0x2c, 0x4b, - 0xd4, 0x2f, 0x4e, 0x2c, 0xcb, 0xcc, 0x4b, 0x2f, 0xd6, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, - 0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, - 0x01, 0xa9, 0xd1, 0x83, 0xaa, 0xd1, 0x83, 0xaa, 0x91, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x2b, - 0xd0, 0x07, 0xb1, 0x20, 0x6a, 0xa5, 0x14, 0xb0, 0x9a, 0x57, 0x5c, 0x92, 0x5f, 0x94, 0x0a, 0x51, - 0xa1, 0x34, 0x9d, 0x91, 0x8b, 0xc7, 0x1d, 0x62, 0x7e, 0x70, 0x49, 0x62, 0x49, 0xaa, 0x90, 0x15, - 0x17, 0x5b, 0x41, 0x62, 0x51, 0x62, 0x6e, 0xb1, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0xb7, 0x91, 0x8c, - 0x1e, 0x36, 0xfb, 0xf4, 0x02, 0xc0, 0x6a, 0x9c, 0x58, 0x4e, 0xdc, 0x93, 0x67, 0x08, 0x82, 0xea, - 0x10, 0xf2, 0xe6, 0xe2, 0x48, 0x49, 0x2d, 0xc8, 0x2f, 0xce, 0x2c, 0x29, 0x96, 0x60, 0x52, 0x60, - 0xd6, 0xe0, 0x36, 0x92, 0xc5, 0xae, 0xdb, 0x05, 0xa2, 0xca, 0x49, 0x00, 0xa4, 0x7d, 0xd5, 0x7d, - 0x79, 0x0e, 0xa8, 0x40, 0x71, 0x10, 0xdc, 0x00, 0x27, 0x97, 0x13, 0x8f, 0xe4, 0x18, 0x2f, 0x3c, - 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, 0x39, 0x86, 0x0b, 0x8f, 0xe5, 0x18, 0x6e, - 0x3c, 0x96, 0x63, 0x88, 0xd2, 0x4a, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, - 0x37, 0x48, 0xcf, 0x49, 0x4c, 0x2a, 0xd6, 0x37, 0x48, 0xd7, 0x4d, 0xce, 0x48, 0xcc, 0xcc, 0xd3, - 0xaf, 0x80, 0xfb, 0xb6, 0xa4, 0xb2, 0x20, 0xb5, 0x38, 0x89, 0x0d, 0xec, 0x4d, 0x63, 0x40, 0x00, - 0x00, 0x00, 0xff, 0xff, 0x05, 0x7d, 0xc8, 0x49, 0x5a, 0x01, 0x00, 0x00, -} - -func (m *GenesisState) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Deposits) > 0 { - for iNdEx := len(m.Deposits) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposits[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *GenesisState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.Deposits) > 0 { - for _, e := range m.Deposits { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *GenesisState) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposits", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Deposits = append(m.Deposits, Deposit{}) - if err := m.Deposits[len(m.Deposits)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/savings/types/hooks.go b/x/savings/types/hooks.go deleted file mode 100644 index b4441b59..00000000 --- a/x/savings/types/hooks.go +++ /dev/null @@ -1,25 +0,0 @@ -package types - -import sdk "github.com/cosmos/cosmos-sdk/types" - -// MultiSavingsHooks combine multiple Savings hooks, all hook functions are run in array sequence -type MultiSavingsHooks []SavingsHooks - -// NewMultiSavingsHooks returns a new MultiSavingsHooks -func NewMultiSavingsHooks(hooks ...SavingsHooks) MultiSavingsHooks { - return hooks -} - -// AfterSavingsDepositCreated runs after a deposit is created -func (s MultiSavingsHooks) AfterSavingsDepositCreated(ctx sdk.Context, deposit Deposit) { - for i := range s { - s[i].AfterSavingsDepositCreated(ctx, deposit) - } -} - -// BeforeSavingsDepositModified runs before a deposit is modified -func (s MultiSavingsHooks) BeforeSavingsDepositModified(ctx sdk.Context, deposit Deposit, incomingDenoms []string) { - for i := range s { - s[i].BeforeSavingsDepositModified(ctx, deposit, incomingDenoms) - } -} diff --git a/x/savings/types/key.go b/x/savings/types/key.go deleted file mode 100644 index 6bf64608..00000000 --- a/x/savings/types/key.go +++ /dev/null @@ -1,20 +0,0 @@ -package types - -const ( - // ModuleName The name that will be used throughout the module - ModuleName = "savings" - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey Top level router key - RouterKey = ModuleName - - // DefaultParamspace default namestore - DefaultParamspace = ModuleName - - // ModuleAccountName is the module account's name - ModuleAccountName = ModuleName -) - -var DepositsKeyPrefix = []byte{0x01} diff --git a/x/savings/types/msg.go b/x/savings/types/msg.go deleted file mode 100644 index f6dae871..00000000 --- a/x/savings/types/msg.go +++ /dev/null @@ -1,97 +0,0 @@ -package types - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// ensure Msg interface compliance at compile time -var ( - _ sdk.Msg = &MsgDeposit{} - _ sdk.Msg = &MsgWithdraw{} -) - -// NewMsgDeposit returns a new MsgDeposit -func NewMsgDeposit(depositor sdk.AccAddress, amount sdk.Coins) MsgDeposit { - return MsgDeposit{ - Depositor: depositor.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgDeposit) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgDeposit) Type() string { return "savings_deposit" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgDeposit) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "deposit amount %s", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgDeposit) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgDeposit) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - panic(err) - } - return []sdk.AccAddress{depositor} -} - -// NewMsgWithdraw returns a new MsgWithdraw -func NewMsgWithdraw(depositor sdk.AccAddress, amount sdk.Coins) MsgWithdraw { - return MsgWithdraw{ - Depositor: depositor.String(), - Amount: amount, - } -} - -// Route return the message type used for routing the message. -func (msg MsgWithdraw) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgWithdraw) Type() string { return "savings_withdraw" } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgWithdraw) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - - if !msg.Amount.IsValid() || msg.Amount.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "withdraw amount %s", msg.Amount) - } - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgWithdraw) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgWithdraw) GetSigners() []sdk.AccAddress { - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - panic(err) - } - return []sdk.AccAddress{depositor} -} diff --git a/x/savings/types/params.go b/x/savings/types/params.go deleted file mode 100644 index a22a3d2e..00000000 --- a/x/savings/types/params.go +++ /dev/null @@ -1,59 +0,0 @@ -package types - -import ( - "fmt" - - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -// Parameter keys -var ( - KeySupportedDenoms = []byte("SupportedDenoms") - DefaultSupportedDenoms = []string{} -) - -// NewParams creates a new Params object -func NewParams(supportedDenoms []string) Params { - return Params{ - SupportedDenoms: supportedDenoms, - } -} - -// DefaultParams default params for savings -func DefaultParams() Params { - return NewParams(DefaultSupportedDenoms) -} - -// ParamKeyTable Key declaration for parameters -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements the ParamSet interface and returns all the key/value pairs -// pairs of savings module's parameters. -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeySupportedDenoms, &p.SupportedDenoms, validateSupportedDenoms), - } -} - -// Validate ensure that params have valid values -func (p Params) Validate() error { - return validateSupportedDenoms(p.SupportedDenoms) -} - -func validateSupportedDenoms(i interface{}) error { - supportedDenoms, ok := i.([]string) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - seenDenoms := make(map[string]bool) - for _, denom := range supportedDenoms { - if seenDenoms[denom] { - return fmt.Errorf("duplicated denom %s", denom) - } - seenDenoms[denom] = true - } - return nil -} diff --git a/x/savings/types/query.pb.go b/x/savings/types/query.pb.go deleted file mode 100644 index d15840bc..00000000 --- a/x/savings/types/query.pb.go +++ /dev/null @@ -1,1495 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/savings/v1beta1/query.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - query "github.com/cosmos/cosmos-sdk/types/query" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// QueryParamsRequest defines the request type for querying x/savings -// parameters. -type QueryParamsRequest struct { -} - -func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } -func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryParamsRequest) ProtoMessage() {} -func (*QueryParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_f78c91efc5db144f, []int{0} -} -func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsRequest.Merge(m, src) -} -func (m *QueryParamsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo - -// QueryParamsResponse defines the response type for querying x/savings -// parameters. -type QueryParamsResponse struct { - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` -} - -func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } -func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryParamsResponse) ProtoMessage() {} -func (*QueryParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_f78c91efc5db144f, []int{1} -} -func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsResponse.Merge(m, src) -} -func (m *QueryParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo - -// QueryDepositsRequest defines the request type for querying x/savings -// deposits. -type QueryDepositsRequest struct { - Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty"` - Owner string `protobuf:"bytes,2,opt,name=owner,proto3" json:"owner,omitempty"` - Pagination *query.PageRequest `protobuf:"bytes,3,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDepositsRequest) Reset() { *m = QueryDepositsRequest{} } -func (m *QueryDepositsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsRequest) ProtoMessage() {} -func (*QueryDepositsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_f78c91efc5db144f, []int{2} -} -func (m *QueryDepositsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryDepositsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsRequest.Merge(m, src) -} -func (m *QueryDepositsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsRequest proto.InternalMessageInfo - -func (m *QueryDepositsRequest) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *QueryDepositsRequest) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *QueryDepositsRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryDepositsResponse defines the response type for querying x/savings -// deposits. -type QueryDepositsResponse struct { - Deposits Deposits `protobuf:"bytes,1,rep,name=deposits,proto3,castrepeated=Deposits" json:"deposits"` - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDepositsResponse) Reset() { *m = QueryDepositsResponse{} } -func (m *QueryDepositsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsResponse) ProtoMessage() {} -func (*QueryDepositsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_f78c91efc5db144f, []int{3} -} -func (m *QueryDepositsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryDepositsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsResponse.Merge(m, src) -} -func (m *QueryDepositsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsResponse proto.InternalMessageInfo - -func (m *QueryDepositsResponse) GetDeposits() Deposits { - if m != nil { - return m.Deposits - } - return nil -} - -func (m *QueryDepositsResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryTotalSupplyRequest defines the request type for Query/TotalSupply method. -type QueryTotalSupplyRequest struct { -} - -func (m *QueryTotalSupplyRequest) Reset() { *m = QueryTotalSupplyRequest{} } -func (m *QueryTotalSupplyRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalSupplyRequest) ProtoMessage() {} -func (*QueryTotalSupplyRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_f78c91efc5db144f, []int{4} -} -func (m *QueryTotalSupplyRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalSupplyRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalSupplyRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTotalSupplyRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalSupplyRequest.Merge(m, src) -} -func (m *QueryTotalSupplyRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalSupplyRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalSupplyRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalSupplyRequest proto.InternalMessageInfo - -// TotalSupplyResponse defines the response type for the Query/TotalSupply method. -type QueryTotalSupplyResponse struct { - // Height is the block height at which these totals apply - Height int64 `protobuf:"varint,1,opt,name=height,proto3" json:"height,omitempty"` - // Result is a list of coins supplied to savings - Result github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=result,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"result"` -} - -func (m *QueryTotalSupplyResponse) Reset() { *m = QueryTotalSupplyResponse{} } -func (m *QueryTotalSupplyResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalSupplyResponse) ProtoMessage() {} -func (*QueryTotalSupplyResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_f78c91efc5db144f, []int{5} -} -func (m *QueryTotalSupplyResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalSupplyResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalSupplyResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryTotalSupplyResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalSupplyResponse.Merge(m, src) -} -func (m *QueryTotalSupplyResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalSupplyResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalSupplyResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalSupplyResponse proto.InternalMessageInfo - -func (m *QueryTotalSupplyResponse) GetHeight() int64 { - if m != nil { - return m.Height - } - return 0 -} - -func (m *QueryTotalSupplyResponse) GetResult() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Result - } - return nil -} - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.savings.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.savings.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryDepositsRequest)(nil), "kava.savings.v1beta1.QueryDepositsRequest") - proto.RegisterType((*QueryDepositsResponse)(nil), "kava.savings.v1beta1.QueryDepositsResponse") - proto.RegisterType((*QueryTotalSupplyRequest)(nil), "kava.savings.v1beta1.QueryTotalSupplyRequest") - proto.RegisterType((*QueryTotalSupplyResponse)(nil), "kava.savings.v1beta1.QueryTotalSupplyResponse") -} - -func init() { proto.RegisterFile("kava/savings/v1beta1/query.proto", fileDescriptor_f78c91efc5db144f) } - -var fileDescriptor_f78c91efc5db144f = []byte{ - // 623 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x94, 0x4f, 0x6f, 0x12, 0x41, - 0x18, 0xc6, 0x19, 0x68, 0x49, 0x9d, 0x5e, 0xcc, 0xb8, 0xea, 0x96, 0xe0, 0x42, 0x36, 0x4d, 0x45, - 0x0c, 0xbb, 0x14, 0x6f, 0xbd, 0x89, 0x8d, 0x1e, 0xbc, 0xe8, 0xd6, 0xc4, 0xc4, 0x4b, 0x33, 0xc0, - 0x64, 0xd8, 0x14, 0x76, 0xb6, 0x3b, 0x03, 0xca, 0x55, 0x2f, 0x26, 0x5e, 0x4c, 0x3c, 0xe8, 0xd1, - 0x83, 0x27, 0x13, 0x6f, 0xc6, 0xcf, 0xd0, 0x63, 0xa3, 0x17, 0x4f, 0x6a, 0xc0, 0x0f, 0x62, 0x76, - 0x66, 0x76, 0x0b, 0x65, 0x53, 0x39, 0xc1, 0xbc, 0xf3, 0x3c, 0xef, 0xfc, 0xde, 0x3f, 0x00, 0xab, - 0x47, 0x78, 0x8c, 0x5d, 0x8e, 0xc7, 0x7e, 0x40, 0xb9, 0x3b, 0xde, 0xed, 0x10, 0x81, 0x77, 0xdd, - 0xe3, 0x11, 0x89, 0x26, 0x4e, 0x18, 0x31, 0xc1, 0x90, 0x11, 0x2b, 0x1c, 0xad, 0x70, 0xb4, 0xa2, - 0x54, 0xef, 0x32, 0x3e, 0x64, 0xdc, 0xed, 0x60, 0x4e, 0x94, 0x3c, 0x35, 0x87, 0x98, 0xfa, 0x01, - 0x16, 0x3e, 0x0b, 0x54, 0x86, 0x92, 0x35, 0xaf, 0x4d, 0x54, 0x5d, 0xe6, 0x27, 0xf7, 0x5b, 0xea, - 0xfe, 0x50, 0x9e, 0x5c, 0x75, 0xd0, 0x57, 0x06, 0x65, 0x94, 0xa9, 0x78, 0xfc, 0x4d, 0x47, 0xcb, - 0x94, 0x31, 0x3a, 0x20, 0x2e, 0x0e, 0x7d, 0x17, 0x07, 0x01, 0x13, 0xf2, 0xb5, 0xc4, 0x93, 0x5d, - 0x12, 0x17, 0x2c, 0x22, 0x4a, 0x61, 0x1b, 0x10, 0x3d, 0x8e, 0x91, 0x1f, 0xe1, 0x08, 0x0f, 0xb9, - 0x47, 0x8e, 0x47, 0x84, 0x0b, 0xfb, 0x29, 0xbc, 0xb2, 0x10, 0xe5, 0x21, 0x0b, 0x38, 0x41, 0x7b, - 0xb0, 0x18, 0xca, 0x88, 0x09, 0xaa, 0xa0, 0xb6, 0xd9, 0x2a, 0x3b, 0x59, 0x0d, 0x71, 0x94, 0xab, - 0xbd, 0x76, 0xf2, 0xab, 0x92, 0xf3, 0xb4, 0x63, 0x6f, 0xed, 0xf5, 0xc7, 0x4a, 0xce, 0xfe, 0x04, - 0xa0, 0x21, 0x33, 0xef, 0x93, 0x90, 0x71, 0x5f, 0x24, 0x2f, 0x22, 0x03, 0xae, 0xf7, 0x48, 0xc0, - 0x86, 0x32, 0xf3, 0x25, 0x4f, 0x1d, 0x90, 0x03, 0xd7, 0xd9, 0xf3, 0x80, 0x44, 0x66, 0x3e, 0x8e, - 0xb6, 0xcd, 0xef, 0x5f, 0x1b, 0x86, 0x6e, 0xca, 0xdd, 0x5e, 0x2f, 0x22, 0x9c, 0x1f, 0x88, 0xc8, - 0x0f, 0xa8, 0xa7, 0x64, 0xe8, 0x3e, 0x84, 0x67, 0x2d, 0x37, 0x0b, 0x12, 0x72, 0xc7, 0xd1, 0x8e, - 0xb8, 0xe7, 0x8e, 0x1a, 0xe7, 0x19, 0x29, 0x25, 0x9a, 0xc0, 0x9b, 0x73, 0xda, 0x5f, 0x00, 0xbc, - 0x7a, 0x0e, 0x53, 0xb7, 0xe0, 0x21, 0xdc, 0xe8, 0xe9, 0x98, 0x09, 0xaa, 0x85, 0xda, 0x66, 0xeb, - 0x46, 0x76, 0x13, 0xb4, 0xb3, 0x7d, 0x39, 0xee, 0xc2, 0xe7, 0xdf, 0x95, 0x8d, 0x34, 0x55, 0x9a, - 0x00, 0x3d, 0x58, 0xc0, 0xcd, 0x4b, 0xdc, 0x9b, 0xff, 0xc5, 0x55, 0x24, 0x0b, 0xbc, 0x5b, 0xf0, - 0xba, 0xc4, 0x7d, 0xc2, 0x04, 0x1e, 0x1c, 0x8c, 0xc2, 0x70, 0x30, 0x49, 0x46, 0xf9, 0x1e, 0x40, - 0x73, 0xf9, 0x4e, 0x57, 0x73, 0x0d, 0x16, 0xfb, 0xc4, 0xa7, 0x7d, 0x21, 0xdb, 0x5e, 0xf0, 0xf4, - 0x09, 0x75, 0x61, 0x31, 0x22, 0x7c, 0x34, 0x10, 0x66, 0x5e, 0xd6, 0xb8, 0xb5, 0x00, 0x95, 0xe0, - 0xdc, 0x63, 0x7e, 0xd0, 0x6e, 0xea, 0xfa, 0x6a, 0xd4, 0x17, 0xfd, 0x51, 0xc7, 0xe9, 0xb2, 0xa1, - 0xde, 0x5b, 0xfd, 0xd1, 0xe0, 0xbd, 0x23, 0x57, 0x4c, 0x42, 0xc2, 0xa5, 0x81, 0x7b, 0x3a, 0x75, - 0xeb, 0x5b, 0x01, 0xae, 0x4b, 0x32, 0xf4, 0x0a, 0xc0, 0xa2, 0x5a, 0x1a, 0x54, 0xcb, 0xee, 0xe6, - 0xf2, 0x8e, 0x96, 0x6e, 0xad, 0xa0, 0x54, 0x65, 0xda, 0xdb, 0x2f, 0x7f, 0xfc, 0x7d, 0x97, 0xb7, - 0x50, 0xd9, 0xcd, 0xfc, 0x3d, 0xa8, 0x0d, 0x45, 0x6f, 0x00, 0x4c, 0x87, 0x84, 0xea, 0x17, 0x64, - 0x3f, 0xb7, 0xbb, 0xa5, 0xdb, 0x2b, 0x69, 0x35, 0xcb, 0x8e, 0x64, 0xa9, 0x22, 0x2b, 0x9b, 0x25, - 0xdd, 0x8d, 0x0f, 0x00, 0x6e, 0xce, 0x8d, 0x0c, 0x35, 0x2e, 0x78, 0x64, 0x79, 0xec, 0x25, 0x67, - 0x55, 0xb9, 0xc6, 0xaa, 0x4b, 0xac, 0x6d, 0x64, 0x67, 0x63, 0x89, 0xd8, 0x72, 0xc8, 0xa5, 0xa7, - 0xbd, 0x7f, 0x32, 0xb5, 0xc0, 0xe9, 0xd4, 0x02, 0x7f, 0xa6, 0x16, 0x78, 0x3b, 0xb3, 0x72, 0xa7, - 0x33, 0x2b, 0xf7, 0x73, 0x66, 0xe5, 0x9e, 0xd5, 0xe7, 0x96, 0xa0, 0x49, 0x07, 0xb8, 0xc3, 0xdd, - 0x26, 0x6d, 0x74, 0xfb, 0xd8, 0x0f, 0xdc, 0x17, 0x69, 0x52, 0xb9, 0x0c, 0x9d, 0xa2, 0xfc, 0x03, - 0xba, 0xf3, 0x2f, 0x00, 0x00, 0xff, 0xff, 0x7f, 0x85, 0x56, 0x54, 0x77, 0x05, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - // Params queries all parameters of the savings module. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Deposits queries savings deposits. - Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, error) - // TotalSupply returns the total sum of all coins currently locked into the savings module. - TotalSupply(ctx context.Context, in *QueryTotalSupplyRequest, opts ...grpc.CallOption) (*QueryTotalSupplyResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { - out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, "/kava.savings.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, error) { - out := new(QueryDepositsResponse) - err := c.cc.Invoke(ctx, "/kava.savings.v1beta1.Query/Deposits", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalSupply(ctx context.Context, in *QueryTotalSupplyRequest, opts ...grpc.CallOption) (*QueryTotalSupplyResponse, error) { - out := new(QueryTotalSupplyResponse) - err := c.cc.Invoke(ctx, "/kava.savings.v1beta1.Query/TotalSupply", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries all parameters of the savings module. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Deposits queries savings deposits. - Deposits(context.Context, *QueryDepositsRequest) (*QueryDepositsResponse, error) - // TotalSupply returns the total sum of all coins currently locked into the savings module. - TotalSupply(context.Context, *QueryTotalSupplyRequest) (*QueryTotalSupplyResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") -} -func (*UnimplementedQueryServer) Deposits(ctx context.Context, req *QueryDepositsRequest) (*QueryDepositsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposits not implemented") -} -func (*UnimplementedQueryServer) TotalSupply(ctx context.Context, req *QueryTotalSupplyRequest) (*QueryTotalSupplyResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalSupply not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryParamsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Params(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.savings.v1beta1.Query/Params", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Deposits_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryDepositsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Deposits(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.savings.v1beta1.Query/Deposits", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Deposits(ctx, req.(*QueryDepositsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalSupply_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalSupplyRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalSupply(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.savings.v1beta1.Query/TotalSupply", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalSupply(ctx, req.(*QueryTotalSupplyRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.savings.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Deposits", - Handler: _Query_Deposits_Handler, - }, - { - MethodName: "TotalSupply", - Handler: _Query_TotalSupply_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/savings/v1beta1/query.proto", -} - -func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryDepositsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryDepositsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0x12 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDepositsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryDepositsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Deposits) > 0 { - for iNdEx := len(m.Deposits) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposits[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalSupplyRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryTotalSupplyRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalSupplyRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryTotalSupplyResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryTotalSupplyResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalSupplyResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Result) > 0 { - for iNdEx := len(m.Result) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Result[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if m.Height != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.Height)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryParamsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryDepositsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDepositsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Deposits) > 0 { - for _, e := range m.Deposits { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryTotalSupplyRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryTotalSupplyResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Height != 0 { - n += 1 + sovQuery(uint64(m.Height)) - } - if len(m.Result) > 0 { - for _, e := range m.Result { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDepositsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryDepositsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDepositsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryDepositsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposits", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Deposits = append(m.Deposits, Deposit{}) - if err := m.Deposits[len(m.Deposits)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTotalSupplyRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTotalSupplyRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalSupplyRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryTotalSupplyResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryTotalSupplyResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalSupplyResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Height", wireType) - } - m.Height = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Height |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Result = append(m.Result, types.Coin{}) - if err := m.Result[len(m.Result)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/savings/types/query.pb.gw.go b/x/savings/types/query.pb.gw.go deleted file mode 100644 index 8a59f3da..00000000 --- a/x/savings/types/query.pb.gw.go +++ /dev/null @@ -1,301 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/savings/v1beta1/query.proto - -/* -Package types is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package types - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join - -func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Params(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Deposits_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Deposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Deposits(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Deposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Deposits(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_TotalSupply_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalSupplyRequest - var metadata runtime.ServerMetadata - - msg, err := client.TotalSupply(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TotalSupply_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalSupplyRequest - var metadata runtime.ServerMetadata - - msg, err := server.TotalSupply(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Deposits_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Deposits_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Deposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalSupply_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_TotalSupply_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TotalSupply_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Deposits_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Deposits_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Deposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalSupply_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_TotalSupply_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_TotalSupply_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "savings", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Deposits_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "savings", "v1beta1", "deposits"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TotalSupply_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "savings", "v1beta1", "total_supply"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Deposits_0 = runtime.ForwardResponseMessage - - forward_Query_TotalSupply_0 = runtime.ForwardResponseMessage -) diff --git a/x/savings/types/store.pb.go b/x/savings/types/store.pb.go deleted file mode 100644 index 1f1ec43a..00000000 --- a/x/savings/types/store.pb.go +++ /dev/null @@ -1,547 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/savings/v1beta1/store.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// Params defines the parameters for the savings module. -type Params struct { - SupportedDenoms []string `protobuf:"bytes,1,rep,name=supported_denoms,json=supportedDenoms,proto3" json:"supported_denoms,omitempty"` -} - -func (m *Params) Reset() { *m = Params{} } -func (m *Params) String() string { return proto.CompactTextString(m) } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_f7110366fa182786, []int{0} -} -func (m *Params) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Params.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Params) XXX_Merge(src proto.Message) { - xxx_messageInfo_Params.Merge(m, src) -} -func (m *Params) XXX_Size() int { - return m.Size() -} -func (m *Params) XXX_DiscardUnknown() { - xxx_messageInfo_Params.DiscardUnknown(m) -} - -var xxx_messageInfo_Params proto.InternalMessageInfo - -// Deposit defines an amount of coins deposited into a savings module account. -type Deposit struct { - Depositor github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=depositor,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"depositor,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *Deposit) Reset() { *m = Deposit{} } -func (m *Deposit) String() string { return proto.CompactTextString(m) } -func (*Deposit) ProtoMessage() {} -func (*Deposit) Descriptor() ([]byte, []int) { - return fileDescriptor_f7110366fa182786, []int{1} -} -func (m *Deposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Deposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Deposit.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Deposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_Deposit.Merge(m, src) -} -func (m *Deposit) XXX_Size() int { - return m.Size() -} -func (m *Deposit) XXX_DiscardUnknown() { - xxx_messageInfo_Deposit.DiscardUnknown(m) -} - -var xxx_messageInfo_Deposit proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Params)(nil), "kava.savings.v1beta1.Params") - proto.RegisterType((*Deposit)(nil), "kava.savings.v1beta1.Deposit") -} - -func init() { proto.RegisterFile("kava/savings/v1beta1/store.proto", fileDescriptor_f7110366fa182786) } - -var fileDescriptor_f7110366fa182786 = []byte{ - // 341 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x51, 0xc1, 0x4e, 0xea, 0x40, - 0x14, 0x6d, 0x1f, 0x09, 0x2f, 0xf4, 0x2d, 0x9e, 0xa9, 0x2c, 0x80, 0xc5, 0xd0, 0xb0, 0xaa, 0x26, - 0x9d, 0x01, 0xf9, 0x02, 0x2a, 0x0b, 0x96, 0x86, 0xa5, 0x1b, 0x32, 0x9d, 0x8e, 0xa5, 0xc1, 0xf6, - 0x36, 0xbd, 0x03, 0x91, 0xbf, 0xf0, 0x3b, 0x5c, 0xfb, 0x11, 0x2c, 0x89, 0x0b, 0xe3, 0x0a, 0x15, - 0xfe, 0xc2, 0x95, 0x69, 0x3b, 0xa2, 0x4b, 0x57, 0x73, 0xef, 0xb9, 0xe7, 0x9c, 0x9c, 0x9c, 0xb1, - 0x9c, 0x05, 0x5f, 0x71, 0x86, 0x7c, 0x15, 0xa7, 0x11, 0xb2, 0xd5, 0x20, 0x90, 0x8a, 0x0f, 0x18, - 0x2a, 0xc8, 0x25, 0xcd, 0x72, 0x50, 0x60, 0x37, 0x0b, 0x06, 0xd5, 0x0c, 0xaa, 0x19, 0x1d, 0x22, - 0x00, 0x13, 0x40, 0x16, 0x70, 0x94, 0x47, 0x99, 0x80, 0x38, 0xad, 0x54, 0x9d, 0x76, 0x75, 0x9f, - 0x95, 0x1b, 0xab, 0x16, 0x7d, 0x6a, 0x46, 0x10, 0x41, 0x85, 0x17, 0x53, 0x85, 0xf6, 0x86, 0x56, - 0xfd, 0x8a, 0xe7, 0x3c, 0x41, 0xfb, 0xcc, 0x3a, 0xc1, 0x65, 0x96, 0x41, 0xae, 0x64, 0x38, 0x0b, - 0x65, 0x0a, 0x09, 0xb6, 0x4c, 0xa7, 0xe6, 0x36, 0xa6, 0xff, 0x8f, 0xf8, 0xb8, 0x84, 0x7b, 0xcf, - 0xa6, 0xf5, 0x77, 0x2c, 0x33, 0xc0, 0x58, 0xd9, 0x37, 0x56, 0x23, 0xac, 0x46, 0xc8, 0x5b, 0xa6, - 0x63, 0xba, 0x0d, 0x7f, 0xf2, 0xb1, 0xeb, 0x7a, 0x51, 0xac, 0xe6, 0xcb, 0x80, 0x0a, 0x48, 0x74, - 0x0c, 0xfd, 0x78, 0x18, 0x2e, 0x98, 0x5a, 0x67, 0x12, 0xe9, 0x48, 0x88, 0x51, 0x18, 0xe6, 0x12, - 0xf1, 0xe9, 0xd1, 0x3b, 0xd5, 0x61, 0x35, 0xe2, 0xaf, 0x95, 0xc4, 0xe9, 0xb7, 0xb5, 0x2d, 0xac, - 0x3a, 0x4f, 0x60, 0x99, 0xaa, 0xd6, 0x1f, 0xa7, 0xe6, 0xfe, 0xbb, 0x68, 0x53, 0x2d, 0x28, 0xaa, - 0xf8, 0xea, 0x87, 0x5e, 0x42, 0x9c, 0xfa, 0xfd, 0xcd, 0xae, 0x6b, 0x3c, 0xbc, 0x76, 0xdd, 0x5f, - 0x64, 0x28, 0x04, 0x38, 0xd5, 0xd6, 0xfe, 0x64, 0xf3, 0x4e, 0x8c, 0xcd, 0x9e, 0x98, 0xdb, 0x3d, - 0x31, 0xdf, 0xf6, 0xc4, 0xbc, 0x3f, 0x10, 0x63, 0x7b, 0x20, 0xc6, 0xcb, 0x81, 0x18, 0xd7, 0xe7, - 0x3f, 0xfc, 0xfa, 0xd1, 0x2d, 0x0f, 0x90, 0xf5, 0x23, 0x4f, 0xcc, 0x79, 0x9c, 0xb2, 0xbb, 0xe3, - 0x67, 0x96, 0xbe, 0x41, 0xbd, 0xac, 0x77, 0xf8, 0x19, 0x00, 0x00, 0xff, 0xff, 0x69, 0xf4, 0xaf, - 0xe1, 0xe9, 0x01, 0x00, 0x00, -} - -func (m *Params) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Params) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.SupportedDenoms) > 0 { - for iNdEx := len(m.SupportedDenoms) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.SupportedDenoms[iNdEx]) - copy(dAtA[i:], m.SupportedDenoms[iNdEx]) - i = encodeVarintStore(dAtA, i, uint64(len(m.SupportedDenoms[iNdEx]))) - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *Deposit) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Deposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Deposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintStore(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintStore(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintStore(dAtA []byte, offset int, v uint64) int { - offset -= sovStore(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.SupportedDenoms) > 0 { - for _, s := range m.SupportedDenoms { - l = len(s) - n += 1 + l + sovStore(uint64(l)) - } - } - return n -} - -func (m *Deposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovStore(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovStore(uint64(l)) - } - } - return n -} - -func sovStore(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozStore(x uint64) (n int) { - return sovStore(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Params) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Params: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SupportedDenoms", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthStore - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthStore - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SupportedDenoms = append(m.SupportedDenoms, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipStore(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthStore - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Deposit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Deposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Deposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthStore - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthStore - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = github_com_cosmos_cosmos_sdk_types.AccAddress(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStore - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthStore - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthStore - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipStore(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthStore - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipStore(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowStore - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowStore - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowStore - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthStore - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupStore - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthStore - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthStore = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowStore = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupStore = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/savings/types/tx.pb.go b/x/savings/types/tx.pb.go deleted file mode 100644 index e1492ec0..00000000 --- a/x/savings/types/tx.pb.go +++ /dev/null @@ -1,993 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/savings/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// MsgDeposit defines the Msg/Deposit request type. -type MsgDeposit struct { - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *MsgDeposit) Reset() { *m = MsgDeposit{} } -func (m *MsgDeposit) String() string { return proto.CompactTextString(m) } -func (*MsgDeposit) ProtoMessage() {} -func (*MsgDeposit) Descriptor() ([]byte, []int) { - return fileDescriptor_c0bf8679b144267a, []int{0} -} -func (m *MsgDeposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDeposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDeposit.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgDeposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDeposit.Merge(m, src) -} -func (m *MsgDeposit) XXX_Size() int { - return m.Size() -} -func (m *MsgDeposit) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDeposit.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDeposit proto.InternalMessageInfo - -func (m *MsgDeposit) GetDepositor() string { - if m != nil { - return m.Depositor - } - return "" -} - -func (m *MsgDeposit) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -// MsgDepositResponse defines the Msg/Deposit response type. -type MsgDepositResponse struct { -} - -func (m *MsgDepositResponse) Reset() { *m = MsgDepositResponse{} } -func (m *MsgDepositResponse) String() string { return proto.CompactTextString(m) } -func (*MsgDepositResponse) ProtoMessage() {} -func (*MsgDepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_c0bf8679b144267a, []int{1} -} -func (m *MsgDepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDepositResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgDepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDepositResponse.Merge(m, src) -} -func (m *MsgDepositResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgDepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDepositResponse proto.InternalMessageInfo - -// MsgWithdraw defines the Msg/Withdraw request type. -type MsgWithdraw struct { - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *MsgWithdraw) Reset() { *m = MsgWithdraw{} } -func (m *MsgWithdraw) String() string { return proto.CompactTextString(m) } -func (*MsgWithdraw) ProtoMessage() {} -func (*MsgWithdraw) Descriptor() ([]byte, []int) { - return fileDescriptor_c0bf8679b144267a, []int{2} -} -func (m *MsgWithdraw) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdraw) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdraw.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgWithdraw) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdraw.Merge(m, src) -} -func (m *MsgWithdraw) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdraw) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdraw.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdraw proto.InternalMessageInfo - -func (m *MsgWithdraw) GetDepositor() string { - if m != nil { - return m.Depositor - } - return "" -} - -func (m *MsgWithdraw) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -type MsgWithdrawResponse struct { -} - -func (m *MsgWithdrawResponse) Reset() { *m = MsgWithdrawResponse{} } -func (m *MsgWithdrawResponse) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawResponse) ProtoMessage() {} -func (*MsgWithdrawResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_c0bf8679b144267a, []int{3} -} -func (m *MsgWithdrawResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgWithdrawResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawResponse.Merge(m, src) -} -func (m *MsgWithdrawResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgDeposit)(nil), "kava.savings.v1beta1.MsgDeposit") - proto.RegisterType((*MsgDepositResponse)(nil), "kava.savings.v1beta1.MsgDepositResponse") - proto.RegisterType((*MsgWithdraw)(nil), "kava.savings.v1beta1.MsgWithdraw") - proto.RegisterType((*MsgWithdrawResponse)(nil), "kava.savings.v1beta1.MsgWithdrawResponse") -} - -func init() { proto.RegisterFile("kava/savings/v1beta1/tx.proto", fileDescriptor_c0bf8679b144267a) } - -var fileDescriptor_c0bf8679b144267a = []byte{ - // 374 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x52, 0x3d, 0x6f, 0xe2, 0x30, - 0x18, 0x8e, 0x0f, 0x89, 0x3b, 0xcc, 0x96, 0xcb, 0x49, 0x10, 0xe9, 0x02, 0xc7, 0x94, 0x3b, 0x09, - 0x1b, 0x38, 0xa9, 0x7b, 0x29, 0x2b, 0x0b, 0x55, 0xd5, 0xaa, 0x4b, 0xe5, 0x7c, 0xc8, 0x58, 0x94, - 0x38, 0xca, 0x6b, 0x28, 0xfd, 0x17, 0xfd, 0x1b, 0x65, 0xae, 0xfa, 0x1b, 0x18, 0x51, 0xa7, 0x4e, - 0x6d, 0x05, 0x7f, 0xa4, 0x22, 0x71, 0x80, 0xa1, 0x15, 0x6b, 0xa7, 0xd8, 0x7e, 0x3e, 0xf4, 0xbc, - 0x4f, 0x5e, 0xfc, 0x7b, 0xc4, 0xa6, 0x8c, 0x02, 0x9b, 0x8a, 0x88, 0x03, 0x9d, 0xb6, 0xbd, 0x50, - 0xb1, 0x36, 0x55, 0x33, 0x12, 0x27, 0x52, 0x49, 0xd3, 0xda, 0xc0, 0x44, 0xc3, 0x44, 0xc3, 0xb6, - 0xe3, 0x4b, 0x18, 0x4b, 0xa0, 0x1e, 0x83, 0x70, 0xab, 0xf1, 0xa5, 0x88, 0x32, 0x95, 0x5d, 0xcd, - 0xf0, 0xab, 0xf4, 0x46, 0xb3, 0x8b, 0x86, 0x2c, 0x2e, 0xb9, 0xcc, 0xde, 0x37, 0xa7, 0xec, 0xb5, - 0x71, 0x8f, 0x30, 0xee, 0x03, 0xef, 0x85, 0xb1, 0x04, 0xa1, 0xcc, 0x23, 0x5c, 0x0a, 0xb2, 0xa3, - 0x4c, 0x2a, 0xa8, 0x8e, 0xdc, 0x52, 0xb7, 0xf2, 0xf4, 0xd0, 0xb4, 0xb4, 0xd3, 0x71, 0x10, 0x24, - 0x21, 0xc0, 0xa9, 0x4a, 0x44, 0xc4, 0x07, 0x3b, 0xaa, 0xe9, 0xe3, 0x22, 0x1b, 0xcb, 0x49, 0xa4, - 0x2a, 0xdf, 0xea, 0x05, 0xb7, 0xdc, 0xa9, 0x12, 0xad, 0xd8, 0x04, 0xcd, 0xd3, 0x93, 0x13, 0x29, - 0xa2, 0x6e, 0x6b, 0xf1, 0x52, 0x33, 0xe6, 0xaf, 0x35, 0x97, 0x0b, 0x35, 0x9c, 0x78, 0xc4, 0x97, - 0x63, 0x1d, 0x54, 0x7f, 0x9a, 0x10, 0x8c, 0xa8, 0xba, 0x8d, 0x43, 0x48, 0x05, 0x30, 0xd0, 0xd6, - 0x0d, 0x0b, 0x9b, 0xbb, 0xa8, 0x83, 0x10, 0x62, 0x19, 0x41, 0xd8, 0x98, 0x23, 0x5c, 0xee, 0x03, - 0x3f, 0x17, 0x6a, 0x18, 0x24, 0xec, 0xe6, 0x6b, 0x8f, 0xf0, 0x0b, 0xff, 0xdc, 0xcb, 0x9a, 0xcf, - 0xd0, 0x79, 0x44, 0xb8, 0xd0, 0x07, 0x6e, 0x9e, 0xe1, 0xef, 0xf9, 0x9f, 0xa8, 0x93, 0x8f, 0x16, - 0x80, 0xec, 0x0a, 0xb0, 0xdd, 0x43, 0x8c, 0xdc, 0xde, 0xbc, 0xc0, 0x3f, 0xb6, 0xf5, 0xfc, 0xf9, - 0x54, 0x95, 0x53, 0xec, 0xbf, 0x07, 0x29, 0xb9, 0x73, 0xb7, 0xb7, 0x58, 0x39, 0x68, 0xb9, 0x72, - 0xd0, 0xdb, 0xca, 0x41, 0x77, 0x6b, 0xc7, 0x58, 0xae, 0x1d, 0xe3, 0x79, 0xed, 0x18, 0x97, 0xff, - 0xf6, 0xba, 0x69, 0xf1, 0x6b, 0xe6, 0x01, 0x6d, 0xf1, 0xa6, 0x3f, 0x64, 0x22, 0xa2, 0xb3, 0xed, - 0xda, 0xa7, 0x1d, 0x79, 0xc5, 0x74, 0x17, 0xff, 0xbf, 0x07, 0x00, 0x00, 0xff, 0xff, 0xc5, 0xcb, - 0x03, 0x6a, 0x13, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - // Deposit defines a method for depositing funds to the savings module account - Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) - // Withdraw defines a method for withdrawing funds to the savings module account - Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) { - out := new(MsgDepositResponse) - err := c.cc.Invoke(ctx, "/kava.savings.v1beta1.Msg/Deposit", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) { - out := new(MsgWithdrawResponse) - err := c.cc.Invoke(ctx, "/kava.savings.v1beta1.Msg/Withdraw", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // Deposit defines a method for depositing funds to the savings module account - Deposit(context.Context, *MsgDeposit) (*MsgDepositResponse, error) - // Withdraw defines a method for withdrawing funds to the savings module account - Withdraw(context.Context, *MsgWithdraw) (*MsgWithdrawResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Deposit(ctx context.Context, req *MsgDeposit) (*MsgDepositResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposit not implemented") -} -func (*UnimplementedMsgServer) Withdraw(ctx context.Context, req *MsgWithdraw) (*MsgWithdrawResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Withdraw not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Deposit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgDeposit) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Deposit(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.savings.v1beta1.Msg/Deposit", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Deposit(ctx, req.(*MsgDeposit)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Withdraw_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgWithdraw) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Withdraw(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.savings.v1beta1.Msg/Withdraw", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Withdraw(ctx, req.(*MsgWithdraw)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.savings.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Deposit", - Handler: _Msg_Deposit_Handler, - }, - { - MethodName: "Withdraw", - Handler: _Msg_Withdraw_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/savings/v1beta1/tx.proto", -} - -func (m *MsgDeposit) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgDeposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDeposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgDepositResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgDepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgWithdraw) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgWithdraw) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdraw) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgWithdrawResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgDeposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgDepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgWithdraw) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgWithdrawResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgDeposit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDeposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDeposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDepositResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdraw) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdraw: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdraw: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/swap/client/cli/query.go b/x/swap/client/cli/query.go deleted file mode 100644 index e890580f..00000000 --- a/x/swap/client/cli/query.go +++ /dev/null @@ -1,154 +0,0 @@ -package cli - -import ( - "context" - "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - - "github.com/0glabs/0g-chain/x/swap/types" -) - -// flags for cli queries -const ( - flagOwner = "owner" - flagPool = "pool" -) - -// GetQueryCmd returns the cli query commands for the module -func GetQueryCmd(queryRoute string) *cobra.Command { - swapQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the swap module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - queryParamsCmd(queryRoute), - queryDepositsCmd(queryRoute), - queryPoolsCmd(queryRoute), - } - - for _, cmd := range cmds { - flags.AddQueryFlagsToCmd(cmd) - } - - swapQueryCmd.AddCommand(cmds...) - - return swapQueryCmd -} - -func queryParamsCmd(queryRoute string) *cobra.Command { - return &cobra.Command{ - Use: "params", - Short: "get the swap module parameters", - Long: "Get the current global swap module parameters.", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.Params(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - } -} - -func queryDepositsCmd(queryRoute string) *cobra.Command { - cmd := &cobra.Command{ - Use: "deposits", - Short: "get liquidity provider deposits", - Long: strings.TrimSpace(`get liquidity provider deposits: - Example: - $ kvcli q swap deposits --pool bnb:usdx - $ kvcli q swap deposits --owner kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny - $ kvcli q swap deposits --pool bnb:usdx --owner kava1l0xsq2z7gqd7yly0g40y5836g0appumark77ny - $ kvcli q swap deposits --page=2 --limit=100 - `, - ), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - bechOwnerAddr, err := cmd.Flags().GetString(flagOwner) - if err != nil { - return err - } - pool, err := cmd.Flags().GetString(flagPool) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - params := types.QueryDepositsRequest{ - Owner: bechOwnerAddr, - PoolId: pool, - Pagination: pageReq, - } - res, err := queryClient.Deposits(context.Background(), ¶ms) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddPaginationFlagsToCmd(cmd, "deposits") - - cmd.Flags().String(flagPool, "", "pool name") - cmd.Flags().String(flagOwner, "", "owner, also known as a liquidity provider") - - return cmd -} - -func queryPoolsCmd(queryRoute string) *cobra.Command { - cmd := &cobra.Command{ - Use: "pools", - Short: "get statistics for all pools", - Long: strings.TrimSpace(`get statistics for all liquidity pools: - Example: - $ kvcli q swap pools`, - ), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - params := types.QueryPoolsRequest{} - res, err := queryClient.Pools(context.Background(), ¶ms) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - return cmd -} diff --git a/x/swap/client/cli/tx.go b/x/swap/client/cli/tx.go deleted file mode 100644 index 72a46925..00000000 --- a/x/swap/client/cli/tx.go +++ /dev/null @@ -1,228 +0,0 @@ -package cli - -import ( - "fmt" - "strconv" - - "github.com/spf13/cobra" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - - "github.com/0glabs/0g-chain/x/swap/types" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - swapTxCmd := &cobra.Command{ - Use: types.ModuleName, - Short: fmt.Sprintf("%s transactions subcommands", types.ModuleName), - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - getCmdDeposit(), - getCmdWithdraw(), - getCmdSwapExactForTokens(), - getCmdSwapForExactTokens(), - } - - for _, cmd := range cmds { - flags.AddTxFlagsToCmd(cmd) - } - - swapTxCmd.AddCommand(cmds...) - - return swapTxCmd -} - -func getCmdDeposit() *cobra.Command { - return &cobra.Command{ - Use: "deposit [tokenA] [tokenB] [slippage] [deadline]", - Short: "deposit coins to a swap liquidity pool", - Example: fmt.Sprintf( - `%s tx %s deposit 10000000ukava 10000000usdx 0.01 1624224736 --from `, - version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - tokenA, err := sdk.ParseCoinNormalized(args[0]) - if err != nil { - return err - } - - tokenB, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - slippage, err := sdk.NewDecFromStr(args[2]) - if err != nil { - return err - } - - deadline, err := strconv.ParseInt(args[3], 10, 64) - if err != nil { - return err - } - - signer := clientCtx.GetFromAddress() - msg := types.NewMsgDeposit(signer.String(), tokenA, tokenB, slippage, deadline) - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} - -func getCmdWithdraw() *cobra.Command { - return &cobra.Command{ - Use: "withdraw [shares] [minCoinA] [minCoinB] [deadline]", - Short: "withdraw coins from a swap liquidity pool", - Example: fmt.Sprintf( - `%s tx %s withdraw 153000 10000000ukava 20000000usdx 176293740 --from `, - version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - numShares, err := strconv.ParseInt(args[0], 10, 64) - if err != nil { - return err - } - shares := sdkmath.NewInt(numShares) - - minTokenA, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - minTokenB, err := sdk.ParseCoinNormalized(args[2]) - if err != nil { - return err - } - - deadline, err := strconv.ParseInt(args[3], 10, 64) - if err != nil { - return err - } - - fromAddr := clientCtx.GetFromAddress() - msg := types.NewMsgWithdraw(fromAddr.String(), shares, minTokenA, minTokenB, deadline) - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} - -func getCmdSwapExactForTokens() *cobra.Command { - return &cobra.Command{ - Use: "swap-exact-for-tokens [exactCoinA] [coinB] [slippage] [deadline]", - Short: "swap an exact amount of token a for token b", - Example: fmt.Sprintf( - `%s tx %s swap-exact-for-tokens 1000000ukava 5000000usdx 0.01 1624224736 --from `, - version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - exactTokenA, err := sdk.ParseCoinNormalized(args[0]) - if err != nil { - return err - } - - tokenB, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - slippage, err := sdk.NewDecFromStr(args[2]) - if err != nil { - return err - } - - deadline, err := strconv.ParseInt(args[3], 10, 64) - if err != nil { - return err - } - - fromAddr := clientCtx.GetFromAddress() - msg := types.NewMsgSwapExactForTokens(fromAddr.String(), exactTokenA, tokenB, slippage, deadline) - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} - -func getCmdSwapForExactTokens() *cobra.Command { - return &cobra.Command{ - Use: "swap-for-exact-tokens [coinA] [exactCoinB] [slippage] [deadline]", - Short: "swap token a for exact amount of token b", - Example: fmt.Sprintf( - `%s tx %s swap-for-exact-tokens 1000000ukava 5000000usdx 0.01 1624224736 --from `, - version.AppName, types.ModuleName, - ), - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - tokenA, err := sdk.ParseCoinNormalized(args[0]) - if err != nil { - return err - } - - exactTokenB, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - slippage, err := sdk.NewDecFromStr(args[2]) - if err != nil { - return err - } - - deadline, err := strconv.ParseInt(args[3], 10, 64) - if err != nil { - return err - } - - fromAddr := clientCtx.GetFromAddress() - msg := types.NewMsgSwapForExactTokens(fromAddr.String(), tokenA, exactTokenB, slippage, deadline) - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } -} diff --git a/x/swap/genesis.go b/x/swap/genesis.go deleted file mode 100644 index 74693479..00000000 --- a/x/swap/genesis.go +++ /dev/null @@ -1,34 +0,0 @@ -package swap - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/swap/keeper" - "github.com/0glabs/0g-chain/x/swap/types" -) - -// InitGenesis initializes story state from genesis file -func InitGenesis(ctx sdk.Context, k keeper.Keeper, gs types.GenesisState) { - if err := gs.Validate(); err != nil { - panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err)) - } - - k.SetParams(ctx, gs.Params) - for _, pr := range gs.PoolRecords { - k.SetPool(ctx, pr) - } - for _, sh := range gs.ShareRecords { - k.SetDepositorShares(ctx, sh) - } -} - -// ExportGenesis exports the genesis state -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { - params := k.GetParams(ctx) - pools := k.GetAllPools(ctx) - shares := k.GetAllDepositorShares(ctx) - - return types.NewGenesisState(params, pools, shares) -} diff --git a/x/swap/genesis_test.go b/x/swap/genesis_test.go deleted file mode 100644 index 20b7e7d1..00000000 --- a/x/swap/genesis_test.go +++ /dev/null @@ -1,151 +0,0 @@ -package swap_test - -import ( - "testing" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/swap" - "github.com/0glabs/0g-chain/x/swap/testutil" - "github.com/0glabs/0g-chain/x/swap/types" - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type genesisTestSuite struct { - testutil.Suite -} - -func (suite *genesisTestSuite) Test_InitGenesis_ValidationPanic() { - invalidState := types.NewGenesisState( - types.Params{ - SwapFee: sdk.NewDec(-1), - }, - types.PoolRecords{}, - types.ShareRecords{}, - ) - - suite.Panics(func() { - swap.InitGenesis(suite.Ctx, suite.Keeper, invalidState) - }, "expected init genesis to panic with invalid state") -} - -func (suite *genesisTestSuite) Test_InitAndExportGenesis() { - depositor_1, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - suite.Require().NoError(err) - depositor_2, err := sdk.AccAddressFromBech32("kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea") - suite.Require().NoError(err) - - // slices are sorted by key as stored in the data store, so init and export can be compared with equal - state := types.NewGenesisState( - types.Params{ - AllowedPools: types.AllowedPools{types.NewAllowedPool("ukava", "usdx")}, - SwapFee: sdk.MustNewDecFromStr("0.00255"), - }, - types.PoolRecords{ - types.NewPoolRecord(sdk.NewCoins(sdk.NewCoin("hard", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(2e6))), sdkmath.NewInt(1e6)), - types.NewPoolRecord(sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6))), sdkmath.NewInt(3e6)), - }, - types.ShareRecords{ - types.NewShareRecord(depositor_2, types.PoolID("hard", "usdx"), sdkmath.NewInt(1e6)), - types.NewShareRecord(depositor_1, types.PoolID("ukava", "usdx"), sdkmath.NewInt(3e6)), - }, - ) - - swap.InitGenesis(suite.Ctx, suite.Keeper, state) - suite.Equal(state.Params, suite.Keeper.GetParams(suite.Ctx)) - - poolRecord1, _ := suite.Keeper.GetPool(suite.Ctx, types.PoolID("hard", "usdx")) - suite.Equal(state.PoolRecords[0], poolRecord1) - poolRecord2, _ := suite.Keeper.GetPool(suite.Ctx, types.PoolID("ukava", "usdx")) - suite.Equal(state.PoolRecords[1], poolRecord2) - - shareRecord1, _ := suite.Keeper.GetDepositorShares(suite.Ctx, depositor_2, types.PoolID("hard", "usdx")) - suite.Equal(state.ShareRecords[0], shareRecord1) - shareRecord2, _ := suite.Keeper.GetDepositorShares(suite.Ctx, depositor_1, types.PoolID("ukava", "usdx")) - suite.Equal(state.ShareRecords[1], shareRecord2) - - exportedState := swap.ExportGenesis(suite.Ctx, suite.Keeper) - suite.Equal(state, exportedState) -} - -func (suite *genesisTestSuite) Test_Marshall() { - depositor_1, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - suite.Require().NoError(err) - depositor_2, err := sdk.AccAddressFromBech32("kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea") - suite.Require().NoError(err) - - // slices are sorted by key as stored in the data store, so init and export can be compared with equal - state := types.NewGenesisState( - types.Params{ - AllowedPools: types.AllowedPools{types.NewAllowedPool("ukava", "usdx")}, - SwapFee: sdk.MustNewDecFromStr("0.00255"), - }, - types.PoolRecords{ - types.NewPoolRecord(sdk.NewCoins(sdk.NewCoin("hard", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(2e6))), sdkmath.NewInt(1e6)), - types.NewPoolRecord(sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6))), sdkmath.NewInt(3e6)), - }, - types.ShareRecords{ - types.NewShareRecord(depositor_2, types.PoolID("hard", "usdx"), sdkmath.NewInt(1e6)), - types.NewShareRecord(depositor_1, types.PoolID("ukava", "usdx"), sdkmath.NewInt(3e6)), - }, - ) - - encodingCfg := app.MakeEncodingConfig() - cdc := encodingCfg.Marshaler - - bz, err := cdc.Marshal(&state) - suite.Require().NoError(err, "expected genesis state to marshal without error") - - var decodedState types.GenesisState - err = cdc.Unmarshal(bz, &decodedState) - suite.Require().NoError(err, "expected genesis state to unmarshal without error") - - suite.Equal(state, decodedState) -} - -func (suite *genesisTestSuite) Test_LegacyJSONConversion() { - depositor_1, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - suite.Require().NoError(err) - depositor_2, err := sdk.AccAddressFromBech32("kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea") - suite.Require().NoError(err) - - // slices are sorted by key as stored in the data store, so init and export can be compared with equal - state := types.NewGenesisState( - types.Params{ - AllowedPools: types.AllowedPools{types.NewAllowedPool("ukava", "usdx")}, - SwapFee: sdk.MustNewDecFromStr("0.00255"), - }, - types.PoolRecords{ - types.NewPoolRecord(sdk.NewCoins(sdk.NewCoin("hard", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(2e6))), sdkmath.NewInt(1e6)), - types.NewPoolRecord(sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6))), sdkmath.NewInt(3e6)), - }, - types.ShareRecords{ - types.NewShareRecord(depositor_2, types.PoolID("hard", "usdx"), sdkmath.NewInt(1e6)), - types.NewShareRecord(depositor_1, types.PoolID("ukava", "usdx"), sdkmath.NewInt(3e6)), - }, - ) - - encodingCfg := app.MakeEncodingConfig() - cdc := encodingCfg.Marshaler - legacyCdc := encodingCfg.Amino - - protoJson, err := cdc.MarshalJSON(&state) - suite.Require().NoError(err, "expected genesis state to marshal amino json without error") - - aminoJson, err := legacyCdc.MarshalJSON(&state) - suite.Require().NoError(err, "expected genesis state to marshal amino json without error") - - suite.JSONEq(string(protoJson), string(aminoJson), "expected json outputs to be equal") - - var importedState types.GenesisState - err = cdc.UnmarshalJSON(aminoJson, &importedState) - suite.Require().NoError(err, "expected amino json to unmarshall to proto without error") - - suite.Equal(state, importedState, "expected genesis state to be equal") -} - -func TestGenesisTestSuite(t *testing.T) { - suite.Run(t, new(genesisTestSuite)) -} diff --git a/x/swap/keeper/deposit.go b/x/swap/keeper/deposit.go deleted file mode 100644 index aab54b7d..00000000 --- a/x/swap/keeper/deposit.go +++ /dev/null @@ -1,139 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/swap/types" -) - -// Deposit creates a new pool or adds liquidity to an existing pool. For a pool to be created, a pool -// for the coin denominations must not exist yet, and it must be allowed by the swap module parameters. -// -// When adding liquidity to an existing pool, the provided coins are considered to be the desired deposit -// amount, and the actual deposited coins may be less than or equal to the provided coins. A deposit -// will never be exceed the coinA and coinB amounts. -// -// The slippage is calculated using both the price and inverse price of the provided coinA and coinB. -// Since adding liquidity is not directional, like a swap would be, using both the price (coinB/coinA), -// and the inverse price (coinA/coinB), protects the depositor from a large deviation in their deposit. -// -// The amount deposited may only change by B' < B or A' < A -- either B depreciates, or A depreciates. -// Therefore, slippage can be written as a function of this depreciation d. Where the new price is -// B*(1-d)/A or A*(1-d)/B, and the inverse of each, and is A/(B*(1-d)) and B/(A*(1-d)) -// respectively. -// -// Since 1/(1-d) >= (1-d) for d <= 1, the maximum slippage is always in the appreciating price -// A/(B*(1-d)) and B/(A*(1-d)). In other words, when the price of an asset depreciates, the -// inverse price -- or the price of the other pool asset, appreciates by a larger amount. -// It's this percent change we calculate and compare to the slippage limit provided. -// -// For example, if we have a pool with 100e6 ukava and 400e6 usdx. The ukava price is 4 usdx and the -// usdx price is 0.25 ukava. If a depositor adds liquidity of 4e6 ukava and 14e6 usdx, a kava price of -// 3.50 usdx and a usdx price of 0.29 ukava. This is a -12.5% slippage is the ukava price, and a 14.3% -// slippage in the usdx price. -// -// These slippages can be calculated by S_B = ((A/B')/(A/B) - 1) and S_A ((B/A')/(B/A) - 1), simplifying to -// S_B = (A/A' - 1), and S_B = (B/B' - 1). An error is returned when max(S_A, S_B) > slippageLimit. -func (k Keeper) Deposit(ctx sdk.Context, depositor sdk.AccAddress, coinA sdk.Coin, coinB sdk.Coin, slippageLimit sdk.Dec) error { - desiredAmount := sdk.NewCoins(coinA, coinB) - - poolID := types.PoolIDFromCoins(desiredAmount) - poolRecord, found := k.GetPool(ctx, poolID) - - var ( - pool *types.DenominatedPool - depositAmount sdk.Coins - shares sdkmath.Int - err error - ) - if found { - pool, depositAmount, shares, err = k.addLiquidityToPool(ctx, poolRecord, depositor, desiredAmount) - } else { - pool, depositAmount, shares, err = k.initializePool(ctx, poolID, depositor, desiredAmount) - } - if err != nil { - return err - } - - if depositAmount.AmountOf(coinA.Denom).IsZero() || depositAmount.AmountOf(coinB.Denom).IsZero() { - return errorsmod.Wrap(types.ErrInsufficientLiquidity, "deposit must be increased") - } - - if shares.IsZero() { - return errorsmod.Wrap(types.ErrInsufficientLiquidity, "deposit must be increased") - } - - maxPercentPriceChange := sdk.MaxDec( - sdk.NewDecFromInt(desiredAmount.AmountOf(coinA.Denom)).Quo(sdk.NewDecFromInt(depositAmount.AmountOf(coinA.Denom))), - sdk.NewDecFromInt(desiredAmount.AmountOf(coinB.Denom)).Quo(sdk.NewDecFromInt(depositAmount.AmountOf(coinB.Denom))), - ) - slippage := maxPercentPriceChange.Sub(sdk.OneDec()) - - if slippage.GT(slippageLimit) { - return errorsmod.Wrapf(types.ErrSlippageExceeded, "slippage %s > limit %s", slippage, slippageLimit) - } - - k.updatePool(ctx, poolID, pool) - if shareRecord, hasExistingShares := k.GetDepositorShares(ctx, depositor, poolID); hasExistingShares { - k.BeforePoolDepositModified(ctx, poolID, depositor, shareRecord.SharesOwned) - k.updateDepositorShares(ctx, depositor, poolID, shareRecord.SharesOwned.Add(shares)) - } else { - k.updateDepositorShares(ctx, depositor, poolID, shares) - k.AfterPoolDepositCreated(ctx, poolID, depositor, shares) - } - - err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, depositor, types.ModuleAccountName, depositAmount) - if err != nil { - return err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeSwapDeposit, - sdk.NewAttribute(types.AttributeKeyPoolID, poolID), - sdk.NewAttribute(types.AttributeKeyDepositor, depositor.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, depositAmount.String()), - sdk.NewAttribute(types.AttributeKeyShares, shares.String()), - ), - ) - - return nil -} - -func (k Keeper) depositAllowed(ctx sdk.Context, poolID string) bool { - params := k.GetParams(ctx) - for _, p := range params.AllowedPools { - if poolID == types.PoolID(p.TokenA, p.TokenB) { - return true - } - } - return false -} - -func (k Keeper) initializePool(ctx sdk.Context, poolID string, depositor sdk.AccAddress, reserves sdk.Coins) (*types.DenominatedPool, sdk.Coins, sdkmath.Int, error) { - if allowed := k.depositAllowed(ctx, poolID); !allowed { - return nil, sdk.Coins{}, sdk.ZeroInt(), errorsmod.Wrap(types.ErrNotAllowed, fmt.Sprintf("can not create pool '%s'", poolID)) - } - - pool, err := types.NewDenominatedPool(reserves) - if err != nil { - return nil, sdk.Coins{}, sdk.ZeroInt(), err - } - - return pool, pool.Reserves(), pool.TotalShares(), nil -} - -func (k Keeper) addLiquidityToPool(ctx sdk.Context, record types.PoolRecord, depositor sdk.AccAddress, desiredAmount sdk.Coins) (*types.DenominatedPool, sdk.Coins, sdkmath.Int, error) { - pool, err := types.NewDenominatedPoolWithExistingShares(record.Reserves(), record.TotalShares) - if err != nil { - return nil, sdk.Coins{}, sdk.ZeroInt(), err - } - - depositAmount, shares := pool.AddLiquidity(desiredAmount) - - return pool, depositAmount, shares, nil -} diff --git a/x/swap/keeper/deposit_test.go b/x/swap/keeper/deposit_test.go deleted file mode 100644 index 3685f89a..00000000 --- a/x/swap/keeper/deposit_test.go +++ /dev/null @@ -1,341 +0,0 @@ -package keeper_test - -import ( - "errors" - "fmt" - - "github.com/0glabs/0g-chain/x/swap/types" - - sdkmath "cosmossdk.io/math" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -func (suite *keeperTestSuite) TestDeposit_CreatePool_PoolNotAllowed() { - depositor := suite.CreateAccount(sdk.Coins{}) - amountA := sdk.NewCoin("ukava", sdkmath.NewInt(10e6)) - amountB := sdk.NewCoin("usdx", sdkmath.NewInt(50e6)) - - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), amountA, amountB, sdk.MustNewDecFromStr("0.01")) - suite.Require().EqualError(err, "can not create pool 'ukava:usdx': not allowed") -} - -func (suite *keeperTestSuite) TestDeposit_InsufficientFunds() { - testCases := []struct { - name string - balanceA sdk.Coin - balanceB sdk.Coin - depositA sdk.Coin - depositB sdk.Coin - }{ - { - name: "no balance", - balanceA: sdk.NewCoin("unuseddenom", sdk.ZeroInt()), - balanceB: sdk.NewCoin("unuseddenom", sdk.ZeroInt()), - depositA: sdk.NewCoin("ukava", sdkmath.NewInt(100)), - depositB: sdk.NewCoin("usdx", sdkmath.NewInt(100)), - }, - { - name: "low balance", - balanceA: sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), - balanceB: sdk.NewCoin("usdx", sdkmath.NewInt(1000000)), - depositA: sdk.NewCoin("ukava", sdkmath.NewInt(1000001)), - depositB: sdk.NewCoin("usdx", sdkmath.NewInt(10000001)), - }, - { - name: "large balance difference", - balanceA: sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - balanceB: sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), - depositA: sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - depositB: sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - pool := types.NewAllowedPool(tc.depositA.Denom, tc.depositB.Denom) - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.NewAllowedPools(pool), types.DefaultSwapFee)) - - balance := sdk.NewCoins(tc.balanceA, tc.balanceB) - depositor := suite.CreateAccount(balance) - - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), tc.depositA, tc.depositB, sdk.MustNewDecFromStr("0")) - // TODO: wrap in module specific error? - suite.Require().True(errors.Is(err, sdkerrors.ErrInsufficientFunds), fmt.Sprintf("got err %s", err)) - - suite.SetupTest() - // test deposit to existing pool insuffient funds - err = suite.CreatePool(sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), sdk.NewCoin("usdx", sdkmath.NewInt(50e6)))) - suite.Require().NoError(err) - err = suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), tc.depositA, tc.depositB, sdk.MustNewDecFromStr("10")) - suite.Require().True(errors.Is(err, sdkerrors.ErrInsufficientFunds)) - }) - } -} - -func (suite *keeperTestSuite) TestDeposit_InsufficientFunds_Vesting() { - testCases := []struct { - name string - balanceA sdk.Coin - balanceB sdk.Coin - vestingA sdk.Coin - vestingB sdk.Coin - depositA sdk.Coin - depositB sdk.Coin - }{ - { - name: "no balance, vesting only", - balanceA: sdk.NewCoin("ukava", sdk.ZeroInt()), - balanceB: sdk.NewCoin("usdx", sdk.ZeroInt()), - vestingA: sdk.NewCoin("ukava", sdkmath.NewInt(100)), - vestingB: sdk.NewCoin("usdx", sdkmath.NewInt(100)), - depositA: sdk.NewCoin("ukava", sdkmath.NewInt(100)), - depositB: sdk.NewCoin("usdx", sdkmath.NewInt(100)), - }, - { - name: "vesting matches balance exactly", - balanceA: sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), - balanceB: sdk.NewCoin("usdx", sdkmath.NewInt(1000000)), - vestingA: sdk.NewCoin("ukava", sdkmath.NewInt(1)), - vestingB: sdk.NewCoin("usdx", sdkmath.NewInt(1)), - depositA: sdk.NewCoin("ukava", sdkmath.NewInt(1000001)), - depositB: sdk.NewCoin("usdx", sdkmath.NewInt(10000001)), - }, - { - name: "large balance difference, vesting covers difference", - balanceA: sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - balanceB: sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), - vestingA: sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - vestingB: sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - depositA: sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - depositB: sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - }, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - - pool := types.NewAllowedPool(tc.depositA.Denom, tc.depositB.Denom) - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.NewAllowedPools(pool), types.DefaultSwapFee)) - - balance := sdk.NewCoins(tc.balanceA, tc.balanceB) - vesting := sdk.NewCoins(tc.vestingA, tc.vestingB) - depositor := suite.CreateVestingAccount(balance, vesting) - - // test create pool insuffient funds - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), tc.depositA, tc.depositB, sdk.MustNewDecFromStr("0")) - // TODO: wrap in module specific error? - suite.Require().True(errors.Is(err, sdkerrors.ErrInsufficientFunds)) - - suite.SetupTest() - // test deposit to existing pool insuffient funds - err = suite.CreatePool(sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), sdk.NewCoin("usdx", sdkmath.NewInt(50e6)))) - suite.Require().NoError(err) - err = suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), tc.depositA, tc.depositB, sdk.MustNewDecFromStr("4")) - suite.Require().True(errors.Is(err, sdkerrors.ErrInsufficientFunds)) - }) - } -} - -func (suite *keeperTestSuite) TestDeposit_CreatePool() { - pool := types.NewAllowedPool("ukava", "usdx") - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.NewAllowedPools(pool), types.DefaultSwapFee)) - - amountA := sdk.NewCoin(pool.TokenA, sdkmath.NewInt(11e6)) - amountB := sdk.NewCoin(pool.TokenB, sdkmath.NewInt(51e6)) - balance := sdk.NewCoins(amountA, amountB) - depositor := suite.CreateAccount(balance) - - depositA := sdk.NewCoin(pool.TokenA, sdkmath.NewInt(10e6)) - depositB := sdk.NewCoin(pool.TokenB, sdkmath.NewInt(50e6)) - deposit := sdk.NewCoins(depositA, depositB) - - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), depositA, depositB, sdk.MustNewDecFromStr("0")) - suite.Require().NoError(err) - suite.AccountBalanceEqual(depositor.GetAddress(), sdk.NewCoins(amountA.Sub(depositA), amountB.Sub(depositB))) - suite.ModuleAccountBalanceEqual(sdk.NewCoins(depositA, depositB)) - suite.PoolLiquidityEqual(deposit) - suite.PoolShareValueEqual(depositor, pool, deposit) - - suite.EventsContains(suite.Ctx.EventManager().Events(), sdk.NewEvent( - types.EventTypeSwapDeposit, - sdk.NewAttribute(types.AttributeKeyPoolID, pool.Name()), - sdk.NewAttribute(types.AttributeKeyDepositor, depositor.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, deposit.String()), - sdk.NewAttribute(types.AttributeKeyShares, "22360679"), - )) -} - -func (suite *keeperTestSuite) TestDeposit_PoolExists() { - pool := types.NewAllowedPool("ukava", "usdx") - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - err := suite.CreatePool(reserves) - suite.Require().NoError(err) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ) - depositor := suite.NewAccountFromAddr(sdk.AccAddress("new depositor-------"), balance) // TODO this is padded to the correct length, find a nicer way of creating test addresses - - depositA := sdk.NewCoin("usdx", balance.AmountOf("usdx")) - depositB := sdk.NewCoin("ukava", balance.AmountOf("ukava")) - - ctx := suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - err = suite.Keeper.Deposit(ctx, depositor.GetAddress(), depositA, depositB, sdk.MustNewDecFromStr("4")) - suite.Require().NoError(err) - - expectedDeposit := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ) - - expectedShareValue := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(999999)), - sdk.NewCoin("usdx", sdkmath.NewInt(4999998)), - ) - - suite.AccountBalanceEqual(depositor.GetAddress(), balance.Sub(expectedDeposit...)) - suite.ModuleAccountBalanceEqual(reserves.Add(expectedDeposit...)) - suite.PoolLiquidityEqual(reserves.Add(expectedDeposit...)) - suite.PoolShareValueEqual(depositor, pool, expectedShareValue) - - suite.EventsContains(ctx.EventManager().Events(), sdk.NewEvent( - types.EventTypeSwapDeposit, - sdk.NewAttribute(types.AttributeKeyPoolID, types.PoolID(pool.TokenA, pool.TokenB)), - sdk.NewAttribute(types.AttributeKeyDepositor, depositor.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, expectedDeposit.String()), - sdk.NewAttribute(types.AttributeKeyShares, "2236067"), - )) -} - -func (suite *keeperTestSuite) TestDeposit_MultipleDeposit() { - fundsToDeposit := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(25e6)), - ) - owner := suite.CreateAccount(fundsToDeposit) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - initialShares := sdkmath.NewInt(30e6) - poolID := suite.setupPool(reserves, initialShares, owner.GetAddress()) - - depositA := sdk.NewCoin("usdx", fundsToDeposit.AmountOf("usdx")) - depositB := sdk.NewCoin("ukava", fundsToDeposit.AmountOf("ukava")) - - err := suite.Keeper.Deposit(suite.Ctx, owner.GetAddress(), depositA, depositB, sdk.MustNewDecFromStr("4")) - suite.Require().NoError(err) - - totalDeposit := reserves.Add(fundsToDeposit...) - totalShares := initialShares.Add(sdkmath.NewInt(15e6)) - - suite.AccountBalanceEqual(owner.GetAddress(), sdk.Coins{}) - suite.ModuleAccountBalanceEqual(totalDeposit) - suite.PoolLiquidityEqual(totalDeposit) - suite.PoolDepositorSharesEqual(owner.GetAddress(), poolID, totalShares) - - suite.EventsContains(suite.Ctx.EventManager().Events(), sdk.NewEvent( - types.EventTypeSwapDeposit, - sdk.NewAttribute(types.AttributeKeyPoolID, poolID), - sdk.NewAttribute(types.AttributeKeyDepositor, owner.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, fundsToDeposit.String()), - sdk.NewAttribute(types.AttributeKeyShares, "15000000"), - )) -} - -func (suite *keeperTestSuite) TestDeposit_Slippage() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - - testCases := []struct { - depositA sdk.Coin - depositB sdk.Coin - slippage sdk.Dec - shouldFail bool - }{ - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.7"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.8"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("3"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("4"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4e6)), sdk.MustNewDecFromStr("0.25"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4e6)), sdk.MustNewDecFromStr("0.2"), true}, - } - - for _, tc := range testCases { - suite.Run(fmt.Sprintf("depositA=%s depositB=%s slippage=%s", tc.depositA, tc.depositB, tc.slippage), func() { - suite.SetupTest() - - err := suite.CreatePool(reserves) - suite.Require().NoError(err) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(100e6)), - ) - depositor := suite.CreateAccount(balance) - - ctx := suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - err = suite.Keeper.Deposit(ctx, depositor.GetAddress(), tc.depositA, tc.depositB, tc.slippage) - if tc.shouldFail { - suite.Require().Error(err) - suite.Contains(err.Error(), "slippage exceeded") - } else { - suite.NoError(err) - } - }) - } -} - -func (suite *keeperTestSuite) TestDeposit_InsufficientLiquidity() { - testCases := []struct { - poolA sdk.Coin - poolB sdk.Coin - poolShares sdkmath.Int - depositA sdk.Coin - depositB sdk.Coin - }{ - // test deposit amount truncating to zero - {sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), sdkmath.NewInt(40e6), sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(1))}, - // test share value rounding to zero - {sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), sdkmath.NewInt(100), sdk.NewCoin("ukava", sdkmath.NewInt(1000)), sdk.NewCoin("usdx", sdkmath.NewInt(1000))}, - } - - for _, tc := range testCases { - suite.Run(fmt.Sprintf("depositA=%s depositB=%s", tc.depositA, tc.depositB), func() { - suite.SetupTest() - - record := types.PoolRecord{ - PoolID: types.PoolID("ukava", "usdx"), - ReservesA: tc.poolA, - ReservesB: tc.poolB, - TotalShares: tc.poolShares, - } - - suite.Keeper.SetPool(suite.Ctx, record) - - balance := sdk.NewCoins(tc.depositA, tc.depositB) - depositor := suite.CreateAccount(balance) - - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), tc.depositA, tc.depositB, sdk.MustNewDecFromStr("10")) - suite.EqualError(err, "deposit must be increased: insufficient liquidity") - }) - } -} diff --git a/x/swap/keeper/grpc_query.go b/x/swap/keeper/grpc_query.go deleted file mode 100644 index e464f77a..00000000 --- a/x/swap/keeper/grpc_query.go +++ /dev/null @@ -1,150 +0,0 @@ -package keeper - -import ( - "context" - "strings" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - - "github.com/0glabs/0g-chain/x/swap/types" -) - -type queryServer struct { - keeper Keeper -} - -// NewQueryServerImpl creates a new server for handling gRPC queries. -func NewQueryServerImpl(k Keeper) types.QueryServer { - return &queryServer{keeper: k} -} - -var _ types.QueryServer = queryServer{} - -// Params implements the gRPC service handler for querying x/swap parameters. -func (s queryServer) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Errorf(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - params := s.keeper.GetParams(sdkCtx) - - return &types.QueryParamsResponse{Params: params}, nil -} - -// Pools implements the Query/Pools gRPC method -func (s queryServer) Pools(c context.Context, req *types.QueryPoolsRequest) (*types.QueryPoolsResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - ctx := sdk.UnwrapSDKContext(c) - store := prefix.NewStore(ctx.KVStore(s.keeper.key), types.PoolKeyPrefix) - - var queryResults []types.PoolResponse - pageRes, err := query.FilteredPaginate(store, req.Pagination, func(_, value []byte, shouldAccumulate bool) (bool, error) { - var poolRecord types.PoolRecord - err := s.keeper.cdc.Unmarshal(value, &poolRecord) - if err != nil { - return false, err - } - - if (len(req.PoolId) > 0) && strings.Compare(poolRecord.PoolID, req.PoolId) != 0 { - return false, nil - } - - if shouldAccumulate { - denominatedPool, err := types.NewDenominatedPoolWithExistingShares(poolRecord.Reserves(), poolRecord.TotalShares) - if err != nil { - return true, types.ErrInvalidPool - } - totalCoins := denominatedPool.ShareValue(denominatedPool.TotalShares()) - queryResult := types.PoolResponse{ - Name: poolRecord.PoolID, - Coins: totalCoins, - TotalShares: denominatedPool.TotalShares(), - } - queryResults = append(queryResults, queryResult) - } - return true, nil - }) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "paginate: %v", err) - } - - return &types.QueryPoolsResponse{ - Pools: queryResults, - Pagination: pageRes, - }, nil -} - -// Deposits implements the Query/Deposits gRPC method -func (s queryServer) Deposits(c context.Context, req *types.QueryDepositsRequest) (*types.QueryDepositsResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - ctx := sdk.UnwrapSDKContext(c) - store := prefix.NewStore(ctx.KVStore(s.keeper.key), types.DepositorPoolSharesPrefix) - - records := types.ShareRecords{} - pageRes, err := query.FilteredPaginate( - store, - req.Pagination, - func(key []byte, value []byte, accumulate bool) (bool, error) { - var record types.ShareRecord - err := s.keeper.cdc.Unmarshal(value, &record) - if err != nil { - return false, err - } - - // Filter for results match the request's pool ID/owner params if given - matchOwner, matchPool := true, true - if len(req.Owner) > 0 { - matchOwner = record.Depositor.String() == req.Owner - } - if len(req.PoolId) > 0 { - matchPool = strings.Compare(record.PoolID, req.PoolId) == 0 - } - if !(matchOwner && matchPool) { - // inform paginate that there was no match on this key - return false, nil - } - if accumulate { - // only add to results if paginate tells us to - records = append(records, record) - } - // inform paginate that were was a match on this key - return true, nil - }, - ) - if err != nil { - return nil, status.Error(codes.Internal, err.Error()) - } - - var queryResults []types.DepositResponse - for _, record := range records { - pool, err := s.keeper.loadDenominatedPool(ctx, record.PoolID) - if err != nil { - return nil, err - } - shareValue := pool.ShareValue(record.SharesOwned) - queryResult := types.DepositResponse{ - Depositor: record.Depositor.String(), - PoolId: record.PoolID, - SharesOwned: record.SharesOwned, - SharesValue: shareValue, - } - queryResults = append(queryResults, queryResult) - } - - return &types.QueryDepositsResponse{ - Deposits: queryResults, - Pagination: pageRes, - }, nil -} diff --git a/x/swap/keeper/hooks.go b/x/swap/keeper/hooks.go deleted file mode 100644 index 79cb058b..00000000 --- a/x/swap/keeper/hooks.go +++ /dev/null @@ -1,25 +0,0 @@ -package keeper - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/swap/types" -) - -// Implements SwapHooks interface -var _ types.SwapHooks = Keeper{} - -// AfterPoolDepositCreated - call hook if registered -func (k Keeper) AfterPoolDepositCreated(ctx sdk.Context, poolID string, depositor sdk.AccAddress, sharesOwned sdkmath.Int) { - if k.hooks != nil { - k.hooks.AfterPoolDepositCreated(ctx, poolID, depositor, sharesOwned) - } -} - -// BeforePoolDepositModified - call hook if registered -func (k Keeper) BeforePoolDepositModified(ctx sdk.Context, poolID string, depositor sdk.AccAddress, sharesOwned sdkmath.Int) { - if k.hooks != nil { - k.hooks.BeforePoolDepositModified(ctx, poolID, depositor, sharesOwned) - } -} diff --git a/x/swap/keeper/hooks_test.go b/x/swap/keeper/hooks_test.go deleted file mode 100644 index f353aa78..00000000 --- a/x/swap/keeper/hooks_test.go +++ /dev/null @@ -1,198 +0,0 @@ -package keeper_test - -import ( - "github.com/0glabs/0g-chain/x/swap/types" - "github.com/0glabs/0g-chain/x/swap/types/mocks" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/mock" -) - -func (suite *keeperTestSuite) TestHooks_DepositAndWithdraw() { - suite.Keeper.ClearHooks() - swapHooks := &mocks.SwapHooks{} - suite.Keeper.SetHooks(swapHooks) - - pool := types.NewAllowedPool("ukava", "usdx") - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.NewAllowedPools(pool), types.DefaultSwapFee)) - - balance := sdk.NewCoins( - sdk.NewCoin(pool.TokenA, sdkmath.NewInt(1000e6)), - sdk.NewCoin(pool.TokenB, sdkmath.NewInt(1000e6)), - ) - depositor_1 := suite.CreateAccount(balance) - - depositA := sdk.NewCoin(pool.TokenA, sdkmath.NewInt(10e6)) - depositB := sdk.NewCoin(pool.TokenB, sdkmath.NewInt(50e6)) - deposit := sdk.NewCoins(depositA, depositB) - - // expected initial shares - geometric mean - expectedShares := sdkmath.NewInt(22360679) - - // first deposit creates pool - calls AfterPoolDepositCreated with initial shares - swapHooks.On("AfterPoolDepositCreated", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_1.GetAddress(), expectedShares).Once() - err := suite.Keeper.Deposit(suite.Ctx, depositor_1.GetAddress(), depositA, depositB, sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - // second deposit adds to pool - calls BeforePoolDepositModified - // shares given are the initial shares, not the shares added to the pool - swapHooks.On("BeforePoolDepositModified", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_1.GetAddress(), expectedShares).Once() - err = suite.Keeper.Deposit(suite.Ctx, depositor_1.GetAddress(), sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.NewCoin("usdx", sdkmath.NewInt(25e6)), sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - // get the shares from the store from the last deposit - shareRecord, found := suite.Keeper.GetDepositorShares(suite.Ctx, depositor_1.GetAddress(), types.PoolIDFromCoins(deposit)) - suite.Require().True(found) - - // third deposit adds to pool - calls BeforePoolDepositModified - // shares given are the shares added in previous deposit, not the shares added to the pool now - swapHooks.On("BeforePoolDepositModified", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_1.GetAddress(), shareRecord.SharesOwned).Once() - err = suite.Keeper.Deposit(suite.Ctx, depositor_1.GetAddress(), sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - depositor_2 := suite.NewAccountFromAddr( - sdk.AccAddress("depositor 2---------"), - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(100e6)), - ), - ) - - // first deposit deposit into pool creates the deposit and calls AfterPoolDepositCreated - expectedShares = sdkmath.NewInt(2236067) - swapHooks.On("AfterPoolDepositCreated", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_2.GetAddress(), expectedShares).Once() - err = suite.Keeper.Deposit(suite.Ctx, depositor_2.GetAddress(), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - // second deposit into pool calls BeforePoolDepositModified with initial shares given - swapHooks.On("BeforePoolDepositModified", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_2.GetAddress(), expectedShares).Once() - err = suite.Keeper.Deposit(suite.Ctx, depositor_2.GetAddress(), sdk.NewCoin("ukava", sdkmath.NewInt(2e6)), sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - // get the shares from the store from the last deposit - shareRecord, found = suite.Keeper.GetDepositorShares(suite.Ctx, depositor_2.GetAddress(), types.PoolIDFromCoins(deposit)) - suite.Require().True(found) - - // third deposit into pool calls BeforePoolDepositModified with shares from last deposit - swapHooks.On("BeforePoolDepositModified", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_2.GetAddress(), shareRecord.SharesOwned).Once() - err = suite.Keeper.Deposit(suite.Ctx, depositor_2.GetAddress(), sdk.NewCoin("ukava", sdkmath.NewInt(3e6)), sdk.NewCoin("usdx", sdkmath.NewInt(15e6)), sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - // test hooks with a full withdraw of all shares - shareRecord, found = suite.Keeper.GetDepositorShares(suite.Ctx, depositor_1.GetAddress(), types.PoolIDFromCoins(deposit)) - suite.Require().True(found) - // all shares given to BeforePoolDepositModified - swapHooks.On("BeforePoolDepositModified", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_1.GetAddress(), shareRecord.SharesOwned).Once() - err = suite.Keeper.Withdraw(suite.Ctx, depositor_1.GetAddress(), shareRecord.SharesOwned, sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(1))) - suite.Require().NoError(err) - - // test hooks on partial withdraw - shareRecord, found = suite.Keeper.GetDepositorShares(suite.Ctx, depositor_2.GetAddress(), types.PoolIDFromCoins(deposit)) - suite.Require().True(found) - partialShares := shareRecord.SharesOwned.Quo(sdkmath.NewInt(3)) - // all shares given to before deposit modified even with partial withdraw - swapHooks.On("BeforePoolDepositModified", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_2.GetAddress(), shareRecord.SharesOwned).Once() - err = suite.Keeper.Withdraw(suite.Ctx, depositor_2.GetAddress(), partialShares, sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(1))) - suite.Require().NoError(err) - - // test hooks on second partial withdraw - shareRecord, found = suite.Keeper.GetDepositorShares(suite.Ctx, depositor_2.GetAddress(), types.PoolIDFromCoins(deposit)) - suite.Require().True(found) - partialShares = shareRecord.SharesOwned.Quo(sdkmath.NewInt(2)) - // all shares given to before deposit modified even with partial withdraw - swapHooks.On("BeforePoolDepositModified", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_2.GetAddress(), shareRecord.SharesOwned).Once() - err = suite.Keeper.Withdraw(suite.Ctx, depositor_2.GetAddress(), partialShares, sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(1))) - suite.Require().NoError(err) - - // test hooks withdraw all shares with second depositor - shareRecord, found = suite.Keeper.GetDepositorShares(suite.Ctx, depositor_2.GetAddress(), types.PoolIDFromCoins(deposit)) - suite.Require().True(found) - // all shares given to before deposit modified even with partial withdraw - swapHooks.On("BeforePoolDepositModified", suite.Ctx, types.PoolIDFromCoins(deposit), depositor_2.GetAddress(), shareRecord.SharesOwned).Once() - err = suite.Keeper.Withdraw(suite.Ctx, depositor_2.GetAddress(), shareRecord.SharesOwned, sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(1))) - suite.Require().NoError(err) - - swapHooks.AssertExpectations(suite.T()) -} - -func (suite *keeperTestSuite) TestHooks_NoPanicsOnNilHooks() { - suite.Keeper.ClearHooks() - - pool := types.NewAllowedPool("ukava", "usdx") - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.NewAllowedPools(pool), types.DefaultSwapFee)) - - balance := sdk.NewCoins( - sdk.NewCoin(pool.TokenA, sdkmath.NewInt(1000e6)), - sdk.NewCoin(pool.TokenB, sdkmath.NewInt(1000e6)), - ) - depositor := suite.CreateAccount(balance) - - depositA := sdk.NewCoin(pool.TokenA, sdkmath.NewInt(10e6)) - depositB := sdk.NewCoin(pool.TokenB, sdkmath.NewInt(50e6)) - deposit := sdk.NewCoins(depositA, depositB) - - // deposit create pool should not panic when hooks are not set - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), depositA, depositB, sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - // existing deposit should not panic with hooks are not set - err = suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.NewCoin("usdx", sdkmath.NewInt(25e6)), sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - // withdraw of shares should not panic when hooks are not set - shareRecord, found := suite.Keeper.GetDepositorShares(suite.Ctx, depositor.GetAddress(), types.PoolIDFromCoins(deposit)) - suite.Require().True(found) - err = suite.Keeper.Withdraw(suite.Ctx, depositor.GetAddress(), shareRecord.SharesOwned, sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(1))) - suite.Require().NoError(err) -} - -func (suite *keeperTestSuite) TestHooks_HookOrdering() { - suite.Keeper.ClearHooks() - swapHooks := &mocks.SwapHooks{} - suite.Keeper.SetHooks(swapHooks) - - pool := types.NewAllowedPool("ukava", "usdx") - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.NewAllowedPools(pool), types.DefaultSwapFee)) - - balance := sdk.NewCoins( - sdk.NewCoin(pool.TokenA, sdkmath.NewInt(1000e6)), - sdk.NewCoin(pool.TokenB, sdkmath.NewInt(1000e6)), - ) - depositor := suite.CreateAccount(balance) - - depositA := sdk.NewCoin(pool.TokenA, sdkmath.NewInt(10e6)) - depositB := sdk.NewCoin(pool.TokenB, sdkmath.NewInt(50e6)) - deposit := sdk.NewCoins(depositA, depositB) - - poolID := types.PoolIDFromCoins(deposit) - expectedShares := sdkmath.NewInt(22360679) - - swapHooks.On("AfterPoolDepositCreated", suite.Ctx, poolID, depositor.GetAddress(), expectedShares).Run(func(args mock.Arguments) { - _, found := suite.Keeper.GetDepositorShares(suite.Ctx, depositor.GetAddress(), poolID) - suite.Require().True(found, "expected after hook to be called after shares are updated") - }) - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), depositA, depositB, sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - swapHooks.On("BeforePoolDepositModified", suite.Ctx, poolID, depositor.GetAddress(), expectedShares).Run(func(args mock.Arguments) { - shareRecord, found := suite.Keeper.GetDepositorShares(suite.Ctx, depositor.GetAddress(), poolID) - suite.Require().True(found, "expected share record to exist") - suite.Equal(expectedShares, shareRecord.SharesOwned, "expected hook to be called before shares are updated") - }) - err = suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), depositA, depositB, sdk.MustNewDecFromStr("0.0015")) - suite.Require().NoError(err) - - existingShareRecord, found := suite.Keeper.GetDepositorShares(suite.Ctx, depositor.GetAddress(), types.PoolIDFromCoins(deposit)) - suite.Require().True(found) - swapHooks.On("BeforePoolDepositModified", suite.Ctx, poolID, depositor.GetAddress(), existingShareRecord.SharesOwned).Run(func(args mock.Arguments) { - shareRecord, found := suite.Keeper.GetDepositorShares(suite.Ctx, depositor.GetAddress(), poolID) - suite.Require().True(found, "expected share record to exist") - suite.Equal(existingShareRecord.SharesOwned, shareRecord.SharesOwned, "expected hook to be called before shares are updated") - }) - err = suite.Keeper.Withdraw(suite.Ctx, depositor.GetAddress(), existingShareRecord.SharesOwned.Quo(sdkmath.NewInt(2)), sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(1))) - suite.Require().NoError(err) -} diff --git a/x/swap/keeper/integration_test.go b/x/swap/keeper/integration_test.go deleted file mode 100644 index 9e6f8de6..00000000 --- a/x/swap/keeper/integration_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package keeper_test - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// nolint -func i(in int64) sdkmath.Int { return sdkmath.NewInt(in) } - -// nolint -func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) } - -// nolint -func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) } - -// func NewAuthGenStateFromAccs(accounts ...authexported.GenesisAccount) app.GenesisState { -// authGenesis := auth.NewGenesisState(auth.DefaultParams(), accounts) -// return app.GenesisState{auth.ModuleName: auth.ModuleCdc.MustMarshalJSON(authGenesis)} -// } - -// func NewSwapGenStateMulti() app.GenesisState { -// swapGenesis := types.GenesisState{ -// Params: types.Params{ -// AllowedPools: types.AllowedPools{ -// types.NewAllowedPool("ukava", "usdx"), -// }, -// SwapFee: sdk.MustNewDecFromStr("0.03"), -// }, -// } - -// return app.GenesisState{types.ModuleName: types.ModuleCdc.MustMarshalJSON(swapGenesis)} -// } diff --git a/x/swap/keeper/invariants.go b/x/swap/keeper/invariants.go deleted file mode 100644 index 50a6ad99..00000000 --- a/x/swap/keeper/invariants.go +++ /dev/null @@ -1,139 +0,0 @@ -package keeper - -import ( - "github.com/0glabs/0g-chain/x/swap/types" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// RegisterInvariants registers the swap module invariants -func RegisterInvariants(ir sdk.InvariantRegistry, k Keeper) { - ir.RegisterRoute(types.ModuleName, "pool-records", PoolRecordsInvariant(k)) - ir.RegisterRoute(types.ModuleName, "share-records", ShareRecordsInvariant(k)) - ir.RegisterRoute(types.ModuleName, "pool-reserves", PoolReservesInvariant(k)) - ir.RegisterRoute(types.ModuleName, "pool-shares", PoolSharesInvariant(k)) -} - -// AllInvariants runs all invariants of the swap module -func AllInvariants(k Keeper) sdk.Invariant { - return func(ctx sdk.Context) (string, bool) { - if res, stop := PoolRecordsInvariant(k)(ctx); stop { - return res, stop - } - - if res, stop := ShareRecordsInvariant(k)(ctx); stop { - return res, stop - } - - if res, stop := PoolReservesInvariant(k)(ctx); stop { - return res, stop - } - - res, stop := PoolSharesInvariant(k)(ctx) - return res, stop - } -} - -// PoolRecordsInvariant iterates all pool records and asserts that they are valid -func PoolRecordsInvariant(k Keeper) sdk.Invariant { - broken := false - message := sdk.FormatInvariant(types.ModuleName, "validate pool records broken", "pool record invalid") - - return func(ctx sdk.Context) (string, bool) { - k.IteratePools(ctx, func(record types.PoolRecord) bool { - if err := record.Validate(); err != nil { - broken = true - return true - } - return false - }) - - return message, broken - } -} - -// ShareRecordsInvariant iterates all share records and asserts that they are valid -func ShareRecordsInvariant(k Keeper) sdk.Invariant { - broken := false - message := sdk.FormatInvariant(types.ModuleName, "validate share records broken", "share record invalid") - - return func(ctx sdk.Context) (string, bool) { - k.IterateDepositorShares(ctx, func(record types.ShareRecord) bool { - if err := record.Validate(); err != nil { - broken = true - return true - } - return false - }) - - return message, broken - } -} - -// PoolReservesInvariant iterates all pools and ensures the total reserves matches the module account coins -func PoolReservesInvariant(k Keeper) sdk.Invariant { - message := sdk.FormatInvariant(types.ModuleName, "pool reserves broken", "pool reserves do not match module account") - - return func(ctx sdk.Context) (string, bool) { - balance := k.bankKeeper.GetAllBalances(ctx, k.GetSwapModuleAccount(ctx).GetAddress()) - - reserves := sdk.Coins{} - k.IteratePools(ctx, func(record types.PoolRecord) bool { - for _, coin := range record.Reserves() { - reserves = reserves.Add(coin) - } - return false - }) - - broken := !reserves.IsEqual(balance) - return message, broken - } -} - -type poolShares struct { - totalShares sdkmath.Int - totalSharesOwned sdkmath.Int -} - -// PoolSharesInvariant iterates all pools and shares and ensures the total pool shares match the sum of depositor shares -func PoolSharesInvariant(k Keeper) sdk.Invariant { - broken := false - message := sdk.FormatInvariant(types.ModuleName, "pool shares broken", "pool shares do not match depositor shares") - - return func(ctx sdk.Context) (string, bool) { - totalShares := make(map[string]poolShares) - - k.IteratePools(ctx, func(pr types.PoolRecord) bool { - totalShares[pr.PoolID] = poolShares{ - totalShares: pr.TotalShares, - totalSharesOwned: sdk.ZeroInt(), - } - - return false - }) - - k.IterateDepositorShares(ctx, func(sr types.ShareRecord) bool { - if shares, found := totalShares[sr.PoolID]; found { - shares.totalSharesOwned = shares.totalSharesOwned.Add(sr.SharesOwned) - totalShares[sr.PoolID] = shares - } else { - totalShares[sr.PoolID] = poolShares{ - totalShares: sdk.ZeroInt(), - totalSharesOwned: sr.SharesOwned, - } - } - - return false - }) - - for _, ps := range totalShares { - if !ps.totalShares.Equal(ps.totalSharesOwned) { - broken = true - break - } - } - - return message, broken - } -} diff --git a/x/swap/keeper/invariants_test.go b/x/swap/keeper/invariants_test.go deleted file mode 100644 index 389379f5..00000000 --- a/x/swap/keeper/invariants_test.go +++ /dev/null @@ -1,235 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/0glabs/0g-chain/x/swap/keeper" - "github.com/0glabs/0g-chain/x/swap/testutil" - "github.com/0glabs/0g-chain/x/swap/types" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" -) - -type invariantTestSuite struct { - testutil.Suite - invariants map[string]map[string]sdk.Invariant -} - -func (suite *invariantTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.invariants = make(map[string]map[string]sdk.Invariant) - keeper.RegisterInvariants(suite, suite.Keeper) -} - -func (suite *invariantTestSuite) SetupValidState() { - suite.Keeper.SetPool(suite.Ctx, types.NewPoolRecord( - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ), - sdkmath.NewInt(3e6), - )) - suite.AddCoinsToModule( - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ), - ) - suite.Keeper.SetDepositorShares(suite.Ctx, types.NewShareRecord( - sdk.AccAddress("depositor 1---------"), // TODO these addresses are padded to get to the required length of 20 bytes. What is a nicer setup? - types.PoolID("ukava", "usdx"), - sdkmath.NewInt(2e6), - )) - suite.Keeper.SetDepositorShares(suite.Ctx, types.NewShareRecord( - sdk.AccAddress("depositor 2---------"), - types.PoolID("ukava", "usdx"), - sdkmath.NewInt(1e6), - )) - - suite.Keeper.SetPool(suite.Ctx, types.NewPoolRecord( - sdk.NewCoins( - sdk.NewCoin("hard", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(2e6)), - ), - sdkmath.NewInt(1e6), - )) - suite.AddCoinsToModule( - sdk.NewCoins( - sdk.NewCoin("hard", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(2e6)), - ), - ) - suite.Keeper.SetDepositorShares(suite.Ctx, types.NewShareRecord( - sdk.AccAddress("depositor 1---------"), - types.PoolID("hard", "usdx"), - sdkmath.NewInt(1e6), - )) -} - -func (suite *invariantTestSuite) RegisterRoute(moduleName string, route string, invariant sdk.Invariant) { - _, exists := suite.invariants[moduleName] - - if !exists { - suite.invariants[moduleName] = make(map[string]sdk.Invariant) - } - - suite.invariants[moduleName][route] = invariant -} - -func (suite *invariantTestSuite) runInvariant(route string, invariant func(k keeper.Keeper) sdk.Invariant) (string, bool) { - ctx := suite.Ctx - registeredInvariant := suite.invariants[types.ModuleName][route] - suite.Require().NotNil(registeredInvariant) - - // direct call - dMessage, dBroken := invariant(suite.Keeper)(ctx) - // registered call - rMessage, rBroken := registeredInvariant(ctx) - // all call - aMessage, aBroken := keeper.AllInvariants(suite.Keeper)(ctx) - - // require matching values for direct call and registered call - suite.Require().Equal(dMessage, rMessage, "expected registered invariant message to match") - suite.Require().Equal(dBroken, rBroken, "expected registered invariant broken to match") - // require matching values for direct call and all invariants call if broken - suite.Require().Equal(dBroken, aBroken, "expected all invariant broken to match") - if dBroken { - suite.Require().Equal(dMessage, aMessage, "expected all invariant message to match") - } - - // return message, broken - return dMessage, dBroken -} - -func (suite *invariantTestSuite) TestPoolRecordsInvariant() { - // default state is valid - message, broken := suite.runInvariant("pool-records", keeper.PoolRecordsInvariant) - suite.Equal("swap: validate pool records broken invariant\npool record invalid\n", message) - suite.Equal(false, broken) - - suite.SetupValidState() - message, broken = suite.runInvariant("pool-records", keeper.PoolRecordsInvariant) - suite.Equal("swap: validate pool records broken invariant\npool record invalid\n", message) - suite.Equal(false, broken) - - // broken with invalid pool record - suite.Keeper.SetPool_Raw(suite.Ctx, types.NewPoolRecord( - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ), - sdkmath.NewInt(-1e6), - )) - message, broken = suite.runInvariant("pool-records", keeper.PoolRecordsInvariant) - suite.Equal("swap: validate pool records broken invariant\npool record invalid\n", message) - suite.Equal(true, broken) -} - -func (suite *invariantTestSuite) TestShareRecordsInvariant() { - message, broken := suite.runInvariant("share-records", keeper.ShareRecordsInvariant) - suite.Equal("swap: validate share records broken invariant\nshare record invalid\n", message) - suite.Equal(false, broken) - - suite.SetupValidState() - message, broken = suite.runInvariant("share-records", keeper.ShareRecordsInvariant) - suite.Equal("swap: validate share records broken invariant\nshare record invalid\n", message) - suite.Equal(false, broken) - - // broken with invalid share record - suite.Keeper.SetDepositorShares_Raw(suite.Ctx, types.NewShareRecord( - sdk.AccAddress("depositor 1---------"), - types.PoolID("ukava", "usdx"), - sdkmath.NewInt(-1e6), - )) - message, broken = suite.runInvariant("share-records", keeper.ShareRecordsInvariant) - suite.Equal("swap: validate share records broken invariant\nshare record invalid\n", message) - suite.Equal(true, broken) -} - -func (suite *invariantTestSuite) TestPoolReservesInvariant() { - message, broken := suite.runInvariant("pool-reserves", keeper.PoolReservesInvariant) - suite.Equal("swap: pool reserves broken invariant\npool reserves do not match module account\n", message) - suite.Equal(false, broken) - - suite.SetupValidState() - message, broken = suite.runInvariant("pool-reserves", keeper.PoolReservesInvariant) - suite.Equal("swap: pool reserves broken invariant\npool reserves do not match module account\n", message) - suite.Equal(false, broken) - - // broken when reserves are greater than module balance - suite.Keeper.SetPool(suite.Ctx, types.NewPoolRecord( - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(2e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), - ), - sdkmath.NewInt(5e6), - )) - message, broken = suite.runInvariant("pool-reserves", keeper.PoolReservesInvariant) - suite.Equal("swap: pool reserves broken invariant\npool reserves do not match module account\n", message) - suite.Equal(true, broken) - - // broken when reserves are less than the module balance - suite.Keeper.SetPool(suite.Ctx, types.NewPoolRecord( - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e5)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e5)), - ), - sdkmath.NewInt(3e5), - )) - message, broken = suite.runInvariant("pool-reserves", keeper.PoolReservesInvariant) - suite.Equal("swap: pool reserves broken invariant\npool reserves do not match module account\n", message) - suite.Equal(true, broken) -} - -func (suite *invariantTestSuite) TestPoolSharesInvariant() { - message, broken := suite.runInvariant("pool-shares", keeper.PoolSharesInvariant) - suite.Equal("swap: pool shares broken invariant\npool shares do not match depositor shares\n", message) - suite.Equal(false, broken) - - suite.SetupValidState() - message, broken = suite.runInvariant("pool-shares", keeper.PoolSharesInvariant) - suite.Equal("swap: pool shares broken invariant\npool shares do not match depositor shares\n", message) - suite.Equal(false, broken) - - // broken when total shares are greater than depositor shares - suite.Keeper.SetPool(suite.Ctx, types.NewPoolRecord( - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ), - sdkmath.NewInt(5e6), - )) - message, broken = suite.runInvariant("pool-shares", keeper.PoolSharesInvariant) - suite.Equal("swap: pool shares broken invariant\npool shares do not match depositor shares\n", message) - suite.Equal(true, broken) - - // broken when total shares are less than the depositor shares - suite.Keeper.SetPool(suite.Ctx, types.NewPoolRecord( - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ), - sdkmath.NewInt(1e5), - )) - message, broken = suite.runInvariant("pool-shares", keeper.PoolSharesInvariant) - suite.Equal("swap: pool shares broken invariant\npool shares do not match depositor shares\n", message) - suite.Equal(true, broken) - - // broken when pool record is missing - suite.Keeper.DeletePool(suite.Ctx, types.PoolID("ukava", "usdx")) - suite.RemoveCoinsFromModule( - sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ), - ) - message, broken = suite.runInvariant("pool-shares", keeper.PoolSharesInvariant) - suite.Equal("swap: pool shares broken invariant\npool shares do not match depositor shares\n", message) - suite.Equal(true, broken) -} - -func TestInvariantTestSuite(t *testing.T) { - suite.Run(t, new(invariantTestSuite)) -} diff --git a/x/swap/keeper/keeper.go b/x/swap/keeper/keeper.go deleted file mode 100644 index 6b098465..00000000 --- a/x/swap/keeper/keeper.go +++ /dev/null @@ -1,271 +0,0 @@ -package keeper - -import ( - "fmt" - - 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" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - - "github.com/0glabs/0g-chain/x/swap/types" -) - -// Keeper keeper for the swap module -type Keeper struct { - key storetypes.StoreKey - cdc codec.Codec - paramSubspace paramtypes.Subspace - hooks types.SwapHooks - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper -} - -// NewKeeper creates a new keeper -func NewKeeper( - cdc codec.Codec, - key storetypes.StoreKey, - paramstore paramtypes.Subspace, - accountKeeper types.AccountKeeper, - bankKeeper types.BankKeeper, -) Keeper { - if !paramstore.HasKeyTable() { - paramstore = paramstore.WithKeyTable(types.ParamKeyTable()) - } - - return Keeper{ - key: key, - cdc: cdc, - paramSubspace: paramstore, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - } -} - -// SetHooks adds hooks to the keeper. -func (k *Keeper) SetHooks(sh types.SwapHooks) *Keeper { - if k.hooks != nil { - panic("cannot set swap hooks twice") - } - k.hooks = sh - return k -} - -// ClearHooks clears the hooks on the keeper -func (k *Keeper) ClearHooks() { - k.hooks = nil -} - -// GetParams returns the params from the store -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - var p types.Params - k.paramSubspace.GetParamSet(ctx, &p) - return p -} - -// SetParams sets params on the store -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSubspace.SetParamSet(ctx, ¶ms) -} - -// GetSwapFee returns the swap fee set in the module parameters -func (k Keeper) GetSwapFee(ctx sdk.Context) sdk.Dec { - return k.GetParams(ctx).SwapFee -} - -// GetSwapModuleAccount returns the swap ModuleAccount -func (k Keeper) GetSwapModuleAccount(ctx sdk.Context) authtypes.ModuleAccountI { - return k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName) -} - -// GetPool retrieves a pool record from the store -func (k Keeper) GetPool(ctx sdk.Context, poolID string) (types.PoolRecord, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PoolKeyPrefix) - - bz := store.Get(types.PoolKey(poolID)) - if bz == nil { - return types.PoolRecord{}, false - } - - var record types.PoolRecord - k.cdc.MustUnmarshal(bz, &record) - - return record, true -} - -// SetPool_Raw saves a pool record to the store without any validation -func (k Keeper) SetPool_Raw(ctx sdk.Context, record types.PoolRecord) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PoolKeyPrefix) - bz := k.cdc.MustMarshal(&record) - store.Set(types.PoolKey(record.PoolID), bz) -} - -// SetPool saves a pool to the store and panics if the record is invalid -func (k Keeper) SetPool(ctx sdk.Context, record types.PoolRecord) { - if err := record.Validate(); err != nil { - panic(fmt.Sprintf("invalid pool record: %s", err)) - } - - k.SetPool_Raw(ctx, record) -} - -// DeletePool deletes a pool record from the store -func (k Keeper) DeletePool(ctx sdk.Context, poolID string) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PoolKeyPrefix) - store.Delete(types.PoolKey(poolID)) -} - -// IteratePools iterates over all pool objects in the store and performs a callback function -func (k Keeper) IteratePools(ctx sdk.Context, cb func(record types.PoolRecord) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.PoolKeyPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var record types.PoolRecord - k.cdc.MustUnmarshal(iterator.Value(), &record) - if cb(record) { - break - } - } -} - -// GetAllPools returns all pool records from the store -func (k Keeper) GetAllPools(ctx sdk.Context) (records types.PoolRecords) { - k.IteratePools(ctx, func(record types.PoolRecord) bool { - records = append(records, record) - return false - }) - return -} - -// GetPoolShares gets the total shares in a pool from the store -func (k Keeper) GetPoolShares(ctx sdk.Context, poolID string) (sdkmath.Int, bool) { - pool, found := k.GetPool(ctx, poolID) - if !found { - return sdkmath.Int{}, false - } - return pool.TotalShares, true -} - -// GetDepositorShares gets a share record from the store -func (k Keeper) GetDepositorShares(ctx sdk.Context, depositor sdk.AccAddress, poolID string) (types.ShareRecord, bool) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositorPoolSharesPrefix) - bz := store.Get(types.DepositorPoolSharesKey(depositor, poolID)) - if bz == nil { - return types.ShareRecord{}, false - } - var record types.ShareRecord - k.cdc.MustUnmarshal(bz, &record) - return record, true -} - -// SetDepositorShares_Raw saves a share record to the store without validation -func (k Keeper) SetDepositorShares_Raw(ctx sdk.Context, record types.ShareRecord) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositorPoolSharesPrefix) - bz := k.cdc.MustMarshal(&record) - store.Set(types.DepositorPoolSharesKey(record.Depositor, record.PoolID), bz) -} - -// SetDepositorShares saves a share record to the store and panics if the record is invalid -func (k Keeper) SetDepositorShares(ctx sdk.Context, record types.ShareRecord) { - if err := record.Validate(); err != nil { - panic(fmt.Sprintf("invalid share record: %s", err)) - } - - k.SetDepositorShares_Raw(ctx, record) -} - -// DeleteDepositorShares deletes a share record from the store -func (k Keeper) DeleteDepositorShares(ctx sdk.Context, depositor sdk.AccAddress, poolID string) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositorPoolSharesPrefix) - store.Delete(types.DepositorPoolSharesKey(depositor, poolID)) -} - -// IterateDepositorShares iterates over all pool objects in the store and performs a callback function -func (k Keeper) IterateDepositorShares(ctx sdk.Context, cb func(record types.ShareRecord) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositorPoolSharesPrefix) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var record types.ShareRecord - k.cdc.MustUnmarshal(iterator.Value(), &record) - if cb(record) { - break - } - } -} - -// GetAllDepositorShares returns all depositor share records from the store -func (k Keeper) GetAllDepositorShares(ctx sdk.Context) (records types.ShareRecords) { - k.IterateDepositorShares(ctx, func(record types.ShareRecord) bool { - records = append(records, record) - return false - }) - return -} - -// IterateDepositorSharesByOwner iterates over share records for a specific address and performs a callback function -func (k Keeper) IterateDepositorSharesByOwner(ctx sdk.Context, owner sdk.AccAddress, cb func(record types.ShareRecord) (stop bool)) { - store := prefix.NewStore(ctx.KVStore(k.key), types.DepositorPoolSharesPrefix) - iterator := sdk.KVStorePrefixIterator(store, owner.Bytes()) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var record types.ShareRecord - k.cdc.MustUnmarshal(iterator.Value(), &record) - if cb(record) { - break - } - } -} - -// GetAllDepositorSharesByOwner returns all depositor share records from the store for a specific address -func (k Keeper) GetAllDepositorSharesByOwner(ctx sdk.Context, owner sdk.AccAddress) (records types.ShareRecords) { - k.IterateDepositorSharesByOwner(ctx, owner, func(record types.ShareRecord) bool { - records = append(records, record) - return false - }) - return -} - -// GetDepositorSharesAmount gets a depositor's shares in a pool from the store -func (k Keeper) GetDepositorSharesAmount(ctx sdk.Context, depositor sdk.AccAddress, poolID string) (sdkmath.Int, bool) { - record, found := k.GetDepositorShares(ctx, depositor, poolID) - if !found { - return sdkmath.Int{}, false - } - return record.SharesOwned, true -} - -// updatePool updates a pool, deleting the pool record if the shares are zero -func (k Keeper) updatePool(ctx sdk.Context, poolID string, pool *types.DenominatedPool) { - if pool.TotalShares().IsZero() { - k.DeletePool(ctx, poolID) - } else { - k.SetPool(ctx, types.NewPoolRecordFromPool(pool)) - } -} - -// updateDepositorShares updates a depositor share records for a pool, deleting the record if the new shares are zero -func (k Keeper) updateDepositorShares(ctx sdk.Context, owner sdk.AccAddress, poolID string, shares sdkmath.Int) { - if shares.IsZero() { - k.DeleteDepositorShares(ctx, owner, poolID) - } else { - shareRecord := types.NewShareRecord(owner, poolID, shares) - k.SetDepositorShares(ctx, shareRecord) - } -} - -func (k Keeper) loadDenominatedPool(ctx sdk.Context, poolID string) (*types.DenominatedPool, error) { - poolRecord, found := k.GetPool(ctx, poolID) - if !found { - return &types.DenominatedPool{}, types.ErrInvalidPool - } - denominatedPool, err := types.NewDenominatedPoolWithExistingShares(poolRecord.Reserves(), poolRecord.TotalShares) - if err != nil { - return &types.DenominatedPool{}, types.ErrInvalidPool - } - return denominatedPool, nil -} diff --git a/x/swap/keeper/keeper_test.go b/x/swap/keeper/keeper_test.go deleted file mode 100644 index 83fbe87c..00000000 --- a/x/swap/keeper/keeper_test.go +++ /dev/null @@ -1,196 +0,0 @@ -package keeper_test - -import ( - "os" - "testing" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/swap/testutil" - "github.com/0glabs/0g-chain/x/swap/types" - "github.com/0glabs/0g-chain/x/swap/types/mocks" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" -) - -func TestMain(m *testing.M) { - config := sdk.GetConfig() - app.SetBech32AddressPrefixes(config) - - os.Exit(m.Run()) -} - -type keeperTestSuite struct { - testutil.Suite -} - -func (suite *keeperTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.DefaultParams()) -} - -func TestKeeperTestSuite(t *testing.T) { - suite.Run(t, new(keeperTestSuite)) -} - -func (suite *keeperTestSuite) setupPool(reserves sdk.Coins, totalShares sdkmath.Int, depositor sdk.AccAddress) string { - poolID := types.PoolIDFromCoins(reserves) - suite.AddCoinsToModule(reserves) - - poolRecord := types.PoolRecord{ - PoolID: poolID, - ReservesA: reserves[0], - ReservesB: reserves[1], - TotalShares: totalShares, - } - suite.Keeper.SetPool(suite.Ctx, poolRecord) - - shareRecord := types.ShareRecord{ - Depositor: depositor, - PoolID: poolID, - SharesOwned: totalShares, - } - suite.Keeper.SetDepositorShares(suite.Ctx, shareRecord) - - return poolID -} - -func (suite keeperTestSuite) TestParams_Persistance() { - keeper := suite.Keeper - - params := types.Params{ - AllowedPools: types.AllowedPools{ - types.NewAllowedPool("ukava", "usdx"), - }, - SwapFee: sdk.MustNewDecFromStr("0.03"), - } - keeper.SetParams(suite.Ctx, params) - suite.Equal(keeper.GetParams(suite.Ctx), params) - - oldParams := params - params = types.Params{ - AllowedPools: types.AllowedPools{ - types.NewAllowedPool("hard", "ukava"), - }, - SwapFee: sdk.MustNewDecFromStr("0.01"), - } - keeper.SetParams(suite.Ctx, params) - suite.NotEqual(keeper.GetParams(suite.Ctx), oldParams) - suite.Equal(keeper.GetParams(suite.Ctx), params) -} - -func (suite keeperTestSuite) TestParams_GetSwapFee() { - keeper := suite.Keeper - - params := types.Params{ - SwapFee: sdk.MustNewDecFromStr("0.00333"), - } - keeper.SetParams(suite.Ctx, params) - - suite.Equal(keeper.GetSwapFee(suite.Ctx), params.SwapFee) -} - -func (suite *keeperTestSuite) TestPool_Persistance() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - - pool, err := types.NewDenominatedPool(reserves) - suite.Nil(err) - record := types.NewPoolRecordFromPool(pool) - - suite.Keeper.SetPool(suite.Ctx, record) - - savedRecord, ok := suite.Keeper.GetPool(suite.Ctx, record.PoolID) - suite.True(ok) - suite.Equal(record, savedRecord) - - savedShares, ok := suite.Keeper.GetPoolShares(suite.Ctx, record.PoolID) - suite.True(ok) - suite.Equal(record.TotalShares, savedShares) - - suite.Keeper.DeletePool(suite.Ctx, record.PoolID) - deletedPool, ok := suite.Keeper.GetPool(suite.Ctx, record.PoolID) - suite.False(ok) - suite.Equal(deletedPool, types.PoolRecord{}) -} - -func (suite *keeperTestSuite) TestPool_PanicsWhenInvalid() { - invalidRecord := types.NewPoolRecord( - sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), sdk.NewCoin("usdx", sdkmath.NewInt(100e6))), - i(-1), - ) - - suite.Panics(func() { - suite.Keeper.SetPool(suite.Ctx, invalidRecord) - }, "expected set pool to panic with invalid record") -} - -func (suite *keeperTestSuite) TestShare_Persistance() { - poolID := types.PoolID("ukava", "usdx") - depositor, err := sdk.AccAddressFromBech32("kava1skpsgk5cnrarn69ql2tfun47fyjssataz0g07l") - suite.NoError(err) - shares := sdkmath.NewInt(3126432331) - - record := types.NewShareRecord(depositor, poolID, shares) - suite.Keeper.SetDepositorShares(suite.Ctx, record) - - savedRecord, ok := suite.Keeper.GetDepositorShares(suite.Ctx, depositor, poolID) - suite.True(ok) - suite.Equal(record, savedRecord) - - savedShares, ok := suite.Keeper.GetDepositorSharesAmount(suite.Ctx, depositor, poolID) - suite.True(ok) - suite.Equal(record.SharesOwned, savedShares) - - suite.Keeper.DeleteDepositorShares(suite.Ctx, depositor, poolID) - deletedShares, ok := suite.Keeper.GetDepositorShares(suite.Ctx, depositor, poolID) - suite.False(ok) - suite.Equal(deletedShares, types.ShareRecord{}) -} - -func (suite *keeperTestSuite) TestShare_PanicsWhenInvalid() { - depositor, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - suite.Require().NoError(err) - - invalidRecord := types.NewShareRecord( - depositor, - "hard/usdx", - i(-1), - ) - - suite.Panics(func() { - suite.Keeper.SetDepositorShares(suite.Ctx, invalidRecord) - }, "expected set depositor shares to panic with invalid record") -} - -func (suite *keeperTestSuite) TestHooks() { - // ensure no hooks are set - suite.Keeper.ClearHooks() - - // data - depositor, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - suite.Require().NoError(err) - - // hooks can be called when not set - suite.Keeper.AfterPoolDepositCreated(suite.Ctx, "ukava/usdx", depositor, sdkmath.NewInt(1e6)) - suite.Keeper.BeforePoolDepositModified(suite.Ctx, "ukava/usdx", depositor, sdkmath.NewInt(1e6)) - - // set hooks - swapHooks := &mocks.SwapHooks{} - suite.Keeper.SetHooks(swapHooks) - - // test hook calls are correct - swapHooks.On("AfterPoolDepositCreated", suite.Ctx, "ukava/usdx", depositor, sdkmath.NewInt(1e6)).Once() - suite.Keeper.AfterPoolDepositCreated(suite.Ctx, "ukava/usdx", depositor, sdkmath.NewInt(1e6)) - swapHooks.On("BeforePoolDepositModified", suite.Ctx, "ukava/usdx", depositor, sdkmath.NewInt(1e6)).Once() - suite.Keeper.BeforePoolDepositModified(suite.Ctx, "ukava/usdx", depositor, sdkmath.NewInt(1e6)) - swapHooks.AssertExpectations(suite.T()) - - // test second set panics - suite.PanicsWithValue("cannot set swap hooks twice", func() { - suite.Keeper.SetHooks(swapHooks) - }, "expected hooks to panic on second set") -} diff --git a/x/swap/keeper/msg_server.go b/x/swap/keeper/msg_server.go deleted file mode 100644 index d2f2d527..00000000 --- a/x/swap/keeper/msg_server.go +++ /dev/null @@ -1,153 +0,0 @@ -package keeper - -import ( - "context" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/swap/types" -) - -type msgServer struct { - keeper Keeper -} - -// NewMsgServerImpl returns an implementation of the swap MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -// Deposit handles MsgDeposit messages -func (m msgServer) Deposit(goCtx context.Context, msg *types.MsgDeposit) (*types.MsgDepositResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if err := checkDeadline(ctx, msg); err != nil { - return nil, err - } - - depositor, err := sdk.AccAddressFromBech32(msg.Depositor) - if err != nil { - return nil, err - } - - if err := m.keeper.Deposit(ctx, depositor, msg.TokenA, msg.TokenB, msg.Slippage); err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.String()), - ), - ) - - return &types.MsgDepositResponse{}, nil -} - -// Withdraw handles MsgWithdraw messages -func (m msgServer) Withdraw(goCtx context.Context, msg *types.MsgWithdraw) (*types.MsgWithdrawResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if err := checkDeadline(ctx, msg); err != nil { - return nil, err - } - - from, err := sdk.AccAddressFromBech32(msg.From) - if err != nil { - return nil, err - } - - if err := m.keeper.Withdraw(ctx, from, msg.Shares, msg.MinTokenA, msg.MinTokenB); err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, from.String()), - ), - ) - - return &types.MsgWithdrawResponse{}, nil -} - -// SwapExactForTokens handles MsgSwapExactForTokens messages -func (m msgServer) SwapExactForTokens(goCtx context.Context, msg *types.MsgSwapExactForTokens) (*types.MsgSwapExactForTokensResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if err := checkDeadline(ctx, msg); err != nil { - return nil, err - } - - requester, err := sdk.AccAddressFromBech32(msg.Requester) - if err != nil { - return nil, err - } - - if err := m.keeper.SwapExactForTokens(ctx, requester, msg.ExactTokenA, msg.TokenB, msg.Slippage); err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, requester.String()), - ), - ) - - return &types.MsgSwapExactForTokensResponse{}, nil -} - -// SwapForExactTokens handles MsgSwapForExactTokens messages -func (m msgServer) SwapForExactTokens(goCtx context.Context, msg *types.MsgSwapForExactTokens) (*types.MsgSwapForExactTokensResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - if err := checkDeadline(ctx, msg); err != nil { - return nil, err - } - - requester, err := sdk.AccAddressFromBech32(msg.Requester) - if err != nil { - return nil, err - } - - if err := m.keeper.SwapForExactTokens(ctx, requester, msg.TokenA, msg.ExactTokenB, msg.Slippage); err != nil { - return nil, err - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, requester.String()), - ), - ) - - return &types.MsgSwapForExactTokensResponse{}, nil -} - -// checkDeadline returns an error if block time exceeds an included deadline -func checkDeadline(ctx sdk.Context, msg sdk.Msg) error { - deadlineMsg, ok := msg.(types.MsgWithDeadline) - if !ok { - return nil - } - - if deadlineMsg.DeadlineExceeded(ctx.BlockTime()) { - return errorsmod.Wrapf( - types.ErrDeadlineExceeded, - "block time %d >= deadline %d", - ctx.BlockTime().Unix(), - deadlineMsg.GetDeadline().Unix(), - ) - } - - return nil -} diff --git a/x/swap/keeper/msg_server_test.go b/x/swap/keeper/msg_server_test.go deleted file mode 100644 index 50268535..00000000 --- a/x/swap/keeper/msg_server_test.go +++ /dev/null @@ -1,591 +0,0 @@ -package keeper_test - -import ( - "fmt" - "testing" - "time" - - "github.com/0glabs/0g-chain/x/swap/keeper" - "github.com/0glabs/0g-chain/x/swap/testutil" - "github.com/0glabs/0g-chain/x/swap/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - "github.com/stretchr/testify/suite" - - sdkmath "cosmossdk.io/math" - "github.com/cometbft/cometbft/crypto" - sdk "github.com/cosmos/cosmos-sdk/types" - bank "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -var swapModuleAccountAddress = sdk.AccAddress(crypto.AddressHash([]byte(types.ModuleAccountName))) - -type msgServerTestSuite struct { - testutil.Suite - msgServer types.MsgServer -} - -func (suite *msgServerTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.msgServer = keeper.NewMsgServerImpl(suite.Keeper) -} - -func (suite *msgServerTestSuite) TestDeposit_CreatePool() { - pool := types.NewAllowedPool("ukava", "usdx") - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.AllowedPools{pool}, types.DefaultSwapFee)) - - balance := sdk.NewCoins( - sdk.NewCoin(pool.TokenA, sdkmath.NewInt(10e6)), - sdk.NewCoin(pool.TokenB, sdkmath.NewInt(50e6)), - ) - depositor := suite.NewAccountFromAddr(sdk.AccAddress("new depositor-------"), balance) - - deposit := types.NewMsgDeposit( - depositor.GetAddress().String(), - suite.BankKeeper.GetBalance(suite.Ctx, depositor.GetAddress(), pool.TokenA), - suite.BankKeeper.GetBalance(suite.Ctx, depositor.GetAddress(), pool.TokenB), - sdk.MustNewDecFromStr("0.01"), - time.Now().Add(10*time.Minute).Unix(), - ) - - res, err := suite.msgServer.Deposit(sdk.WrapSDKContext(suite.Ctx), deposit) - suite.Require().Equal(&types.MsgDepositResponse{}, res) - suite.Require().NoError(err) - - suite.AccountBalanceEqual(depositor.GetAddress(), sdk.Coins{}) - suite.ModuleAccountBalanceEqual(balance) - suite.PoolLiquidityEqual(balance) - suite.PoolShareValueEqual(depositor, pool, balance) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.GetAddress().String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - bank.EventTypeTransfer, - sdk.NewAttribute(bank.AttributeKeyRecipient, swapModuleAccountAddress.String()), - sdk.NewAttribute(bank.AttributeKeySender, depositor.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, balance.String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - types.EventTypeSwapDeposit, - sdk.NewAttribute(types.AttributeKeyPoolID, types.PoolID(pool.TokenA, pool.TokenB)), - sdk.NewAttribute(types.AttributeKeyDepositor, depositor.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, balance.String()), - sdk.NewAttribute(types.AttributeKeyShares, "22360679"), - )) -} - -func (suite *msgServerTestSuite) TestDeposit_DeadlineExceeded() { - pool := types.NewAllowedPool("ukava", "usdx") - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.AllowedPools{pool}, types.DefaultSwapFee)) - - balance := sdk.NewCoins( - sdk.NewCoin(pool.TokenA, sdkmath.NewInt(10e6)), - sdk.NewCoin(pool.TokenB, sdkmath.NewInt(50e6)), - ) - depositor := suite.NewAccountFromAddr(sdk.AccAddress("new depositor-------"), balance) - - deposit := types.NewMsgDeposit( - depositor.GetAddress().String(), - suite.BankKeeper.GetBalance(suite.Ctx, depositor.GetAddress(), pool.TokenA), - suite.BankKeeper.GetBalance(suite.Ctx, depositor.GetAddress(), pool.TokenB), - sdk.MustNewDecFromStr("0.01"), - suite.Ctx.BlockTime().Add(-1*time.Second).Unix(), - ) - - res, err := suite.msgServer.Deposit(sdk.WrapSDKContext(suite.Ctx), deposit) - suite.Require().Nil(res) - suite.EqualError(err, fmt.Sprintf("block time %d >= deadline %d: deadline exceeded", suite.Ctx.BlockTime().Unix(), deposit.GetDeadline().Unix())) - suite.Nil(res) -} - -func (suite *msgServerTestSuite) TestDeposit_ExistingPool() { - pool := types.NewAllowedPool("ukava", "usdx") - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - err := suite.CreatePool(reserves) - suite.Require().NoError(err) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ) - depositor := suite.NewAccountFromAddr(sdk.AccAddress("new depositor-------"), balance) - - deposit := types.NewMsgDeposit( - depositor.GetAddress().String(), - suite.BankKeeper.GetBalance(suite.Ctx, depositor.GetAddress(), "usdx"), - suite.BankKeeper.GetBalance(suite.Ctx, depositor.GetAddress(), "ukava"), - sdk.MustNewDecFromStr("0.01"), - time.Now().Add(10*time.Minute).Unix(), - ) - - res, err := suite.msgServer.Deposit(sdk.WrapSDKContext(suite.Ctx), deposit) - suite.Require().Equal(&types.MsgDepositResponse{}, res) - suite.Require().NoError(err) - - expectedDeposit := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ) - - expectedShareValue := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(999999)), - sdk.NewCoin("usdx", sdkmath.NewInt(4999998)), - ) - - // Use sdk.NewCoins to remove zero coins, otherwise it will compare sdk.Coins(nil) with sdk.Coins{} - suite.AccountBalanceEqual(depositor.GetAddress(), sdk.NewCoins(balance.Sub(expectedDeposit...)...)) - suite.ModuleAccountBalanceEqual(reserves.Add(expectedDeposit...)) - suite.PoolLiquidityEqual(reserves.Add(expectedDeposit...)) - suite.PoolShareValueEqual(depositor, pool, expectedShareValue) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.GetAddress().String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - bank.EventTypeTransfer, - sdk.NewAttribute(bank.AttributeKeyRecipient, swapModuleAccountAddress.String()), - sdk.NewAttribute(bank.AttributeKeySender, depositor.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, expectedDeposit.String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - types.EventTypeSwapDeposit, - sdk.NewAttribute(types.AttributeKeyPoolID, types.PoolID(pool.TokenA, pool.TokenB)), - sdk.NewAttribute(types.AttributeKeyDepositor, depositor.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, expectedDeposit.String()), - sdk.NewAttribute(types.AttributeKeyShares, "2236067"), - )) -} - -func (suite *msgServerTestSuite) TestDeposit_ExistingPool_SlippageFailure() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - err := suite.CreatePool(reserves) - suite.Require().NoError(err) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - ) - depositor := suite.NewAccountFromAddr(sdk.AccAddress("new depositor-------"), balance) - - deposit := types.NewMsgDeposit( - depositor.GetAddress().String(), - suite.BankKeeper.GetBalance(suite.Ctx, depositor.GetAddress(), "usdx"), - suite.BankKeeper.GetBalance(suite.Ctx, depositor.GetAddress(), "ukava"), - sdk.MustNewDecFromStr("0.01"), - time.Now().Add(10*time.Minute).Unix(), - ) - - res, err := suite.msgServer.Deposit(sdk.WrapSDKContext(suite.Ctx), deposit) - suite.Require().Nil(res) - suite.EqualError(err, "slippage 4.000000000000000000 > limit 0.010000000000000000: slippage exceeded") - suite.Nil(res) -} - -func (suite *msgServerTestSuite) TestWithdraw_AllShares() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - depositor := suite.NewAccountFromAddr(sdk.AccAddress("new depositor-------"), reserves) - pool := types.NewAllowedPool(reserves[0].Denom, reserves[1].Denom) - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.AllowedPools{pool}, types.DefaultSwapFee)) - - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), reserves[0], reserves[1], sdk.MustNewDecFromStr("1")) - suite.Require().NoError(err) - - withdraw := types.NewMsgWithdraw( - depositor.GetAddress().String(), - sdkmath.NewInt(22360679), - reserves[0], - reserves[1], - time.Now().Add(10*time.Minute).Unix(), - ) - - suite.Ctx = suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - res, err := suite.msgServer.Withdraw(sdk.WrapSDKContext(suite.Ctx), withdraw) - suite.Require().Equal(&types.MsgWithdrawResponse{}, res) - suite.Require().NoError(err) - - suite.AccountBalanceEqual(depositor.GetAddress(), reserves) - suite.ModuleAccountBalanceEqual(sdk.Coins{}) - suite.PoolDeleted("ukava", "usdx") - suite.PoolSharesDeleted(depositor.GetAddress(), "ukava", "usdx") - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.GetAddress().String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - bank.EventTypeTransfer, - sdk.NewAttribute(bank.AttributeKeyRecipient, depositor.GetAddress().String()), - sdk.NewAttribute(bank.AttributeKeySender, swapModuleAccountAddress.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, reserves.String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - types.EventTypeSwapWithdraw, - sdk.NewAttribute(types.AttributeKeyPoolID, types.PoolID(pool.TokenA, pool.TokenB)), - sdk.NewAttribute(types.AttributeKeyOwner, depositor.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, reserves.String()), - sdk.NewAttribute(types.AttributeKeyShares, "22360679"), - )) -} - -func (suite *msgServerTestSuite) TestWithdraw_PartialShares() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - depositor := suite.NewAccountFromAddr(sdk.AccAddress("new depositor-------"), reserves) - pool := types.NewAllowedPool(reserves[0].Denom, reserves[1].Denom) - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.AllowedPools{pool}, types.DefaultSwapFee)) - - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), reserves[0], reserves[1], sdk.MustNewDecFromStr("1")) - suite.Require().NoError(err) - - minTokenA := sdk.NewCoin("ukava", sdkmath.NewInt(4999999)) - minTokenB := sdk.NewCoin("usdx", sdkmath.NewInt(24999998)) - - withdraw := types.NewMsgWithdraw( - depositor.GetAddress().String(), - sdkmath.NewInt(11180339), - minTokenA, - minTokenB, - time.Now().Add(10*time.Minute).Unix(), - ) - - suite.Ctx = suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - res, err := suite.msgServer.Withdraw(sdk.WrapSDKContext(suite.Ctx), withdraw) - suite.Require().Equal(&types.MsgWithdrawResponse{}, res) - suite.Require().NoError(err) - - expectedCoinsReceived := sdk.NewCoins(minTokenA, minTokenB) - - suite.AccountBalanceEqual(depositor.GetAddress(), expectedCoinsReceived) - suite.ModuleAccountBalanceEqual(reserves.Sub(expectedCoinsReceived...)) - suite.PoolLiquidityEqual(reserves.Sub(expectedCoinsReceived...)) - suite.PoolShareValueEqual(depositor, types.NewAllowedPool("ukava", "usdx"), reserves.Sub(expectedCoinsReceived...)) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, depositor.GetAddress().String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - bank.EventTypeTransfer, - sdk.NewAttribute(bank.AttributeKeyRecipient, depositor.GetAddress().String()), - sdk.NewAttribute(bank.AttributeKeySender, swapModuleAccountAddress.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, expectedCoinsReceived.String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - types.EventTypeSwapWithdraw, - sdk.NewAttribute(types.AttributeKeyPoolID, types.PoolID(pool.TokenA, pool.TokenB)), - sdk.NewAttribute(types.AttributeKeyOwner, depositor.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, expectedCoinsReceived.String()), - sdk.NewAttribute(types.AttributeKeyShares, "11180339"), - )) -} - -func (suite *msgServerTestSuite) TestWithdraw_SlippageFailure() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - depositor := suite.NewAccountFromAddr(sdk.AccAddress("new depositor-------"), reserves) - pool := types.NewAllowedPool(reserves[0].Denom, reserves[1].Denom) - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.AllowedPools{pool}, types.DefaultSwapFee)) - - err := suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), reserves[0], reserves[1], sdk.MustNewDecFromStr("1")) - suite.Require().NoError(err) - - minTokenA := sdk.NewCoin("ukava", sdkmath.NewInt(5e6)) - minTokenB := sdk.NewCoin("usdx", sdkmath.NewInt(25e6)) - - withdraw := types.NewMsgWithdraw( - depositor.GetAddress().String(), - sdkmath.NewInt(11180339), - minTokenA, - minTokenB, - time.Now().Add(10*time.Minute).Unix(), - ) - - res, err := suite.msgServer.Withdraw(sdk.WrapSDKContext(suite.Ctx), withdraw) - suite.Require().Nil(res) - suite.EqualError(err, "minimum withdraw not met: slippage exceeded") - suite.Nil(res) -} - -func (suite *msgServerTestSuite) TestWithdraw_DeadlineExceeded() { - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - from := suite.NewAccountFromAddr(sdk.AccAddress("from----------------"), balance) - - withdraw := types.NewMsgWithdraw( - from.GetAddress().String(), - sdkmath.NewInt(2e6), - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - suite.Ctx.BlockTime().Add(-1*time.Second).Unix(), - ) - - res, err := suite.msgServer.Withdraw(sdk.WrapSDKContext(suite.Ctx), withdraw) - suite.Require().Nil(res) - suite.EqualError(err, fmt.Sprintf("block time %d >= deadline %d: deadline exceeded", suite.Ctx.BlockTime().Unix(), withdraw.GetDeadline().Unix())) - suite.Nil(res) -} - -func (suite *msgServerTestSuite) TestSwapExactForTokens() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - err := suite.CreatePool(reserves) - suite.Require().NoError(err) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - swapInput := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - swapMsg := types.NewMsgSwapExactForTokens( - requester.GetAddress().String(), - swapInput, - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - sdk.MustNewDecFromStr("0.01"), - time.Now().Add(10*time.Minute).Unix(), - ) - - suite.Ctx = suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - res, err := suite.msgServer.SwapExactForTokens(sdk.WrapSDKContext(suite.Ctx), swapMsg) - suite.Require().Equal(&types.MsgSwapExactForTokensResponse{}, res) - suite.Require().NoError(err) - - expectedSwapOutput := sdk.NewCoin("usdx", sdkmath.NewInt(4980034)) - - suite.AccountBalanceEqual(requester.GetAddress(), balance.Sub(swapInput).Add(expectedSwapOutput)) - suite.ModuleAccountBalanceEqual(reserves.Add(swapInput).Sub(expectedSwapOutput)) - suite.PoolLiquidityEqual(reserves.Add(swapInput).Sub(expectedSwapOutput)) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, requester.GetAddress().String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - bank.EventTypeTransfer, - sdk.NewAttribute(bank.AttributeKeyRecipient, swapModuleAccountAddress.String()), - sdk.NewAttribute(bank.AttributeKeySender, requester.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, swapInput.String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - bank.EventTypeTransfer, - sdk.NewAttribute(bank.AttributeKeyRecipient, requester.GetAddress().String()), - sdk.NewAttribute(bank.AttributeKeySender, swapModuleAccountAddress.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, expectedSwapOutput.String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - types.EventTypeSwapTrade, - sdk.NewAttribute(types.AttributeKeyPoolID, types.PoolID("ukava", "usdx")), - sdk.NewAttribute(types.AttributeKeyRequester, requester.GetAddress().String()), - sdk.NewAttribute(types.AttributeKeySwapInput, swapInput.String()), - sdk.NewAttribute(types.AttributeKeySwapOutput, expectedSwapOutput.String()), - sdk.NewAttribute(types.AttributeKeyFeePaid, "3000ukava"), - sdk.NewAttribute(types.AttributeKeyExactDirection, "input"), - )) -} - -func (suite *msgServerTestSuite) TestSwapExactForTokens_SlippageFailure() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - err := suite.CreatePool(reserves) - suite.Require().NoError(err) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - swapInput := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - swapMsg := types.NewMsgSwapExactForTokens( - requester.GetAddress().String(), - swapInput, - sdk.NewCoin("usdx", sdkmath.NewInt(5030338)), - sdk.MustNewDecFromStr("0.01"), - time.Now().Add(10*time.Minute).Unix(), - ) - - suite.Ctx = suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - res, err := suite.msgServer.SwapExactForTokens(sdk.WrapSDKContext(suite.Ctx), swapMsg) - suite.Require().Nil(res) - suite.EqualError(err, "slippage 0.010000123252155223 > limit 0.010000000000000000: slippage exceeded") - suite.Nil(res) -} - -func (suite *msgServerTestSuite) TestSwapExactForTokens_DeadlineExceeded() { - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - swapMsg := types.NewMsgSwapExactForTokens( - requester.GetAddress().String(), - sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(25e5)), - sdk.MustNewDecFromStr("0.01"), - suite.Ctx.BlockTime().Add(-1*time.Second).Unix(), - ) - - res, err := suite.msgServer.SwapExactForTokens(sdk.WrapSDKContext(suite.Ctx), swapMsg) - suite.Require().Nil(res) - suite.EqualError(err, fmt.Sprintf("block time %d >= deadline %d: deadline exceeded", suite.Ctx.BlockTime().Unix(), swapMsg.GetDeadline().Unix())) - suite.Nil(res) -} - -func (suite *msgServerTestSuite) TestSwapForExactTokens() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - err := suite.CreatePool(reserves) - suite.Require().NoError(err) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - swapOutput := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - swapMsg := types.NewMsgSwapForExactTokens( - requester.GetAddress().String(), - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - swapOutput, - sdk.MustNewDecFromStr("0.01"), - time.Now().Add(10*time.Minute).Unix(), - ) - - suite.Ctx = suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - res, err := suite.msgServer.SwapForExactTokens(sdk.WrapSDKContext(suite.Ctx), swapMsg) - suite.Require().Equal(&types.MsgSwapForExactTokensResponse{}, res) - suite.Require().NoError(err) - - expectedSwapInput := sdk.NewCoin("ukava", sdkmath.NewInt(1004015)) - - suite.AccountBalanceEqual(requester.GetAddress(), balance.Sub(expectedSwapInput).Add(swapOutput)) - suite.ModuleAccountBalanceEqual(reserves.Add(expectedSwapInput).Sub(swapOutput)) - suite.PoolLiquidityEqual(reserves.Add(expectedSwapInput).Sub(swapOutput)) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), - sdk.NewAttribute(sdk.AttributeKeySender, requester.GetAddress().String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - bank.EventTypeTransfer, - sdk.NewAttribute(bank.AttributeKeyRecipient, swapModuleAccountAddress.String()), - sdk.NewAttribute(bank.AttributeKeySender, requester.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, expectedSwapInput.String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - bank.EventTypeTransfer, - sdk.NewAttribute(bank.AttributeKeyRecipient, requester.GetAddress().String()), - sdk.NewAttribute(bank.AttributeKeySender, swapModuleAccountAddress.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, swapOutput.String()), - )) - - suite.EventsContains(suite.GetEvents(), sdk.NewEvent( - types.EventTypeSwapTrade, - sdk.NewAttribute(types.AttributeKeyPoolID, types.PoolID("ukava", "usdx")), - sdk.NewAttribute(types.AttributeKeyRequester, requester.GetAddress().String()), - sdk.NewAttribute(types.AttributeKeySwapInput, expectedSwapInput.String()), - sdk.NewAttribute(types.AttributeKeySwapOutput, swapOutput.String()), - sdk.NewAttribute(types.AttributeKeyFeePaid, "3013ukava"), - sdk.NewAttribute(types.AttributeKeyExactDirection, "output"), - )) -} - -func (suite *msgServerTestSuite) TestSwapForExactTokens_SlippageFailure() { - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - err := suite.CreatePool(reserves) - suite.Require().NoError(err) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - swapOutput := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - swapMsg := types.NewMsgSwapForExactTokens( - requester.GetAddress().String(), - sdk.NewCoin("ukava", sdkmath.NewInt(990991)), - swapOutput, - sdk.MustNewDecFromStr("0.01"), - time.Now().Add(10*time.Minute).Unix(), - ) - - suite.Ctx = suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - res, err := suite.msgServer.SwapForExactTokens(sdk.WrapSDKContext(suite.Ctx), swapMsg) - suite.Require().Nil(res) - suite.EqualError(err, "slippage 0.010000979019022939 > limit 0.010000000000000000: slippage exceeded") - suite.Nil(res) -} - -func (suite *msgServerTestSuite) TestSwapForExactTokens_DeadlineExceeded() { - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - swapMsg := types.NewMsgSwapForExactTokens( - requester.GetAddress().String(), - sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(25e5)), - sdk.MustNewDecFromStr("0.01"), - suite.Ctx.BlockTime().Add(-1*time.Second).Unix(), - ) - - res, err := suite.msgServer.SwapForExactTokens(sdk.WrapSDKContext(suite.Ctx), swapMsg) - suite.Require().Nil(res) - suite.EqualError(err, fmt.Sprintf("block time %d >= deadline %d: deadline exceeded", suite.Ctx.BlockTime().Unix(), swapMsg.GetDeadline().Unix())) - suite.Nil(res) -} - -func TestMsgServerTestSuite(t *testing.T) { - suite.Run(t, new(msgServerTestSuite)) -} diff --git a/x/swap/keeper/swap.go b/x/swap/keeper/swap.go deleted file mode 100644 index e7a8def0..00000000 --- a/x/swap/keeper/swap.go +++ /dev/null @@ -1,122 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/0glabs/0g-chain/x/swap/types" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// SwapExactForTokens swaps an exact coin a input for a coin b output -func (k *Keeper) SwapExactForTokens(ctx sdk.Context, requester sdk.AccAddress, exactCoinA, coinB sdk.Coin, slippageLimit sdk.Dec) error { - poolID, pool, err := k.loadPool(ctx, exactCoinA.Denom, coinB.Denom) - if err != nil { - return err - } - - swapOutput, feePaid := pool.SwapWithExactInput(exactCoinA, k.GetSwapFee(ctx)) - if swapOutput.IsZero() { - return errorsmod.Wrapf(types.ErrInsufficientLiquidity, "swap output rounds to zero, increase input amount") - } - - priceChange := sdk.NewDecFromInt(swapOutput.Amount).Quo(sdk.NewDecFromInt(coinB.Amount)) - if err := k.assertSlippageWithinLimit(priceChange, slippageLimit); err != nil { - return err - } - - if err := k.commitSwap(ctx, poolID, pool, requester, exactCoinA, swapOutput, feePaid, "input"); err != nil { - return err - } - - return nil -} - -// SwapForExactTokens swaps a coin a input for an exact coin b output -func (k *Keeper) SwapForExactTokens(ctx sdk.Context, requester sdk.AccAddress, coinA, exactCoinB sdk.Coin, slippageLimit sdk.Dec) error { - poolID, pool, err := k.loadPool(ctx, coinA.Denom, exactCoinB.Denom) - if err != nil { - return err - } - - if exactCoinB.Amount.GTE(pool.Reserves().AmountOf(exactCoinB.Denom)) { - return errorsmod.Wrapf( - types.ErrInsufficientLiquidity, - "output %s >= pool reserves %s", exactCoinB.Amount.String(), pool.Reserves().AmountOf(exactCoinB.Denom).String(), - ) - } - - swapInput, feePaid := pool.SwapWithExactOutput(exactCoinB, k.GetSwapFee(ctx)) - - priceChange := sdk.NewDecFromInt(coinA.Amount).Quo(sdk.NewDecFromInt(swapInput.Sub(feePaid).Amount)) - if err := k.assertSlippageWithinLimit(priceChange, slippageLimit); err != nil { - return err - } - - if err := k.commitSwap(ctx, poolID, pool, requester, swapInput, exactCoinB, feePaid, "output"); err != nil { - return err - } - - return nil -} - -func (k Keeper) loadPool(ctx sdk.Context, denomA string, denomB string) (string, *types.DenominatedPool, error) { - poolID := types.PoolID(denomA, denomB) - - poolRecord, found := k.GetPool(ctx, poolID) - if !found { - return poolID, nil, errorsmod.Wrapf(types.ErrInvalidPool, "pool %s not found", poolID) - } - - pool, err := types.NewDenominatedPoolWithExistingShares(poolRecord.Reserves(), poolRecord.TotalShares) - if err != nil { - panic(fmt.Sprintf("invalid pool %s: %s", poolID, err)) - } - - return poolID, pool, nil -} - -func (k Keeper) assertSlippageWithinLimit(priceChange sdk.Dec, slippageLimit sdk.Dec) error { - slippage := sdk.OneDec().Sub(priceChange) - if slippage.GT(slippageLimit) { - return errorsmod.Wrapf(types.ErrSlippageExceeded, "slippage %s > limit %s", slippage, slippageLimit) - } - - return nil -} - -func (k Keeper) commitSwap( - ctx sdk.Context, - poolID string, - pool *types.DenominatedPool, - requester sdk.AccAddress, - swapInput sdk.Coin, - swapOutput sdk.Coin, - feePaid sdk.Coin, - exactDirection string, -) error { - k.SetPool(ctx, types.NewPoolRecordFromPool(pool)) - - if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, requester, types.ModuleAccountName, sdk.NewCoins(swapInput)); err != nil { - return err - } - - if err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, requester, sdk.NewCoins(swapOutput)); err != nil { - panic(err) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeSwapTrade, - sdk.NewAttribute(types.AttributeKeyPoolID, poolID), - sdk.NewAttribute(types.AttributeKeyRequester, requester.String()), - sdk.NewAttribute(types.AttributeKeySwapInput, swapInput.String()), - sdk.NewAttribute(types.AttributeKeySwapOutput, swapOutput.String()), - sdk.NewAttribute(types.AttributeKeyFeePaid, feePaid.String()), - sdk.NewAttribute(types.AttributeKeyExactDirection, exactDirection), - ), - ) - - return nil -} diff --git a/x/swap/keeper/swap_test.go b/x/swap/keeper/swap_test.go deleted file mode 100644 index 3a47ddcb..00000000 --- a/x/swap/keeper/swap_test.go +++ /dev/null @@ -1,631 +0,0 @@ -package keeper_test - -import ( - "errors" - "fmt" - - sdkmath "cosmossdk.io/math" - "github.com/0glabs/0g-chain/x/swap/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -func (suite *keeperTestSuite) TestSwapExactForTokens() { - suite.Keeper.SetParams(suite.Ctx, types.Params{ - SwapFee: sdk.MustNewDecFromStr("0.0025"), - }) - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - totalShares := sdkmath.NewInt(30e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - coinB := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - - err := suite.Keeper.SwapExactForTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - suite.Require().NoError(err) - - expectedOutput := sdk.NewCoin("usdx", sdkmath.NewInt(4982529)) - - suite.AccountBalanceEqual(requester.GetAddress(), balance.Sub(coinA).Add(expectedOutput)) - suite.ModuleAccountBalanceEqual(reserves.Add(coinA).Sub(expectedOutput)) - suite.PoolLiquidityEqual(reserves.Add(coinA).Sub(expectedOutput)) - - suite.EventsContains(suite.Ctx.EventManager().Events(), sdk.NewEvent( - types.EventTypeSwapTrade, - sdk.NewAttribute(types.AttributeKeyPoolID, poolID), - sdk.NewAttribute(types.AttributeKeyRequester, requester.GetAddress().String()), - sdk.NewAttribute(types.AttributeKeySwapInput, coinA.String()), - sdk.NewAttribute(types.AttributeKeySwapOutput, expectedOutput.String()), - sdk.NewAttribute(types.AttributeKeyFeePaid, "2500ukava"), - sdk.NewAttribute(types.AttributeKeyExactDirection, "input"), - )) -} - -func (suite *keeperTestSuite) TestSwapExactForTokens_OutputGreaterThanZero() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - balance := sdk.NewCoins( - sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("usdx", sdkmath.NewInt(5)) - coinB := sdk.NewCoin("ukava", sdkmath.NewInt(1)) - - err := suite.Keeper.SwapExactForTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("1")) - suite.EqualError(err, "swap output rounds to zero, increase input amount: insufficient liquidity") -} - -func (suite *keeperTestSuite) TestSwapExactForTokens_Slippage() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), - ) - totalShares := sdkmath.NewInt(30e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - testCases := []struct { - coinA sdk.Coin - coinB sdk.Coin - slippage sdk.Dec - fee sdk.Dec - shouldFail bool - }{ - // positive slippage OK - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(2e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.0025"), false}, - // positive slippage with zero slippage OK - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(2e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.0025"), false}, - // exact zero slippage OK - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4950495)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4935790)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.003"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4705299)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.05"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(990099)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(987158)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.003"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(941059)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.05"), false}, - // slippage failure, zero slippage tolerance - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4950496)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4935793)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.003"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4705300)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.05"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(990100)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(987159)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.003"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(941060)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.05"), true}, - // slippage failure, 1 percent slippage - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000501)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4985647)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.003"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4752828)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.05"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000101)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(997130)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.003"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(950565)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.05"), true}, - // slippage OK, 1 percent slippage - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000500)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4985646)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.003"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(4752827)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.05"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000100)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(997129)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.003"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.NewCoin("ukava", sdkmath.NewInt(950564)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.05"), false}, - } - - for _, tc := range testCases { - suite.Run(fmt.Sprintf("coinA=%s coinB=%s slippage=%s fee=%s", tc.coinA, tc.coinB, tc.slippage, tc.fee), func() { - suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.Params{ - SwapFee: tc.fee, - }) - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), - ) - totalShares := sdkmath.NewInt(30e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(100e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - ctx := suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - err := suite.Keeper.SwapExactForTokens(ctx, requester.GetAddress(), tc.coinA, tc.coinB, tc.slippage) - - if tc.shouldFail { - suite.Require().Error(err) - suite.Contains(err.Error(), "slippage exceeded") - } else { - suite.NoError(err) - } - }) - } -} - -func (suite *keeperTestSuite) TestSwapExactForTokens_InsufficientFunds() { - testCases := []struct { - name string - balanceA sdk.Coin - coinA sdk.Coin - coinB sdk.Coin - }{ - {"no ukava balance", sdk.NewCoin("ukava", sdk.ZeroInt()), sdk.NewCoin("ukava", sdkmath.NewInt(100)), sdk.NewCoin("usdx", sdkmath.NewInt(500))}, - {"no usdx balance", sdk.NewCoin("usdx", sdk.ZeroInt()), sdk.NewCoin("usdx", sdkmath.NewInt(500)), sdk.NewCoin("ukava", sdkmath.NewInt(100))}, - {"low ukava balance", sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), sdk.NewCoin("ukava", sdkmath.NewInt(1000001)), sdk.NewCoin("usdx", sdkmath.NewInt(5000000))}, - {"low ukava balance", sdk.NewCoin("usdx", sdkmath.NewInt(5000000)), sdk.NewCoin("usdx", sdkmath.NewInt(5000001)), sdk.NewCoin("ukava", sdkmath.NewInt(1000000))}, - {"large ukava balance difference", sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000e6))}, - {"large usdx balance difference", sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000e6))}, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(500000e6)), - ) - totalShares := sdkmath.NewInt(30000e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - balance := sdk.NewCoins(tc.balanceA) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - ctx := suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - err := suite.Keeper.SwapExactForTokens(ctx, requester.GetAddress(), tc.coinA, tc.coinB, sdk.MustNewDecFromStr("0.1")) - suite.Require().True(errors.Is(err, sdkerrors.ErrInsufficientFunds), fmt.Sprintf("got err %s", err)) - }) - } -} - -func (suite *keeperTestSuite) TestSwapExactForTokens_InsufficientFunds_Vesting() { - testCases := []struct { - name string - balanceA sdk.Coin - vestingA sdk.Coin - coinA sdk.Coin - coinB sdk.Coin - }{ - {"no ukava balance, vesting only", sdk.NewCoin("ukava", sdk.ZeroInt()), sdk.NewCoin("ukava", sdkmath.NewInt(100)), sdk.NewCoin("ukava", sdkmath.NewInt(100)), sdk.NewCoin("usdx", sdkmath.NewInt(500))}, - {"no usdx balance, vesting only", sdk.NewCoin("usdx", sdk.ZeroInt()), sdk.NewCoin("usdx", sdkmath.NewInt(500)), sdk.NewCoin("usdx", sdkmath.NewInt(500)), sdk.NewCoin("ukava", sdkmath.NewInt(100))}, - {"low ukava balance, vesting matches exact", sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("ukava", sdkmath.NewInt(1000001)), sdk.NewCoin("usdx", sdkmath.NewInt(5000000))}, - {"low ukava balance, vesting matches exact", sdk.NewCoin("usdx", sdkmath.NewInt(5000000)), sdk.NewCoin("usdx", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(5000001)), sdk.NewCoin("ukava", sdkmath.NewInt(1000000))}, - {"large ukava balance difference, vesting covers difference", sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000e6))}, - {"large usdx balance difference, vesting covers difference", sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000e6))}, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(500000e6)), - ) - totalShares := sdkmath.NewInt(30000e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - balance := sdk.NewCoins(tc.balanceA) - vesting := sdk.NewCoins(tc.vestingA) - requester := suite.CreateVestingAccount(balance, vesting) - - ctx := suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - err := suite.Keeper.SwapExactForTokens(ctx, requester.GetAddress(), tc.coinA, tc.coinB, sdk.MustNewDecFromStr("0.1")) - suite.Require().True(errors.Is(err, sdkerrors.ErrInsufficientFunds), fmt.Sprintf("got err %s", err)) - }) - } -} - -func (suite *keeperTestSuite) TestSwapExactForTokens_PoolNotFound() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - totalShares := sdkmath.NewInt(3000e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - suite.Keeper.DeletePool(suite.Ctx, poolID) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - coinB := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - - err := suite.Keeper.SwapExactForTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - suite.EqualError(err, "pool ukava:usdx not found: invalid pool") - - err = suite.Keeper.SwapExactForTokens(suite.Ctx, requester.GetAddress(), coinB, coinA, sdk.MustNewDecFromStr("0.01")) - suite.EqualError(err, "pool ukava:usdx not found: invalid pool") -} - -func (suite *keeperTestSuite) TestSwapExactForTokens_PanicOnInvalidPool() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - totalShares := sdkmath.NewInt(3000e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - - poolRecord, found := suite.Keeper.GetPool(suite.Ctx, poolID) - suite.Require().True(found, "expected pool record to exist") - - poolRecord.TotalShares = sdk.ZeroInt() - suite.Keeper.SetPool_Raw(suite.Ctx, poolRecord) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - coinB := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - - suite.PanicsWithValue("invalid pool ukava:usdx: total shares must be greater than zero: invalid pool", func() { - _ = suite.Keeper.SwapExactForTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - }, "expected invalid pool record to panic") - - suite.PanicsWithValue("invalid pool ukava:usdx: total shares must be greater than zero: invalid pool", func() { - _ = suite.Keeper.SwapExactForTokens(suite.Ctx, requester.GetAddress(), coinB, coinA, sdk.MustNewDecFromStr("0.01")) - }, "expected invalid pool record to panic") -} - -func (suite *keeperTestSuite) TestSwapExactForTokens_PanicOnInsufficientModuleAccFunds() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - totalShares := sdkmath.NewInt(3000e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - suite.RemoveCoinsFromModule(sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - )) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - coinB := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - - suite.Panics(func() { - _ = suite.Keeper.SwapExactForTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - }, "expected panic when module account does not have enough funds") - - suite.Panics(func() { - _ = suite.Keeper.SwapExactForTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - }, "expected panic when module account does not have enough funds") -} - -func (suite *keeperTestSuite) TestSwapForExactTokens() { - suite.Keeper.SetParams(suite.Ctx, types.Params{ - SwapFee: sdk.MustNewDecFromStr("0.0025"), - }) - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - totalShares := sdkmath.NewInt(30e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - coinB := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - - err := suite.Keeper.SwapForExactTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - suite.Require().NoError(err) - - expectedInput := sdk.NewCoin("ukava", sdkmath.NewInt(1003511)) - - suite.AccountBalanceEqual(requester.GetAddress(), balance.Sub(expectedInput).Add(coinB)) - suite.ModuleAccountBalanceEqual(reserves.Add(expectedInput).Sub(coinB)) - suite.PoolLiquidityEqual(reserves.Add(expectedInput).Sub(coinB)) - - suite.EventsContains(suite.Ctx.EventManager().Events(), sdk.NewEvent( - types.EventTypeSwapTrade, - sdk.NewAttribute(types.AttributeKeyPoolID, poolID), - sdk.NewAttribute(types.AttributeKeyRequester, requester.GetAddress().String()), - sdk.NewAttribute(types.AttributeKeySwapInput, expectedInput.String()), - sdk.NewAttribute(types.AttributeKeySwapOutput, coinB.String()), - sdk.NewAttribute(types.AttributeKeyFeePaid, "2509ukava"), - sdk.NewAttribute(types.AttributeKeyExactDirection, "output"), - )) -} - -func (suite *keeperTestSuite) TestSwapForExactTokens_OutputLessThanPoolReserves() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), - ) - totalShares := sdkmath.NewInt(300e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - - coinB := sdk.NewCoin("usdx", sdkmath.NewInt(500e6).Add(sdk.OneInt())) - err := suite.Keeper.SwapForExactTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - suite.EqualError(err, "output 500000001 >= pool reserves 500000000: insufficient liquidity") - - coinB = sdk.NewCoin("usdx", sdkmath.NewInt(500e6)) - err = suite.Keeper.SwapForExactTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - suite.EqualError(err, "output 500000000 >= pool reserves 500000000: insufficient liquidity") -} - -func (suite *keeperTestSuite) TestSwapForExactTokens_Slippage() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), - ) - totalShares := sdkmath.NewInt(30e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - testCases := []struct { - coinA sdk.Coin - coinB sdk.Coin - slippage sdk.Dec - fee sdk.Dec - shouldFail bool - }{ - // positive slippage OK - {sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(100e6)), sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(100e6)), sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.0025"), false}, - // positive slippage with zero slippage OK - {sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(5e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(100e6)), sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.0025"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(100e6)), sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.0025"), false}, - // exact zero slippage OK - {sdk.NewCoin("ukava", sdkmath.NewInt(1010102)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1010102)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.003"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1010102)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.05"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5050506)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5050506)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.003"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5050506)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.05"), false}, - // slippage failure, zero slippage tolerance - {sdk.NewCoin("ukava", sdkmath.NewInt(1010101)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1010101)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.003"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1010101)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.05"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5050505)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5050505)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.003"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5050505)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.ZeroDec(), sdk.MustNewDecFromStr("0.05"), true}, - // slippage failure, 1 percent slippage - {sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.003"), true}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.05"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5000000)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5000000)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.003"), true}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5000000)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.05"), true}, - // slippage OK, 1 percent slippage - {sdk.NewCoin("ukava", sdkmath.NewInt(1000001)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1000001)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.003"), false}, - {sdk.NewCoin("ukava", sdkmath.NewInt(1000001)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.05"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5000001)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5000001)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.003"), false}, - {sdk.NewCoin("usdx", sdkmath.NewInt(5000001)), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.MustNewDecFromStr("0.01"), sdk.MustNewDecFromStr("0.05"), false}, - } - - for _, tc := range testCases { - suite.Run(fmt.Sprintf("coinA=%s coinB=%s slippage=%s fee=%s", tc.coinA, tc.coinB, tc.slippage, tc.fee), func() { - suite.SetupTest() - suite.Keeper.SetParams(suite.Ctx, types.Params{ - SwapFee: tc.fee, - }) - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), - ) - totalShares := sdkmath.NewInt(30e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(100e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - ctx := suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - err := suite.Keeper.SwapForExactTokens(ctx, requester.GetAddress(), tc.coinA, tc.coinB, tc.slippage) - - if tc.shouldFail { - suite.Require().Error(err) - suite.Contains(err.Error(), "slippage exceeded") - } else { - suite.NoError(err) - } - }) - } -} - -func (suite *keeperTestSuite) TestSwapForExactTokens_InsufficientFunds() { - testCases := []struct { - name string - balanceA sdk.Coin - coinA sdk.Coin - coinB sdk.Coin - }{ - {"no ukava balance", sdk.NewCoin("ukava", sdk.ZeroInt()), sdk.NewCoin("ukava", sdkmath.NewInt(100)), sdk.NewCoin("usdx", sdkmath.NewInt(500))}, - {"no usdx balance", sdk.NewCoin("usdx", sdk.ZeroInt()), sdk.NewCoin("usdx", sdkmath.NewInt(500)), sdk.NewCoin("ukava", sdkmath.NewInt(100))}, - {"low ukava balance", sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), sdk.NewCoin("usdx", sdkmath.NewInt(5000000))}, - {"low ukava balance", sdk.NewCoin("usdx", sdkmath.NewInt(5000000)), sdk.NewCoin("usdx", sdkmath.NewInt(5000000)), sdk.NewCoin("ukava", sdkmath.NewInt(1000000))}, - {"large ukava balance difference", sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000e6))}, - {"large usdx balance difference", sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000e6))}, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(500000e6)), - ) - totalShares := sdkmath.NewInt(30000e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - balance := sdk.NewCoins(tc.balanceA) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - - ctx := suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - err := suite.Keeper.SwapForExactTokens(ctx, requester.GetAddress(), tc.coinA, tc.coinB, sdk.MustNewDecFromStr("0.1")) - suite.Require().True(errors.Is(err, sdkerrors.ErrInsufficientFunds), fmt.Sprintf("got err %s", err)) - }) - } -} - -func (suite *keeperTestSuite) TestSwapForExactTokens_InsufficientFunds_Vesting() { - testCases := []struct { - name string - balanceA sdk.Coin - vestingA sdk.Coin - coinA sdk.Coin - coinB sdk.Coin - }{ - {"no ukava balance, vesting only", sdk.NewCoin("ukava", sdk.ZeroInt()), sdk.NewCoin("ukava", sdkmath.NewInt(100)), sdk.NewCoin("ukava", sdkmath.NewInt(1000)), sdk.NewCoin("usdx", sdkmath.NewInt(500))}, - {"no usdx balance, vesting only", sdk.NewCoin("usdx", sdk.ZeroInt()), sdk.NewCoin("usdx", sdkmath.NewInt(500)), sdk.NewCoin("usdx", sdkmath.NewInt(5000)), sdk.NewCoin("ukava", sdkmath.NewInt(100))}, - {"low ukava balance, vesting matches exact", sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), sdk.NewCoin("ukava", sdkmath.NewInt(100000)), sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), sdk.NewCoin("usdx", sdkmath.NewInt(5000000))}, - {"low ukava balance, vesting matches exact", sdk.NewCoin("usdx", sdkmath.NewInt(5000000)), sdk.NewCoin("usdx", sdkmath.NewInt(500000)), sdk.NewCoin("usdx", sdkmath.NewInt(5000000)), sdk.NewCoin("ukava", sdkmath.NewInt(1000000))}, - {"large ukava balance difference, vesting covers difference", sdk.NewCoin("ukava", sdkmath.NewInt(100e6)), sdk.NewCoin("ukava", sdkmath.NewInt(10000e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000e6))}, - {"large usdx balance difference, vesting covers difference", sdk.NewCoin("usdx", sdkmath.NewInt(500e6)), sdk.NewCoin("usdx", sdkmath.NewInt(500000e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), sdk.NewCoin("ukava", sdkmath.NewInt(1000e6))}, - } - - for _, tc := range testCases { - suite.Run(tc.name, func() { - suite.SetupTest() - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(100000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(500000e6)), - ) - totalShares := sdkmath.NewInt(30000e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - balance := sdk.NewCoins(tc.balanceA) - vesting := sdk.NewCoins(tc.vestingA) - requester := suite.CreateVestingAccount(balance, vesting) - - ctx := suite.App.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - err := suite.Keeper.SwapForExactTokens(ctx, requester.GetAddress(), tc.coinA, tc.coinB, sdk.MustNewDecFromStr("0.1")) - suite.Require().True(errors.Is(err, sdkerrors.ErrInsufficientFunds), fmt.Sprintf("got err %s", err)) - }) - } -} - -func (suite *keeperTestSuite) TestSwapForExactTokens_PoolNotFound() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - totalShares := sdkmath.NewInt(3000e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - suite.Keeper.DeletePool(suite.Ctx, poolID) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - coinB := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - - err := suite.Keeper.SwapForExactTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - suite.EqualError(err, "pool ukava:usdx not found: invalid pool") - - err = suite.Keeper.SwapForExactTokens(suite.Ctx, requester.GetAddress(), coinB, coinA, sdk.MustNewDecFromStr("0.01")) - suite.EqualError(err, "pool ukava:usdx not found: invalid pool") -} - -func (suite *keeperTestSuite) TestSwapForExactTokens_PanicOnInvalidPool() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - totalShares := sdkmath.NewInt(3000e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - - poolRecord, found := suite.Keeper.GetPool(suite.Ctx, poolID) - suite.Require().True(found, "expected pool record to exist") - - poolRecord.TotalShares = sdk.ZeroInt() - suite.Keeper.SetPool_Raw(suite.Ctx, poolRecord) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - coinB := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - - suite.PanicsWithValue("invalid pool ukava:usdx: total shares must be greater than zero: invalid pool", func() { - _ = suite.Keeper.SwapForExactTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - }, "expected invalid pool record to panic") - - suite.PanicsWithValue("invalid pool ukava:usdx: total shares must be greater than zero: invalid pool", func() { - _ = suite.Keeper.SwapForExactTokens(suite.Ctx, requester.GetAddress(), coinB, coinA, sdk.MustNewDecFromStr("0.01")) - }, "expected invalid pool record to panic") -} - -func (suite *keeperTestSuite) TestSwapForExactTokens_PanicOnInsufficientModuleAccFunds() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - ) - totalShares := sdkmath.NewInt(3000e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - suite.RemoveCoinsFromModule(sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1000e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5000e6)), - )) - - balance := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(10e6)), - ) - requester := suite.NewAccountFromAddr(sdk.AccAddress("requester-----------"), balance) - coinA := sdk.NewCoin("ukava", sdkmath.NewInt(1e6)) - coinB := sdk.NewCoin("usdx", sdkmath.NewInt(5e6)) - - suite.Panics(func() { - _ = suite.Keeper.SwapForExactTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - }, "expected panic when module account does not have enough funds") - - suite.Panics(func() { - _ = suite.Keeper.SwapForExactTokens(suite.Ctx, requester.GetAddress(), coinA, coinB, sdk.MustNewDecFromStr("0.01")) - }, "expected panic when module account does not have enough funds") -} diff --git a/x/swap/keeper/withdraw.go b/x/swap/keeper/withdraw.go deleted file mode 100644 index bd45f452..00000000 --- a/x/swap/keeper/withdraw.go +++ /dev/null @@ -1,75 +0,0 @@ -package keeper - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/0glabs/0g-chain/x/swap/types" -) - -// Withdraw removes liquidity from an existing pool from an owners deposit, converting the provided shares for -// the returned pool liquidity. -// -// If 100% of the owners shares are removed, then the deposit is deleted. In addition, if all the pool shares -// are removed then the pool is deleted. -// -// The number of shares must be large enough to result in at least 1 unit of the smallest reserve in the pool. -// If the share input is below the minimum required for positive liquidity to be remove from both reserves, a -// insufficient error is returned. -// -// In addition, if the withdrawn liquidity for each reserve is below the provided minimum, a slippage exceeded -// error is returned. -func (k Keeper) Withdraw(ctx sdk.Context, owner sdk.AccAddress, shares sdkmath.Int, minCoinA, minCoinB sdk.Coin) error { - poolID := types.PoolID(minCoinA.Denom, minCoinB.Denom) - - shareRecord, found := k.GetDepositorShares(ctx, owner, poolID) - if !found { - return errorsmod.Wrapf(types.ErrDepositNotFound, "no deposit for account %s and pool %s", owner, poolID) - } - - if shares.GT(shareRecord.SharesOwned) { - return errorsmod.Wrapf(types.ErrInvalidShares, "withdraw of %s shares greater than %s shares owned", shares, shareRecord.SharesOwned) - } - - poolRecord, found := k.GetPool(ctx, poolID) - if !found { - panic(fmt.Sprintf("pool %s not found", poolID)) - } - - pool, err := types.NewDenominatedPoolWithExistingShares(poolRecord.Reserves(), poolRecord.TotalShares) - if err != nil { - panic(fmt.Sprintf("invalid pool %s: %s", poolID, err)) - } - - withdrawnAmount := pool.RemoveLiquidity(shares) - if withdrawnAmount.AmountOf(minCoinA.Denom).IsZero() || withdrawnAmount.AmountOf(minCoinB.Denom).IsZero() { - return errorsmod.Wrap(types.ErrInsufficientLiquidity, "shares must be increased") - } - if withdrawnAmount.AmountOf(minCoinA.Denom).LT(minCoinA.Amount) || withdrawnAmount.AmountOf(minCoinB.Denom).LT(minCoinB.Amount) { - return errorsmod.Wrap(types.ErrSlippageExceeded, "minimum withdraw not met") - } - - k.updatePool(ctx, poolID, pool) - k.BeforePoolDepositModified(ctx, poolID, owner, shareRecord.SharesOwned) - k.updateDepositorShares(ctx, owner, poolID, shareRecord.SharesOwned.Sub(shares)) - - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleAccountName, owner, withdrawnAmount) - if err != nil { - panic(err) - } - - ctx.EventManager().EmitEvent( - sdk.NewEvent( - types.EventTypeSwapWithdraw, - sdk.NewAttribute(types.AttributeKeyPoolID, poolID), - sdk.NewAttribute(types.AttributeKeyOwner, owner.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, withdrawnAmount.String()), - sdk.NewAttribute(types.AttributeKeyShares, shares.String()), - ), - ) - - return nil -} diff --git a/x/swap/keeper/withdraw_test.go b/x/swap/keeper/withdraw_test.go deleted file mode 100644 index adcda9ac..00000000 --- a/x/swap/keeper/withdraw_test.go +++ /dev/null @@ -1,224 +0,0 @@ -package keeper_test - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - "github.com/0glabs/0g-chain/x/swap/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func (suite *keeperTestSuite) TestWithdraw_AllShares() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - - err := suite.Keeper.Withdraw(suite.Ctx, owner.GetAddress(), totalShares, reserves[0], reserves[1]) - suite.Require().NoError(err) - - suite.PoolDeleted(reserves[0].Denom, reserves[1].Denom) - suite.PoolSharesDeleted(owner.GetAddress(), reserves[0].Denom, reserves[1].Denom) - suite.AccountBalanceEqual(owner.GetAddress(), reserves) - suite.ModuleAccountBalanceEqual(sdk.Coins{}) - - suite.EventsContains(suite.Ctx.EventManager().Events(), sdk.NewEvent( - types.EventTypeSwapWithdraw, - sdk.NewAttribute(types.AttributeKeyPoolID, poolID), - sdk.NewAttribute(types.AttributeKeyOwner, owner.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, reserves.String()), - sdk.NewAttribute(types.AttributeKeyShares, totalShares.String()), - )) -} - -func (suite *keeperTestSuite) TestWithdraw_PartialShares() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - - sharesToWithdraw := sdkmath.NewInt(15e6) - minCoinA := sdk.NewCoin("usdx", sdkmath.NewInt(25e6)) - minCoinB := sdk.NewCoin("ukava", sdkmath.NewInt(5e6)) - - err := suite.Keeper.Withdraw(suite.Ctx, owner.GetAddress(), sharesToWithdraw, minCoinA, minCoinB) - suite.Require().NoError(err) - - sharesLeft := totalShares.Sub(sharesToWithdraw) - reservesLeft := sdk.NewCoins(reserves[0].Sub(minCoinB), reserves[1].Sub(minCoinA)) - - suite.PoolShareTotalEqual(poolID, sharesLeft) - suite.PoolDepositorSharesEqual(owner.GetAddress(), poolID, sharesLeft) - suite.PoolReservesEqual(poolID, reservesLeft) - suite.AccountBalanceEqual(owner.GetAddress(), sdk.NewCoins(minCoinA, minCoinB)) - suite.ModuleAccountBalanceEqual(reservesLeft) - - suite.EventsContains(suite.Ctx.EventManager().Events(), sdk.NewEvent( - types.EventTypeSwapWithdraw, - sdk.NewAttribute(types.AttributeKeyPoolID, poolID), - sdk.NewAttribute(types.AttributeKeyOwner, owner.GetAddress().String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, sdk.NewCoins(minCoinA, minCoinB).String()), - sdk.NewAttribute(types.AttributeKeyShares, sharesToWithdraw.String()), - )) -} - -func (suite *keeperTestSuite) TestWithdraw_NoSharesOwned() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - - accWithNoDeposit := sdk.AccAddress("some account") - - err := suite.Keeper.Withdraw(suite.Ctx, accWithNoDeposit, totalShares, reserves[0], reserves[1]) - suite.EqualError(err, fmt.Sprintf("no deposit for account %s and pool %s: deposit not found", accWithNoDeposit.String(), poolID)) -} - -func (suite *keeperTestSuite) TestWithdraw_GreaterThanSharesOwned() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - sharesToWithdraw := totalShares.Add(sdk.OneInt()) - err := suite.Keeper.Withdraw(suite.Ctx, owner.GetAddress(), sharesToWithdraw, reserves[0], reserves[1]) - suite.EqualError(err, fmt.Sprintf("withdraw of %s shares greater than %s shares owned: invalid shares", sharesToWithdraw, totalShares)) -} - -func (suite *keeperTestSuite) TestWithdraw_MinWithdraw() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - - testCases := []struct { - shares sdkmath.Int - minCoinA sdk.Coin - minCoinB sdk.Coin - shouldFail bool - }{ - {sdkmath.NewInt(1), sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(1)), true}, - {sdkmath.NewInt(1), sdk.NewCoin("usdx", sdkmath.NewInt(5)), sdk.NewCoin("ukava", sdkmath.NewInt(1)), true}, - - {sdkmath.NewInt(2), sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(1)), true}, - {sdkmath.NewInt(2), sdk.NewCoin("usdx", sdkmath.NewInt(5)), sdk.NewCoin("ukava", sdkmath.NewInt(1)), true}, - - {sdkmath.NewInt(3), sdk.NewCoin("ukava", sdkmath.NewInt(1)), sdk.NewCoin("usdx", sdkmath.NewInt(5)), false}, - {sdkmath.NewInt(3), sdk.NewCoin("usdx", sdkmath.NewInt(5)), sdk.NewCoin("ukava", sdkmath.NewInt(1)), false}, - } - - for _, tc := range testCases { - suite.Run(fmt.Sprintf("shares=%s minCoinA=%s minCoinB=%s", tc.shares, tc.minCoinA, tc.minCoinB), func() { - suite.SetupTest() - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - err := suite.Keeper.Withdraw(suite.Ctx, owner.GetAddress(), tc.shares, tc.minCoinA, tc.minCoinB) - if tc.shouldFail { - suite.EqualError(err, "shares must be increased: insufficient liquidity") - } else { - suite.NoError(err, "expected no liquidity error") - } - }) - } -} - -func (suite *keeperTestSuite) TestWithdraw_BelowMinimum() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - - testCases := []struct { - shares sdkmath.Int - minCoinA sdk.Coin - minCoinB sdk.Coin - shouldFail bool - }{ - {sdkmath.NewInt(15e6), sdk.NewCoin("ukava", sdkmath.NewInt(5000001)), sdk.NewCoin("usdx", sdkmath.NewInt(25e6)), true}, - } - - for _, tc := range testCases { - suite.Run(fmt.Sprintf("shares=%s minCoinA=%s minCoinB=%s", tc.shares, tc.minCoinA, tc.minCoinB), func() { - suite.SetupTest() - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - err := suite.Keeper.Withdraw(suite.Ctx, owner.GetAddress(), tc.shares, tc.minCoinA, tc.minCoinB) - if tc.shouldFail { - suite.EqualError(err, "minimum withdraw not met: slippage exceeded") - } else { - suite.NoError(err, "expected no slippage error") - } - }) - } -} - -func (suite *keeperTestSuite) TestWithdraw_PanicOnMissingPool() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - - suite.Keeper.DeletePool(suite.Ctx, poolID) - - suite.PanicsWithValue("pool ukava:usdx not found", func() { - _ = suite.Keeper.Withdraw(suite.Ctx, owner.GetAddress(), totalShares, reserves[0], reserves[1]) - }, "expected missing pool record to panic") -} - -func (suite *keeperTestSuite) TestWithdraw_PanicOnInvalidPool() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - poolID := suite.setupPool(reserves, totalShares, owner.GetAddress()) - - poolRecord, found := suite.Keeper.GetPool(suite.Ctx, poolID) - suite.Require().True(found, "expected pool record to exist") - - poolRecord.TotalShares = sdk.ZeroInt() - suite.Keeper.SetPool_Raw(suite.Ctx, poolRecord) - - suite.PanicsWithValue("invalid pool ukava:usdx: total shares must be greater than zero: invalid pool", func() { - _ = suite.Keeper.Withdraw(suite.Ctx, owner.GetAddress(), totalShares, reserves[0], reserves[1]) - }, "expected invalid pool record to panic") -} - -func (suite *keeperTestSuite) TestWithdraw_PanicOnModuleInsufficientFunds() { - owner := suite.CreateAccount(sdk.Coins{}) - reserves := sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(10e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(50e6)), - ) - totalShares := sdkmath.NewInt(30e6) - suite.setupPool(reserves, totalShares, owner.GetAddress()) - - suite.RemoveCoinsFromModule(sdk.NewCoins( - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - )) - - suite.Panics(func() { - _ = suite.Keeper.Withdraw(suite.Ctx, owner.GetAddress(), totalShares, reserves[0], reserves[1]) - }, "expected panic when module account does not have enough funds") -} diff --git a/x/swap/legacy/v0_15/types.go b/x/swap/legacy/v0_15/types.go deleted file mode 100644 index 95d4d8e6..00000000 --- a/x/swap/legacy/v0_15/types.go +++ /dev/null @@ -1,58 +0,0 @@ -package v0_15 - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // ModuleName name that will be used throughout the module - ModuleName = "swap" -) - -// GenesisState is the state that must be provided at genesis. -type GenesisState struct { - Params Params `json:"params" yaml:"params"` - PoolRecords `json:"pool_records" yaml:"pool_records"` - ShareRecords `json:"share_records" yaml:"share_records"` -} - -// Params are governance parameters for the swap module -type Params struct { - AllowedPools AllowedPools `json:"allowed_pools" yaml:"allowed_pools"` - SwapFee sdk.Dec `json:"swap_fee" yaml:"swap_fee"` -} - -// PoolRecords is a slice of PoolRecord -type PoolRecords []PoolRecord - -// PoolRecord represents the state of a liquidity pool -// and is used to store the state of a denominated pool -type PoolRecord struct { - // primary key - PoolID string `json:"pool_id" yaml:"pool_id"` - ReservesA sdk.Coin `json:"reserves_a" yaml:"reserves_a"` - ReservesB sdk.Coin `json:"reserves_b" yaml:"reserves_b"` - TotalShares sdkmath.Int `json:"total_shares" yaml:"total_shares"` -} - -// ShareRecords is a slice of ShareRecord -type ShareRecords []ShareRecord - -// ShareRecord stores the shares owned for a depositor and pool -type ShareRecord struct { - // primary key - Depositor sdk.AccAddress `json:"depositor" yaml:"depositor"` - // secondary / sort key - PoolID string `json:"pool_id" yaml:"pool_id"` - SharesOwned sdkmath.Int `json:"shares_owned" yaml:"shares_owned"` -} - -// AllowedPools is a slice of AllowedPool -type AllowedPools []AllowedPool - -// AllowedPool defines a tradable pool -type AllowedPool struct { - TokenA string `json:"token_a" yaml:"token_a"` - TokenB string `json:"token_b" yaml:"token_b"` -} diff --git a/x/swap/legacy/v0_16/migrate.go b/x/swap/legacy/v0_16/migrate.go deleted file mode 100644 index bf4546cb..00000000 --- a/x/swap/legacy/v0_16/migrate.go +++ /dev/null @@ -1,54 +0,0 @@ -package v0_16 - -import ( - v015swap "github.com/0glabs/0g-chain/x/swap/legacy/v0_15" - v016swap "github.com/0glabs/0g-chain/x/swap/types" -) - -func migrateParams(params v015swap.Params) v016swap.Params { - allowedPools := make(v016swap.AllowedPools, len(params.AllowedPools)) - for i, pool := range params.AllowedPools { - allowedPools[i] = v016swap.AllowedPool{ - TokenA: pool.TokenA, - TokenB: pool.TokenB, - } - } - return v016swap.Params{ - AllowedPools: allowedPools, - SwapFee: params.SwapFee, - } -} - -func migratePoolRecords(oldRecords v015swap.PoolRecords) v016swap.PoolRecords { - newRecords := make(v016swap.PoolRecords, len(oldRecords)) - for i, oldRecord := range oldRecords { - newRecords[i] = v016swap.PoolRecord{ - PoolID: oldRecord.PoolID, - ReservesA: oldRecord.ReservesA, - ReservesB: oldRecord.ReservesB, - TotalShares: oldRecord.TotalShares, - } - } - return newRecords -} - -func migrateShareRecords(oldRecords v015swap.ShareRecords) v016swap.ShareRecords { - newRecords := make(v016swap.ShareRecords, len(oldRecords)) - for i, oldRecord := range oldRecords { - newRecords[i] = v016swap.ShareRecord{ - Depositor: oldRecord.Depositor, - PoolID: oldRecord.PoolID, - SharesOwned: oldRecord.SharesOwned, - } - } - return newRecords -} - -// Migrate converts v0.15 swap state and returns it in v0.16 format -func Migrate(oldState v015swap.GenesisState) *v016swap.GenesisState { - return &v016swap.GenesisState{ - Params: migrateParams(oldState.Params), - PoolRecords: migratePoolRecords(oldState.PoolRecords), - ShareRecords: migrateShareRecords(oldState.ShareRecords), - } -} diff --git a/x/swap/legacy/v0_16/migrate_test.go b/x/swap/legacy/v0_16/migrate_test.go deleted file mode 100644 index e50439ac..00000000 --- a/x/swap/legacy/v0_16/migrate_test.go +++ /dev/null @@ -1,147 +0,0 @@ -package v0_16 - -import ( - "io/ioutil" - "path/filepath" - "testing" - - sdkmath "cosmossdk.io/math" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - app "github.com/0glabs/0g-chain/app" - v015swap "github.com/0glabs/0g-chain/x/swap/legacy/v0_15" - v016swap "github.com/0glabs/0g-chain/x/swap/types" -) - -type migrateTestSuite struct { - suite.Suite - - addresses []sdk.AccAddress - v15genstate v015swap.GenesisState - cdc codec.Codec - legacyCdc *codec.LegacyAmino -} - -func (s *migrateTestSuite) SetupTest() { - app.SetSDKConfig() - - s.v15genstate = v015swap.GenesisState{ - Params: v015swap.Params{}, - PoolRecords: v015swap.PoolRecords{}, - ShareRecords: v015swap.ShareRecords{}, - } - - config := app.MakeEncodingConfig() - s.cdc = config.Marshaler - - legacyCodec := codec.NewLegacyAmino() - s.legacyCdc = legacyCodec - - _, accAddresses := app.GeneratePrivKeyAddressPairs(10) - s.addresses = accAddresses -} - -func (s *migrateTestSuite) TestMigrate_JSON() { - // Migrate v15 swap to v16 - file := filepath.Join("testdata", "v15-swap.json") - data, err := ioutil.ReadFile(file) - s.Require().NoError(err) - err = s.legacyCdc.UnmarshalJSON(data, &s.v15genstate) - s.Require().NoError(err) - genstate := Migrate(s.v15genstate) - - // Compare expect v16 swap json with migrated json - actual := s.cdc.MustMarshalJSON(genstate) - file = filepath.Join("testdata", "v16-swap.json") - expected, err := ioutil.ReadFile(file) - s.Require().NoError(err) - s.Require().JSONEq(string(expected), string(actual)) -} - -func (s *migrateTestSuite) TestMigrate_Params() { - params := v015swap.Params{ - SwapFee: sdk.MustNewDecFromStr("0.33"), - AllowedPools: v015swap.AllowedPools{ - {TokenA: "A", TokenB: "B"}, - {TokenA: "C", TokenB: "D"}, - }, - } - expectedParams := v016swap.Params{ - SwapFee: sdk.MustNewDecFromStr("0.33"), - AllowedPools: v016swap.AllowedPools{ - {TokenA: "A", TokenB: "B"}, - {TokenA: "C", TokenB: "D"}, - }, - } - s.v15genstate.Params = params - genState := Migrate(s.v15genstate) - s.Require().Equal(expectedParams, genState.Params) -} - -func (s *migrateTestSuite) TestMigrate_PoolRecords() { - s.v15genstate.PoolRecords = v015swap.PoolRecords{ - { - PoolID: "pool-1", - ReservesA: sdk.NewCoin("usdx", sdkmath.NewInt(100)), - ReservesB: sdk.NewCoin("xrpb", sdkmath.NewInt(200)), - TotalShares: sdkmath.NewInt(300), - }, - { - PoolID: "pool-2", - ReservesA: sdk.NewCoin("usdx", sdkmath.NewInt(500)), - ReservesB: sdk.NewCoin("ukava", sdkmath.NewInt(500)), - TotalShares: sdkmath.NewInt(1000), - }, - } - expected := v016swap.PoolRecords{ - { - PoolID: "pool-1", - ReservesA: sdk.NewCoin("usdx", sdkmath.NewInt(100)), - ReservesB: sdk.NewCoin("xrpb", sdkmath.NewInt(200)), - TotalShares: sdkmath.NewInt(300), - }, - { - PoolID: "pool-2", - ReservesA: sdk.NewCoin("usdx", sdkmath.NewInt(500)), - ReservesB: sdk.NewCoin("ukava", sdkmath.NewInt(500)), - TotalShares: sdkmath.NewInt(1000), - }, - } - genState := Migrate(s.v15genstate) - s.Require().Equal(expected, genState.PoolRecords) -} - -func (s *migrateTestSuite) TestMigrate_ShareRecords() { - s.v15genstate.ShareRecords = v015swap.ShareRecords{ - { - PoolID: "pool-1", - Depositor: s.addresses[0], - SharesOwned: sdkmath.NewInt(100), - }, - { - PoolID: "pool-2", - Depositor: s.addresses[1], - SharesOwned: sdkmath.NewInt(410), - }, - } - expected := v016swap.ShareRecords{ - { - PoolID: "pool-1", - Depositor: s.addresses[0], - SharesOwned: sdkmath.NewInt(100), - }, - { - PoolID: "pool-2", - Depositor: s.addresses[1], - SharesOwned: sdkmath.NewInt(410), - }, - } - genState := Migrate(s.v15genstate) - s.Require().Equal(expected, genState.ShareRecords) -} - -func TestMigrateTestSuite(t *testing.T) { - suite.Run(t, new(migrateTestSuite)) -} diff --git a/x/swap/legacy/v0_16/testdata/v15-swap.json b/x/swap/legacy/v0_16/testdata/v15-swap.json deleted file mode 100644 index 50f09d8a..00000000 --- a/x/swap/legacy/v0_16/testdata/v15-swap.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "params": { - "allowed_pools": [ - { - "token_a": "bnb", - "token_b": "usdx" - }, - { - "token_a": "btcb", - "token_b": "usdx" - }, - { - "token_a": "busd", - "token_b": "usdx" - }, - { - "token_a": "hard", - "token_b": "usdx" - }, - { - "token_a": "swp", - "token_b": "usdx" - }, - { - "token_a": "ukava", - "token_b": "usdx" - }, - { - "token_a": "usdx", - "token_b": "xrpb" - } - ], - "swap_fee": "0.001500000000000000" - }, - "pool_records": [ - { - "pool_id": "ukava:usdx", - "reserves_a": { - "amount": "583616549439", - "denom": "ukava" - }, - "reserves_b": { - "amount": "3431399443511", - "denom": "usdx" - }, - "total_shares": "1398497336200" - }, - { - "pool_id": "usdx:xrpb", - "reserves_a": { - "amount": "843639517257", - "denom": "usdx" - }, - "reserves_b": { - "amount": "72251274276145", - "denom": "xrpb" - }, - "total_shares": "7739661881008" - } - ], - "share_records": [ - { - "depositor": "kava1l77xymdt2ya0rl2mludkny5aqmr67u88ymgdje", - "pool_id": "usdx:xrpb", - "shares_owned": "29034728969" - }, - { - "depositor": "kava1llqkrdr69wc76cuxpx6j06x9pt63f52f7mlcye", - "pool_id": "busd:usdx", - "shares_owned": "24905307583" - }, - { - "depositor": "kava1ll3ndyv333aet6mzqltu5wdepqhyme8umv34es", - "pool_id": "hard:usdx", - "shares_owned": "708138421" - }, - { - "depositor": "kava1ll3ndyv333aet6mzqltu5wdepqhyme8umv34es", - "pool_id": "ukava:usdx", - "shares_owned": "3427014047" - } - ] -} diff --git a/x/swap/legacy/v0_16/testdata/v16-swap.json b/x/swap/legacy/v0_16/testdata/v16-swap.json deleted file mode 100644 index 6911ab40..00000000 --- a/x/swap/legacy/v0_16/testdata/v16-swap.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "params": { - "allowed_pools": [ - { "token_a": "bnb", "token_b": "usdx" }, - { "token_a": "btcb", "token_b": "usdx" }, - { "token_a": "busd", "token_b": "usdx" }, - { "token_a": "hard", "token_b": "usdx" }, - { "token_a": "swp", "token_b": "usdx" }, - { "token_a": "ukava", "token_b": "usdx" }, - { "token_a": "usdx", "token_b": "xrpb" } - ], - "swap_fee": "0.001500000000000000" - }, - "pool_records": [ - { - "pool_id": "ukava:usdx", - "reserves_a": { "denom": "ukava", "amount": "583616549439" }, - "reserves_b": { "denom": "usdx", "amount": "3431399443511" }, - "total_shares": "1398497336200" - }, - { - "pool_id": "usdx:xrpb", - "reserves_a": { "denom": "usdx", "amount": "843639517257" }, - "reserves_b": { "denom": "xrpb", "amount": "72251274276145" }, - "total_shares": "7739661881008" - } - ], - "share_records": [ - { - "depositor": "kava1l77xymdt2ya0rl2mludkny5aqmr67u88ymgdje", - "pool_id": "usdx:xrpb", - "shares_owned": "29034728969" - }, - { - "depositor": "kava1llqkrdr69wc76cuxpx6j06x9pt63f52f7mlcye", - "pool_id": "busd:usdx", - "shares_owned": "24905307583" - }, - { - "depositor": "kava1ll3ndyv333aet6mzqltu5wdepqhyme8umv34es", - "pool_id": "hard:usdx", - "shares_owned": "708138421" - }, - { - "depositor": "kava1ll3ndyv333aet6mzqltu5wdepqhyme8umv34es", - "pool_id": "ukava:usdx", - "shares_owned": "3427014047" - } - ] -} diff --git a/x/swap/module.go b/x/swap/module.go deleted file mode 100644 index 19f3d9f8..00000000 --- a/x/swap/module.go +++ /dev/null @@ -1,141 +0,0 @@ -package swap - -import ( - "context" - "encoding/json" - - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/0glabs/0g-chain/x/swap/client/cli" - "github.com/0glabs/0g-chain/x/swap/keeper" - "github.com/0glabs/0g-chain/x/swap/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// AppModuleBasic app module basics object -type AppModuleBasic struct{} - -// Name get module name -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterLegacyAminoCodec register module codec -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// DefaultGenesis default genesis state -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - gs := types.DefaultGenesisState() - return cdc.MustMarshalJSON(&gs) -} - -// ValidateGenesis module validate genesis -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var gs types.GenesisState - err := cdc.UnmarshalJSON(bz, &gs) - if err != nil { - return err - } - return gs.Validate() -} - -// RegisterInterfaces implements InterfaceModule.RegisterInterfaces -func (a AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the gov module. -func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// GetTxCmd returns the root tx command for the swap module. -func (AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the swap module. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd(types.StoreKey) -} - -//____________________________________________________________________________ - -// AppModule app module type -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper -} - -// NewAppModule creates a new AppModule object -func NewAppModule(keeper keeper.Keeper, accountKeeper types.AccountKeeper) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - keeper: keeper, - accountKeeper: accountKeeper, - } -} - -// Name module name -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// RegisterInvariants register module invariants -func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) { - keeper.RegisterInvariants(ir, am.keeper) -} - -// ConsensusVersion implements AppModule/ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { - return 1 -} - -// RegisterServices registers module services. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServerImpl(am.keeper)) -} - -// InitGenesis module init-genesis -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { - var genState types.GenesisState - // Initialize global index to index in genesis state - cdc.MustUnmarshalJSON(gs, &genState) - - InitGenesis(ctx, am.keeper, genState) - - return []abci.ValidatorUpdate{} -} - -// ExportGenesis module export genesis -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(&gs) -} - -// BeginBlock module begin-block -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) { -} - -// EndBlock module end-block -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/swap/module_test.go b/x/swap/module_test.go deleted file mode 100644 index 413316b5..00000000 --- a/x/swap/module_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package swap_test - -import ( - "testing" - - "github.com/0glabs/0g-chain/x/swap/testutil" - "github.com/0glabs/0g-chain/x/swap/types" - - crisiskeeper "github.com/cosmos/cosmos-sdk/x/crisis/keeper" - "github.com/stretchr/testify/suite" -) - -type moduleTestSuite struct { - testutil.Suite - crisisKeeper crisiskeeper.Keeper -} - -func (suite *moduleTestSuite) SetupTest() { - suite.Suite.SetupTest() - suite.crisisKeeper = suite.App.GetCrisisKeeper() -} - -func (suite *moduleTestSuite) TestRegisterInvariants() { - swapRoutes := []string{} - - for _, route := range suite.crisisKeeper.Routes() { - if route.ModuleName == types.ModuleName { - swapRoutes = append(swapRoutes, route.Route) - } - } - - suite.Contains(swapRoutes, "pool-records") - suite.Contains(swapRoutes, "share-records") - suite.Contains(swapRoutes, "pool-reserves") - suite.Contains(swapRoutes, "pool-shares") -} - -func TestModuleTestSuite(t *testing.T) { - suite.Run(t, new(moduleTestSuite)) -} diff --git a/x/swap/spec/01_concepts.md b/x/swap/spec/01_concepts.md deleted file mode 100644 index b7a0a305..00000000 --- a/x/swap/spec/01_concepts.md +++ /dev/null @@ -1,13 +0,0 @@ - - -# Concepts - -## Automated Market Maker - -The swap module provides for functionality and governance of an Automated Market Maker protocol. The main state transitions in the swap module include deposits/withdrawals to liquidity pools by liquidity providers and token swaps executed against liquidity pools by users. Each liquidity pool consists of a unique pair of two tokens. A global swap fee set by governance is paid by users to execute trades, with the proceeds going to the relevant pool's liquidity providers. - -## SWP Token distribution - -[See Incentive Module](../../incentive/spec/01_concepts.md) diff --git a/x/swap/spec/02_state.md b/x/swap/spec/02_state.md deleted file mode 100644 index 15b68165..00000000 --- a/x/swap/spec/02_state.md +++ /dev/null @@ -1,62 +0,0 @@ - - -# State - -## Parameters and Genesis State - -`Parameters` define the governance parameters and default behavior of the swap module. - -```go -// Params are governance parameters for the swap module -type Params struct { - AllowedPools AllowedPools `json:"allowed_pools" yaml:"allowed_pools"` - SwapFee sdk.Dec `json:"swap_fee" yaml:"swap_fee"` -} - -// AllowedPool defines a tradable pool -type AllowedPool struct { - TokenA string `json:"token_a" yaml:"token_a"` - TokenB string `json:"token_b" yaml:"token_b"` -} - -// AllowedPools is a slice of AllowedPool -type AllowedPools []AllowedPool -``` - -`GenesisState` defines the state that must be persisted when the blockchain stops/restarts in order for the normal function of the swap module to resume. - -```go -// GenesisState is the state that must be provided at genesis. -type GenesisState struct { - Params Params `json:"params" yaml:"params"` - PoolRecords `json:"pool_records" yaml:"pool_records"` - ShareRecords `json:"share_records" yaml:"share_records"` -} - -// PoolRecord represents the state of a liquidity pool -// and is used to store the state of a denominated pool -type PoolRecord struct { - // primary key - PoolID string `json:"pool_id" yaml:"pool_id"` - ReservesA sdk.Coin `json:"reserves_a" yaml:"reserves_a"` - ReservesB sdk.Coin `json:"reserves_b" yaml:"reserves_b"` - TotalShares sdkmath.Int `json:"total_shares" yaml:"total_shares"` -} - -// PoolRecords is a slice of PoolRecord -type PoolRecords []PoolRecord - -// ShareRecord stores the shares owned for a depositor and pool -type ShareRecord struct { - // primary key - Depositor sdk.AccAddress `json:"depositor" yaml:"depositor"` - // secondary / sort key - PoolID string `json:"pool_id" yaml:"pool_id"` - SharesOwned sdkmath.Int `json:"shares_owned" yaml:"shares_owned"` -} - -// ShareRecords is a slice of ShareRecord -type ShareRecords []ShareRecord -``` diff --git a/x/swap/spec/03_messages.md b/x/swap/spec/03_messages.md deleted file mode 100644 index 1b331f95..00000000 --- a/x/swap/spec/03_messages.md +++ /dev/null @@ -1,65 +0,0 @@ - - -# Messages - - -MsgDeposit adds liquidity to a pool: - -```go -// MsgDeposit deposits liquidity into a pool -type MsgDeposit struct { - Depositor sdk.AccAddress `json:"depositor" yaml:"depositor"` - TokenA sdk.Coin `json:"token_a" yaml:"token_a"` - TokenB sdk.Coin `json:"token_b" yaml:"token_b"` - Slippage sdk.Dec `json:"slippage" yaml:"slippage"` - Deadline int64 `json:"deadline" yaml:"deadline"` -} -``` - -The first deposit to a pool results in a `PoolRecord` being created. For each deposit, a `ShareRecord` is created or updated, depending on if the depositor has an existing deposit. The deposited tokens are converted to shares. For the first deposit to a pool, shares are equal to the geometric mean of the deposited amount. For example, depositing 200 TokenA and 100 TokenB will create `sqrt(100 * 200) = 141` shares. For subsequent deposits, shares are issued equal to the current conversion between tokens and shares in that pool. - -MsgWithdraw removes liquidity from a pool: - -```go -// MsgWithdraw deposits liquidity into a pool -type MsgWithdraw struct { - From sdk.AccAddress `json:"from" yaml:"from"` - Shares sdkmath.Int `json:"shares" yaml:"shares"` - MinTokenA sdk.Coin `json:"min_token_a" yaml:"min_token_a"` - MinTokenB sdk.Coin `json:"min_token_b" yaml:"min_token_b"` - Deadline int64 `json:"deadline" yaml:"deadline"` -} -``` -When withdrawing from a pool, the user specifies the amount of shares they want to withdraw, as well as the minimum amount of tokenA and tokenB that they must receive for the transaction to succeed. When withdrawing, the `ShareRecord` of the user will be decremented by the corresponding amount of shares, or deleted in the case that all liquidity has been withdrawn. If all shares of a pool have been withdrawn from a pool, the `PoolRecord` will be deleted. - -MsgSwapExactForTokens trades an exact amount of input tokens for a variable amount of output tokens, with a specified maximum slippage tolerance. - -```go -// MsgSwapExactForTokens trades an exact coinA for coinB -type MsgSwapExactForTokens struct { - Requester sdk.AccAddress `json:"requester" yaml:"requester"` - ExactTokenA sdk.Coin `json:"exact_token_a" yaml:"exact_token_a"` - TokenB sdk.Coin `json:"token_b" yaml:"token_b"` - Slippage sdk.Dec `json:"slippage" yaml:"slippage"` - Deadline int64 `json:"deadline" yaml:"deadline"` -} -``` - -When trading exact inputs for variable outputs, the swap fee is removed from TokenA and added to the pool, then slippage is calculated based on the actual amount of TokenB received compared to the desired amount of TokenB. If the realized slippage of the trade is greater than the specified slippage tolerance, the transaction fails. - -MsgSwapForExactTokens trades a variable amount of input tokens for an exact amount of output tokens, with a specified maximum slippage tolerance. - -```go -// MsgSwapForExactTokens trades coinA for an exact coinB -type MsgSwapForExactTokens struct { - Requester sdk.AccAddress `json:"requester" yaml:"requester"` - TokenA sdk.Coin `json:"token_a" yaml:"token_a"` - ExactTokenB sdk.Coin `json:"exact_token_b" yaml:"exact_token_b"` - Slippage sdk.Dec `json:"slippage" yaml:"slippage"` - Deadline int64 `json:"deadline" yaml:"deadline"` -} -``` - -When trading variable inputs for exact outputs, the fee swap fee is removed from TokenA and added to the pool, then slippage is calculated based on the actual amount of TokenA required to acquire the exact TokenB amount versus the desired TokenA required. If the realized slippage of the trade is greater than the specified slippage tolerance, the transaction fails. diff --git a/x/swap/spec/04_events.md b/x/swap/spec/04_events.md deleted file mode 100644 index 75aa8ea2..00000000 --- a/x/swap/spec/04_events.md +++ /dev/null @@ -1,59 +0,0 @@ - - -# Events - -The swap module emits the following events: - -## Handlers - -### MsgDeposit - -| Type | Attribute Key | Attribute Value | -| ------------ | ------------- | --------------------- | -| message | module | swap | -| message | sender | `{sender address}` | -| swap_deposit | pool_id | `{poolID}` | -| swap_deposit | depositor | `{depositor address}` | -| swap_deposit | amount | `{amount}` | -| swap_deposit | shares | `{shares}` | - -### MsgWithdraw - -| Type | Attribute Key | Attribute Value | -| ------------- | ------------- | --------------------- | -| message | module | swap | -| message | sender | `{sender address}` | -| swap_withdraw | pool_id | `{poolID}` | -| swap_withdraw | owner | `{owner address}` | -| swap_withdraw | amount | `{amount}` | -| swap_withdraw | shares | `{shares}` | - - -### MsgSwapExactForTokens - -| Type | Attribute Key | Attribute Value | -| ------------- | ------------- | ------------------------ | -| message | module | swap | -| message | sender | `{sender address}` | -| swap_trade | pool_id | `{poolID}` | -| swap_trade | requester | `{requester address}` | -| swap_trade | swap_input | `{input amount}` | -| swap_trade | swap_output | `{output amount}` | -| swap_trade | fee_paid | `{fee amount}` | -| swap_trade | exact | `{exact trade direction}`| - - -### MsgSwapForExactTokens - -| Type | Attribute Key | Attribute Value | -| ------------- | ------------- | ------------------------ | -| message | module | swap | -| message | sender | `{sender address}` | -| swap_trade | pool_id | `{poolID}` | -| swap_trade | requester | `{requester address}` | -| swap_trade | swap_input | `{input amount}` | -| swap_trade | swap_output | `{output amount}` | -| swap_trade | fee_paid | `{fee amount}` | -| swap_trade | exact | `{exact trade direction}`| diff --git a/x/swap/spec/05_params.md b/x/swap/spec/05_params.md deleted file mode 100644 index 321187da..00000000 --- a/x/swap/spec/05_params.md +++ /dev/null @@ -1,19 +0,0 @@ - - -# Parameters - -Example parameters for the swap module: - -| Key | Type | Example | Description | -| ------------ | ------------------- | ------------- | --------------------------------------- | -| AllowedPools | array (AllowedPool) | [{see below}] | Array of tradable pools supported | -| SwapFee | sdk.Dec | 0.03 | Global trading fee in percentage format | - -Example parameters for `AllowedPool`: - -| Key | Type | Example | Description | -| ------ | ------ | ------- | ------------------- | -| TokenA | string | "ukava" | First coin's denom | -| TokenB | string | "usdx" | Second coin's denom | diff --git a/x/swap/spec/README.md b/x/swap/spec/README.md deleted file mode 100644 index 3a8da861..00000000 --- a/x/swap/spec/README.md +++ /dev/null @@ -1,20 +0,0 @@ - - -# `swap` - - - -1. **[Concepts](01_concepts.md)** -2. **[State](02_state.md)** -3. **[Messages](03_messages.md)** -4. **[Events](04_events.md)** -5. **[Params](05_params.md)** - -## Abstract - -`x/swap` is a Cosmos SDK module that implements an Automated Market Maker (AMM) that enables users to swap coins by trading against liquidity pools. diff --git a/x/swap/testutil/suite.go b/x/swap/testutil/suite.go deleted file mode 100644 index 06cbe230..00000000 --- a/x/swap/testutil/suite.go +++ /dev/null @@ -1,214 +0,0 @@ -package testutil - -import ( - "fmt" - "reflect" - "time" - - "github.com/0glabs/0g-chain/app" - "github.com/0glabs/0g-chain/x/swap/keeper" - "github.com/0glabs/0g-chain/x/swap/types" - - sdkmath "cosmossdk.io/math" - abci "github.com/cometbft/cometbft/abci/types" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtime "github.com/cometbft/cometbft/types/time" - sdk "github.com/cosmos/cosmos-sdk/types" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - BankKeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/stretchr/testify/suite" -) - -var defaultSwapFee = sdk.MustNewDecFromStr("0.003") - -// Suite implements a test suite for the swap module integration tests -type Suite struct { - suite.Suite - Keeper keeper.Keeper - App app.TestApp - Ctx sdk.Context - BankKeeper BankKeeper.Keeper - AccountKeeper authkeeper.AccountKeeper -} - -// SetupTest instantiates a new app, keepers, and sets suite state -func (suite *Suite) SetupTest() { - tApp := app.NewTestApp() - ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()}) - - suite.Ctx = ctx - suite.App = tApp - suite.Keeper = tApp.GetSwapKeeper() - suite.BankKeeper = tApp.GetBankKeeper() - suite.AccountKeeper = tApp.GetAccountKeeper() -} - -// GetEvents returns emitted events on the sdk context -func (suite *Suite) GetEvents() sdk.Events { - return suite.Ctx.EventManager().Events() -} - -// AddCoinsToModule adds coins to the swap module account -func (suite *Suite) AddCoinsToModule(amount sdk.Coins) { - // Does not use suite.BankKeeper.MintCoins as module account would not have permission to mint - err := suite.App.FundModuleAccount(suite.Ctx, types.ModuleName, amount) - suite.Require().NoError(err) -} - -// RemoveCoinsFromModule removes coins to the swap module account -func (suite *Suite) RemoveCoinsFromModule(amount sdk.Coins) { - // Swap module does not have BurnCoins permission so we need to transfer to gov first to burn - err := suite.BankKeeper.SendCoinsFromModuleToModule(suite.Ctx, types.ModuleAccountName, govtypes.ModuleName, amount) - suite.Require().NoError(err) - err = suite.BankKeeper.BurnCoins(suite.Ctx, govtypes.ModuleName, amount) - suite.Require().NoError(err) -} - -// CreateAccount creates a new account from the provided balance -func (suite *Suite) CreateAccount(initialBalance sdk.Coins) authtypes.AccountI { - _, addrs := app.GeneratePrivKeyAddressPairs(1) - ak := suite.App.GetAccountKeeper() - - acc := ak.NewAccountWithAddress(suite.Ctx, addrs[0]) - ak.SetAccount(suite.Ctx, acc) - - err := suite.App.FundAccount(suite.Ctx, acc.GetAddress(), initialBalance) - suite.Require().NoError(err) - - return acc -} - -// NewAccountFromAddr creates a new account from the provided address with the provided balance -func (suite *Suite) NewAccountFromAddr(addr sdk.AccAddress, balance sdk.Coins) authtypes.AccountI { - ak := suite.App.GetAccountKeeper() - - acc := ak.NewAccountWithAddress(suite.Ctx, addr) - ak.SetAccount(suite.Ctx, acc) - - err := suite.App.FundAccount(suite.Ctx, acc.GetAddress(), balance) - suite.Require().NoError(err) - - return acc -} - -// CreateVestingAccount creates a new vesting account from the provided balance and vesting balance -func (suite *Suite) CreateVestingAccount(initialBalance sdk.Coins, vestingBalance sdk.Coins) authtypes.AccountI { - acc := suite.CreateAccount(initialBalance) - bacc := acc.(*authtypes.BaseAccount) - - periods := vestingtypes.Periods{ - vestingtypes.Period{ - Length: 31556952, - Amount: vestingBalance, - }, - } - vacc := vestingtypes.NewPeriodicVestingAccount(bacc, initialBalance, time.Now().Unix(), periods) // TODO is initialBalance correct for originalVesting? - - return vacc -} - -// CreatePool creates a pool and stores it in state with the provided reserves -func (suite *Suite) CreatePool(reserves sdk.Coins) error { - depositor := suite.CreateAccount(reserves) - pool := types.NewAllowedPool(reserves[0].Denom, reserves[1].Denom) - suite.Require().NoError(pool.Validate()) - suite.Keeper.SetParams(suite.Ctx, types.NewParams(types.AllowedPools{pool}, defaultSwapFee)) - - return suite.Keeper.Deposit(suite.Ctx, depositor.GetAddress(), reserves[0], reserves[1], sdk.MustNewDecFromStr("1")) -} - -// AccountBalanceEqual asserts that the coins match the account balance -func (suite *Suite) AccountBalanceEqual(addr sdk.AccAddress, coins sdk.Coins) { - balance := suite.BankKeeper.GetAllBalances(suite.Ctx, addr) - suite.Equal(coins, balance, fmt.Sprintf("expected account balance to equal coins %s, but got %s", coins, balance)) -} - -// ModuleAccountBalanceEqual asserts that the swap module account balance matches the provided coins -func (suite *Suite) ModuleAccountBalanceEqual(coins sdk.Coins) { - balance := suite.BankKeeper.GetAllBalances( - suite.Ctx, - suite.AccountKeeper.GetModuleAddress(types.ModuleAccountName), - ) - suite.Equal(coins, balance, fmt.Sprintf("expected module account balance to equal coins %s, but got %s", coins, balance)) -} - -// PoolLiquidityEqual asserts that the pool matching the provided coins has those reserves -func (suite *Suite) PoolLiquidityEqual(coins sdk.Coins) { - poolRecord, ok := suite.Keeper.GetPool(suite.Ctx, types.PoolIDFromCoins(coins)) - suite.Require().True(ok, "expected pool to exist") - reserves := sdk.NewCoins(poolRecord.ReservesA, poolRecord.ReservesB) - suite.Equal(coins, reserves, fmt.Sprintf("expected pool reserves of %s, got %s", coins, reserves)) -} - -// PoolDeleted asserts that the pool does not exist -func (suite *Suite) PoolDeleted(denomA, denomB string) { - _, ok := suite.Keeper.GetPool(suite.Ctx, types.PoolID(denomA, denomB)) - suite.Require().False(ok, "expected pool to not exist") -} - -// PoolShareTotalEqual asserts the total shares match the stored pool -func (suite *Suite) PoolShareTotalEqual(poolID string, totalShares sdkmath.Int) { - poolRecord, found := suite.Keeper.GetPool(suite.Ctx, poolID) - suite.Require().True(found, fmt.Sprintf("expected pool %s to exist", poolID)) - suite.Equal(totalShares, poolRecord.TotalShares, "expected pool total shares to be equal") -} - -// PoolDepositorSharesEqual asserts the depositor owns the shares for the provided pool -func (suite *Suite) PoolDepositorSharesEqual(depositor sdk.AccAddress, poolID string, shares sdkmath.Int) { - shareRecord, found := suite.Keeper.GetDepositorShares(suite.Ctx, depositor, poolID) - suite.Require().True(found, fmt.Sprintf("expected share record to exist for depositor %s and pool %s", depositor.String(), poolID)) - suite.Equal(shares, shareRecord.SharesOwned) -} - -// PoolReservesEqual assets the stored pool reserves are equal to the provided reserves -func (suite *Suite) PoolReservesEqual(poolID string, reserves sdk.Coins) { - poolRecord, found := suite.Keeper.GetPool(suite.Ctx, poolID) - suite.Require().True(found, fmt.Sprintf("expected pool %s to exist", poolID)) - suite.Equal(reserves, poolRecord.Reserves(), "expected pool reserves to be equal") -} - -// PoolShareValueEqual asserts that the depositor shares are in state and the value matches the expected coins -func (suite *Suite) PoolShareValueEqual(depositor authtypes.AccountI, pool types.AllowedPool, coins sdk.Coins) { - poolRecord, ok := suite.Keeper.GetPool(suite.Ctx, pool.Name()) - suite.Require().True(ok, fmt.Sprintf("expected pool %s to exist", pool.Name())) - shares, ok := suite.Keeper.GetDepositorShares(suite.Ctx, depositor.GetAddress(), poolRecord.PoolID) - suite.Require().True(ok, fmt.Sprintf("expected shares to exist for depositor %s", depositor.GetAddress())) - - storedPool, err := types.NewDenominatedPoolWithExistingShares(sdk.NewCoins(poolRecord.ReservesA, poolRecord.ReservesB), poolRecord.TotalShares) - suite.Nil(err) - value := storedPool.ShareValue(shares.SharesOwned) - suite.Equal(coins, value, fmt.Sprintf("expected shares to equal %s, but got %s", coins, value)) -} - -// PoolSharesDeleted asserts that the pool shares have been removed -func (suite *Suite) PoolSharesDeleted(depositor sdk.AccAddress, denomA, denomB string) { - _, ok := suite.Keeper.GetDepositorShares(suite.Ctx, depositor, types.PoolID(denomA, denomB)) - suite.Require().False(ok, "expected pool shares to not exist") -} - -// EventsContains asserts that the expected event is in the provided events -func (suite *Suite) EventsContains(events sdk.Events, expectedEvent sdk.Event) { - foundMatch := false - for _, event := range events { - if event.Type == expectedEvent.Type { - if reflect.DeepEqual(attrsToMap(expectedEvent.Attributes), attrsToMap(event.Attributes)) { - foundMatch = true - } - } - } - - suite.True(foundMatch, fmt.Sprintf("event of type %s not found or did not match", expectedEvent.Type)) -} - -func attrsToMap(attrs []abci.EventAttribute) []sdk.Attribute { // new cosmos changed the event attribute type - out := []sdk.Attribute{} - - for _, attr := range attrs { - out = append(out, sdk.NewAttribute(string(attr.Key), string(attr.Value))) - } - - return out -} diff --git a/x/swap/types/base_pool.go b/x/swap/types/base_pool.go deleted file mode 100644 index fcc2e6b6..00000000 --- a/x/swap/types/base_pool.go +++ /dev/null @@ -1,436 +0,0 @@ -package types - -import ( - "fmt" - "math/big" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var zero = sdk.ZeroInt() - -// calculateInitialShares calculates initial shares as sqrt(A*B), the geometric mean of A and B -func calculateInitialShares(reservesA, reservesB sdkmath.Int) sdkmath.Int { - // Big.Int allows multiplication without overflow at 255 bits. - // In addition, Sqrt converges to a correct solution for inputs - // where sdkmath.Int.ApproxSqrt does not converge due to exceeding - // 100 iterations. - var result big.Int - result.Mul(reservesA.BigInt(), reservesB.BigInt()).Sqrt(&result) - return sdkmath.NewIntFromBigInt(&result) -} - -// BasePool implements a unitless constant-product liquidity pool. -// -// The pool is symmetric. For all A,B,s, any operation F on a pool (A,B,s) and pool (B,A,s) -// will result in equal state values of A', B', s': F(A,B,s) => (A',B',s'), F(B,A,s) => (B',A',s') -// -// In addition, the pool is protected from overflow in intermediate calculations, and will -// only overflow when A, B, or s become larger than the max sdkmath.Int. -// -// Pool operations with non-positive values are invalid, and all functions on a pool will panic -// when given zero or negative values. -type BasePool struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - totalShares sdkmath.Int -} - -// NewBasePool returns a pointer to a base pool with reserves and total shares initialized -func NewBasePool(reservesA, reservesB sdkmath.Int) (*BasePool, error) { - if reservesA.LTE(zero) || reservesB.LTE(zero) { - return nil, errorsmod.Wrap(ErrInvalidPool, "reserves must be greater than zero") - } - - totalShares := calculateInitialShares(reservesA, reservesB) - - return &BasePool{ - reservesA: reservesA, - reservesB: reservesB, - totalShares: totalShares, - }, nil -} - -// NewBasePoolWithExistingShares returns a pointer to a base pool with existing shares -func NewBasePoolWithExistingShares(reservesA, reservesB, totalShares sdkmath.Int) (*BasePool, error) { - if reservesA.LTE(zero) || reservesB.LTE(zero) { - return nil, errorsmod.Wrap(ErrInvalidPool, "reserves must be greater than zero") - } - - if totalShares.LTE(zero) { - return nil, errorsmod.Wrap(ErrInvalidPool, "total shares must be greater than zero") - } - - return &BasePool{ - reservesA: reservesA, - reservesB: reservesB, - totalShares: totalShares, - }, nil -} - -// ReservesA returns the A reserves of the pool -func (p *BasePool) ReservesA() sdkmath.Int { - return p.reservesA -} - -// ReservesB returns the B reserves of the pool -func (p *BasePool) ReservesB() sdkmath.Int { - return p.reservesB -} - -// IsEmpty returns true if all reserves are zero and -// returns false if reserveA or reserveB is not empty -func (p *BasePool) IsEmpty() bool { - return p.reservesA.IsZero() && p.reservesB.IsZero() -} - -// TotalShares returns the total number of shares in the pool -func (p *BasePool) TotalShares() sdkmath.Int { - return p.totalShares -} - -// AddLiquidity adds liquidity to the pool returns the actual reservesA, reservesB deposits in addition -// to the number of shares created. The deposits are always less than or equal to the provided and desired -// values. -func (p *BasePool) AddLiquidity(desiredA sdkmath.Int, desiredB sdkmath.Int) (sdkmath.Int, sdkmath.Int, sdkmath.Int) { - // Panics if provided values are zero - p.assertDepositsArePositive(desiredA, desiredB) - - // Reinitialize the pool if reserves are empty and return the initialized state. - if p.IsEmpty() { - p.reservesA = desiredA - p.reservesB = desiredB - p.totalShares = calculateInitialShares(desiredA, desiredB) - return p.ReservesA(), p.ReservesB(), p.TotalShares() - } - - // Panics if reserveA or reserveB is zero. - p.assertReservesArePositive() - - // In order to preserve the reserve ratio of the pool, we must deposit - // A and B in the same ratio of the existing reserves. In addition, - // we should not deposit more funds than requested. - // - // To meet these requirements, we first calculate the optimalB to deposit - // if we keep desiredA fixed. If this is less than or equal to the desiredB, - // then we use (desiredA, optimalB) as the deposit. - // - // If the optimalB is greater than the desiredB, we calculate the optimalA - // from the desiredB and use (optimalA, desiredB) as the deposit. - // - // These optimal values are calculated as: - // - // optimalB = reservesB * desiredA / reservesA - // optimalA = reservesA * desiredB / reservesB - // - // Which shows us: - // - // if optimalB < desiredB then optimalA > desiredA - // if optimalB = desiredB then optimalA = desiredA - // if optimalB > desiredB then optimalA < desiredA - // - // so we first check if optimalB <= desiredB, then deposit - // (desiredA, optimalB) else deposit (optimalA, desiredA). - // - // In order avoid precision loss, we rearrange the inequality - // of optimalB <= desiredB - // from: - // reservesB * desiredA / reservesA <= desiredB - // to: - // reservesB * desiredA <= desiredB * reservesA - // - // which also shares the same intermediate products - // as the calculations for optimalB and optimalA. - actualA := desiredA.BigInt() - actualB := desiredB.BigInt() - - // productA = reservesB * desiredA - var productA big.Int - productA.Mul(p.reservesB.BigInt(), actualA) - - // productB = reservesA * desiredB - var productB big.Int - productB.Mul(p.reservesA.BigInt(), actualB) - - // optimalB <= desiredB - if productA.Cmp(&productB) <= 0 { - actualB.Quo(&productA, p.reservesA.BigInt()) - } else { // optimalA < desiredA - actualA.Quo(&productB, p.reservesB.BigInt()) - } - - var sharesA big.Int - sharesA.Mul(actualA, p.totalShares.BigInt()).Quo(&sharesA, p.reservesA.BigInt()) - - var sharesB big.Int - sharesB.Mul(actualB, p.totalShares.BigInt()).Quo(&sharesB, p.reservesB.BigInt()) - - // a/A and b/B may not be equal due to discrete math and truncation errors, - // so use the smallest deposit ratio to calculate the number of shares - // - // If we do not use the min or max ratio, then the result becomes - // dependent on the order of reserves in the pool - // - // Min is used to always ensure the share ratio is never larger - // than the deposit ratio for either A or B, ensuring there are no - // cases where a withdraw will allow funds to be removed at a higher ratio - // than it was deposited. - var shares sdkmath.Int - if sharesA.Cmp(&sharesB) <= 0 { - shares = sdkmath.NewIntFromBigInt(&sharesA) - } else { - shares = sdkmath.NewIntFromBigInt(&sharesB) - } - - depositA := sdkmath.NewIntFromBigInt(actualA) - depositB := sdkmath.NewIntFromBigInt(actualB) - - // update internal pool state - p.reservesA = p.reservesA.Add(depositA) - p.reservesB = p.reservesB.Add(depositB) - p.totalShares = p.totalShares.Add(shares) - - return depositA, depositB, shares -} - -// RemoveLiquidity removes liquidity from the pool and panics if the -// shares provided are greater than the total shares of the pool -// or the shares are not positive. -// In addition, also panics if reserves go negative, which should not happen. -// If panic occurs, it is a bug. -func (p *BasePool) RemoveLiquidity(shares sdkmath.Int) (sdkmath.Int, sdkmath.Int) { - // calculate amount to withdraw from the pool based - // on the number of shares provided. s/S * reserves - withdrawA, withdrawB := p.ShareValue(shares) - - // update internal pool state - p.reservesA = p.reservesA.Sub(withdrawA) - p.reservesB = p.reservesB.Sub(withdrawB) - p.totalShares = p.totalShares.Sub(shares) - - // Panics if reserveA or reserveB are negative - // A zero value (100% withdraw) is OK and should not panic. - p.assertReservesAreNotNegative() - - return withdrawA, withdrawB -} - -// SwapExactAForB trades an exact value of a for b. Returns the positive amount b -// that is removed from the pool and the portion of a that is used for paying the fee. -func (p *BasePool) SwapExactAForB(a sdkmath.Int, fee sdk.Dec) (sdkmath.Int, sdkmath.Int) { - b, feeValue := p.calculateOutputForExactInput(a, p.reservesA, p.reservesB, fee) - - p.assertInvariantAndUpdateReserves( - p.reservesA.Add(a), feeValue, p.reservesB.Sub(b), sdk.ZeroInt(), - ) - - return b, feeValue -} - -// SwapExactBForA trades an exact value of b for a. Returns the positive amount a -// that is removed from the pool and the portion of b that is used for paying the fee. -func (p *BasePool) SwapExactBForA(b sdkmath.Int, fee sdk.Dec) (sdkmath.Int, sdkmath.Int) { - a, feeValue := p.calculateOutputForExactInput(b, p.reservesB, p.reservesA, fee) - - p.assertInvariantAndUpdateReserves( - p.reservesA.Sub(a), sdk.ZeroInt(), p.reservesB.Add(b), feeValue, - ) - - return a, feeValue -} - -// calculateOutputForExactInput calculates the output amount of a swap using a fixed input, returning this amount in -// addition to the amount of input that is used to pay the fee. -// -// The fee is ceiled, ensuring a minimum fee of 1 and ensuring fees of a trade can not be reduced -// by splitting a trade into multiple trades. -// -// The swap output is truncated to ensure the pool invariant is always greater than or equal to the previous invariant. -func (p *BasePool) calculateOutputForExactInput(in, inReserves, outReserves sdkmath.Int, fee sdk.Dec) (sdkmath.Int, sdkmath.Int) { - p.assertSwapInputIsValid(in) - p.assertFeeIsValid(fee) - - inAfterFee := sdk.NewDecFromInt(in).Mul(sdk.OneDec().Sub(fee)).TruncateInt() - - var result big.Int - result.Mul(outReserves.BigInt(), inAfterFee.BigInt()) - result.Quo(&result, inReserves.Add(inAfterFee).BigInt()) - - out := sdkmath.NewIntFromBigInt(&result) - feeValue := in.Sub(inAfterFee) - - return out, feeValue -} - -// SwapAForExactB trades a for an exact b. Returns the positive amount a -// that is added to the pool, and the portion of a that is used to pay the fee. -func (p *BasePool) SwapAForExactB(b sdkmath.Int, fee sdk.Dec) (sdkmath.Int, sdkmath.Int) { - a, feeValue := p.calculateInputForExactOutput(b, p.reservesB, p.reservesA, fee) - - p.assertInvariantAndUpdateReserves( - p.reservesA.Add(a), feeValue, p.reservesB.Sub(b), sdk.ZeroInt(), - ) - - return a, feeValue -} - -// SwapBForExactA trades b for an exact a. Returns the positive amount b -// that is added to the pool, and the portion of b that is used to pay the fee. -func (p *BasePool) SwapBForExactA(a sdkmath.Int, fee sdk.Dec) (sdkmath.Int, sdkmath.Int) { - b, feeValue := p.calculateInputForExactOutput(a, p.reservesA, p.reservesB, fee) - - p.assertInvariantAndUpdateReserves( - p.reservesA.Sub(a), sdk.ZeroInt(), p.reservesB.Add(b), feeValue, - ) - - return b, feeValue -} - -// calculateInputForExactOutput calculates the input amount of a swap using a fixed output, returning this amount in -// addition to the amount of input that is used to pay the fee. -// -// The fee is ceiled, ensuring a minimum fee of 1 and ensuring fees of a trade can not be reduced -// by splitting a trade into multiple trades. -// -// The swap input is ceiled to ensure the pool invariant is always greater than or equal to the previous invariant. -func (p *BasePool) calculateInputForExactOutput(out, outReserves, inReserves sdkmath.Int, fee sdk.Dec) (sdkmath.Int, sdkmath.Int) { - p.assertSwapOutputIsValid(out, outReserves) - p.assertFeeIsValid(fee) - - var result big.Int - result.Mul(inReserves.BigInt(), out.BigInt()) - - newOutReserves := outReserves.Sub(out) - var remainder big.Int - result.QuoRem(&result, newOutReserves.BigInt(), &remainder) - - inWithoutFee := sdkmath.NewIntFromBigInt(&result) - if remainder.Sign() != 0 { - inWithoutFee = inWithoutFee.Add(sdk.OneInt()) - } - - in := sdk.NewDecFromInt(inWithoutFee).Quo(sdk.OneDec().Sub(fee)).Ceil().TruncateInt() - feeValue := in.Sub(inWithoutFee) - - return in, feeValue -} - -// ShareValue returns the value of the provided shares and panics -// if the shares are greater than the total shares of the pool or -// if the shares are not positive. -func (p *BasePool) ShareValue(shares sdkmath.Int) (sdkmath.Int, sdkmath.Int) { - p.assertSharesArePositive(shares) - p.assertSharesAreLessThanTotal(shares) - - var resultA big.Int - resultA.Mul(p.reservesA.BigInt(), shares.BigInt()) - resultA.Quo(&resultA, p.totalShares.BigInt()) - - var resultB big.Int - resultB.Mul(p.reservesB.BigInt(), shares.BigInt()) - resultB.Quo(&resultB, p.totalShares.BigInt()) - - return sdkmath.NewIntFromBigInt(&resultA), sdkmath.NewIntFromBigInt(&resultB) -} - -// assertInvariantAndUpdateRerserves asserts the constant product invariant is not violated, subtracting -// any fees first, then updates the pool reserves. Panics if invariant is violated. -func (p *BasePool) assertInvariantAndUpdateReserves(newReservesA, feeA, newReservesB, feeB sdkmath.Int) { - var invariant big.Int - invariant.Mul(p.reservesA.BigInt(), p.reservesB.BigInt()) - - var newInvariant big.Int - newInvariant.Mul(newReservesA.Sub(feeA).BigInt(), newReservesB.Sub(feeB).BigInt()) - - p.assertInvariant(&invariant, &newInvariant) - - p.reservesA = newReservesA - p.reservesB = newReservesB -} - -// assertSwapInputIsValid checks if the provided swap input is positive -// and panics if it is 0 or negative -func (p *BasePool) assertSwapInputIsValid(input sdkmath.Int) { - if !input.IsPositive() { - panic("invalid value: swap input must be positive") - } -} - -// assertSwapOutputIsValid checks if the provided swap input is positive and -// less than the provided reserves. -func (p *BasePool) assertSwapOutputIsValid(output sdkmath.Int, reserves sdkmath.Int) { - if !output.IsPositive() { - panic("invalid value: swap output must be positive") - } - - if output.GTE(reserves) { - panic("invalid value: swap output must be less than reserves") - } -} - -// assertFeeIsValid checks if the provided fee is less -func (p *BasePool) assertFeeIsValid(fee sdk.Dec) { - if fee.IsNegative() || fee.GTE(sdk.OneDec()) { - panic("invalid value: fee must be between 0 and 1") - } -} - -// assertSharesPositive panics if shares is zero or negative -func (p *BasePool) assertSharesArePositive(shares sdkmath.Int) { - if !shares.IsPositive() { - panic("invalid value: shares must be positive") - } -} - -// assertSharesLessThanTotal panics if the number of shares is greater than the total shares -func (p *BasePool) assertSharesAreLessThanTotal(shares sdkmath.Int) { - if shares.GT(p.totalShares) { - panic(fmt.Sprintf("out of bounds: shares %s > total shares %s", shares, p.totalShares)) - } -} - -// assertDepositsPositive panics if a deposit is zero or negative -func (p *BasePool) assertDepositsArePositive(depositA, depositB sdkmath.Int) { - if !depositA.IsPositive() { - panic("invalid value: deposit A must be positive") - } - - if !depositB.IsPositive() { - panic("invalid state: deposit B must be positive") - } -} - -// assertReservesArePositive panics if any reserves are zero. This is an invalid -// state that should never happen. If this panic is seen, it is a bug. -func (p *BasePool) assertReservesArePositive() { - if !p.reservesA.IsPositive() { - panic("invalid state: reserves A must be positive") - } - - if !p.reservesB.IsPositive() { - panic("invalid state: reserves B must be positive") - } -} - -// assertReservesAreNotNegative panics if any reserves are negative. This is an invalid -// state that should never happen. If this panic is seen, it is a bug. -func (p *BasePool) assertReservesAreNotNegative() { - if p.reservesA.IsNegative() { - panic("invalid state: reserves A can not be negative") - } - - if p.reservesB.IsNegative() { - panic("invalid state: reserves B can not be negative") - } -} - -// assertInvariant panics if the new invariant is less than the previous invariant. This -// is an invalid state that should never happen. If this panic is seen, it is a bug. -func (p *BasePool) assertInvariant(prevInvariant, newInvariant *big.Int) { - // invariant > newInvariant - if prevInvariant.Cmp(newInvariant) == 1 { - panic(fmt.Sprintf("invalid state: invariant %s decreased to %s", prevInvariant.String(), newInvariant.String())) - } -} diff --git a/x/swap/types/base_pool_test.go b/x/swap/types/base_pool_test.go deleted file mode 100644 index ab79eb95..00000000 --- a/x/swap/types/base_pool_test.go +++ /dev/null @@ -1,591 +0,0 @@ -package types_test - -import ( - "fmt" - "math/big" - "testing" - - types "github.com/0glabs/0g-chain/x/swap/types" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// i creates a new sdkmath.Int from int64 -func i(n int64) sdkmath.Int { - return sdkmath.NewInt(n) -} - -// s returns a new sdkmath.Int from a string -func s(str string) sdkmath.Int { - num, ok := sdkmath.NewIntFromString(str) - if !ok { - panic(fmt.Sprintf("overflow creating Int from %s", str)) - } - return num -} - -// d creates a new sdk.Dec from a string -func d(str string) sdk.Dec { - return sdk.MustNewDecFromStr(str) -} - -// exp takes a sdkmath.Int and computes the power -// helper to generate large numbers -func exp(n sdkmath.Int, power int64) sdkmath.Int { - b := n.BigInt() - b.Exp(b, big.NewInt(power), nil) - return sdkmath.NewIntFromBigInt(b) -} - -func TestBasePool_NewPool_Validation(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - expectedErr string - }{ - {i(0), i(1e6), "reserves must be greater than zero: invalid pool"}, - {i(0), i(0), "reserves must be greater than zero: invalid pool"}, - {i(-1), i(1e6), "reserves must be greater than zero: invalid pool"}, - {i(1e6), i(-1), "reserves must be greater than zero: invalid pool"}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s", tc.reservesA, tc.reservesB), func(t *testing.T) { - pool, err := types.NewBasePool(tc.reservesA, tc.reservesB) - require.EqualError(t, err, tc.expectedErr) - assert.Nil(t, pool) - }) - } -} - -func TestBasePool_NewPoolWithExistingShares_Validation(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - totalShares sdkmath.Int - expectedErr string - }{ - {i(0), i(1e6), i(1), "reserves must be greater than zero: invalid pool"}, - {i(0), i(0), i(1), "reserves must be greater than zero: invalid pool"}, - {i(-1), i(1e6), i(3), "reserves must be greater than zero: invalid pool"}, - {i(1e6), i(-1), i(100), "reserves must be greater than zero: invalid pool"}, - {i(1e6), i(-1), i(3), "reserves must be greater than zero: invalid pool"}, - {i(1e6), i(1e6), i(0), "total shares must be greater than zero: invalid pool"}, - {i(1e6), i(1e6), i(-1), "total shares must be greater than zero: invalid pool"}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s shares=%s", tc.reservesA, tc.reservesB, tc.totalShares), func(t *testing.T) { - pool, err := types.NewBasePoolWithExistingShares(tc.reservesA, tc.reservesB, tc.totalShares) - require.EqualError(t, err, tc.expectedErr) - assert.Nil(t, pool) - }) - } -} - -func TestBasePool_InitialState(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - expectedShares sdkmath.Int - }{ - {i(1), i(1), i(1)}, - {i(100), i(100), i(100)}, - {i(100), i(10000000), i(31622)}, - {i(1e5), i(5e6), i(707106)}, - {i(1e6), i(5e6), i(2236067)}, - {i(1e15), i(7e15), i(2645751311064590)}, - {i(1), i(6e18), i(2449489742)}, - {i(1.345678e18), i(4.313456e18), i(2409257736973775913)}, - // handle sqrt of large numbers, sdkmath.Int.ApproxSqrt() doesn't converge in 100 iterations - {i(145345664).Mul(exp(i(10), 26)), i(6432294561).Mul(exp(i(10), 20)), s("96690543695447979624812468142651")}, - {i(465432423).Mul(exp(i(10), 50)), i(4565432).Mul(exp(i(10), 50)), s("4609663846531258725944608083913166083991595286362304230475")}, - {exp(i(2), 253), exp(i(2), 253), s("14474011154664524427946373126085988481658748083205070504932198000989141204992")}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s", tc.reservesA, tc.reservesB), func(t *testing.T) { - pool, err := types.NewBasePool(tc.reservesA, tc.reservesB) - require.Nil(t, err) - assert.Equal(t, tc.reservesA, pool.ReservesA()) - assert.Equal(t, tc.reservesB, pool.ReservesB()) - assert.Equal(t, tc.expectedShares, pool.TotalShares()) - }) - } -} - -func TestBasePool_ExistingState(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - totalShares sdkmath.Int - }{ - {i(1), i(1), i(1)}, - {i(100), i(100), i(100)}, - {i(1e5), i(5e6), i(707106)}, - {i(1e15), i(7e15), i(2645751311064590)}, - {i(465432423).Mul(exp(i(10), 50)), i(4565432).Mul(exp(i(10), 50)), s("4609663846531258725944608083913166083991595286362304230475")}, - {exp(i(2), 253), exp(i(2), 253), s("14474011154664524427946373126085988481658748083205070504932198000989141204992")}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s shares=%s", tc.reservesA, tc.reservesB, tc.totalShares), func(t *testing.T) { - pool, err := types.NewBasePoolWithExistingShares(tc.reservesA, tc.reservesB, tc.totalShares) - require.Nil(t, err) - assert.Equal(t, tc.reservesA, pool.ReservesA()) - assert.Equal(t, tc.reservesB, pool.ReservesB()) - assert.Equal(t, tc.totalShares, pool.TotalShares()) - }) - } -} - -func TestBasePool_ShareValue_PoolCreator(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - }{ - {i(1), i(1)}, - {i(100), i(100)}, - {i(100), i(10000000)}, - {i(1e5), i(5e6)}, - {i(1e15), i(7e15)}, - {i(1), i(6e18)}, - {i(1.345678e18), i(4.313456e18)}, - // ensure no overflows in intermediate values - {exp(i(2), 253), exp(i(2), 253)}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s", tc.reservesA, tc.reservesB), func(t *testing.T) { - pool, err := types.NewBasePool(tc.reservesA, tc.reservesB) - assert.NoError(t, err) - - a, b := pool.ShareValue(pool.TotalShares()) - // pool creators experience zero truncation error and always - // and always receive their original balance on a 100% withdraw - // when there are no other deposits that result in a fractional share ownership - assert.Equal(t, tc.reservesA, a, "share value of reserves A not equal") - assert.Equal(t, tc.reservesB, b, "share value of reserves B not equal") - }) - } -} - -func TestBasePool_AddLiquidity(t *testing.T) { - testCases := []struct { - initialA sdkmath.Int - initialB sdkmath.Int - desiredA sdkmath.Int - desiredB sdkmath.Int - expectedA sdkmath.Int - expectedB sdkmath.Int - expectedShares sdkmath.Int - }{ - {i(1), i(1), i(1), i(1), i(1), i(1), i(1)}, // small pool, i(100)% deposit - {i(10), i(10), i(5), i(5), i(5), i(5), i(5)}, // i(50)% deposit - {i(10), i(10), i(3), i(3), i(3), i(3), i(3)}, // i(30)% deposit - {i(10), i(10), i(1), i(1), i(1), i(1), i(1)}, // i(10)% deposit - - // small pools, unequal deposit ratios - {i(11), i(10), i(5), i(6), i(5), i(4), i(4)}, - {i(11), i(10), i(5), i(5), i(5), i(4), i(4)}, - // this test case fails if we don't use min share ratio - {i(11), i(10), i(5), i(4), i(4), i(4), i(3)}, - - // small pools, unequal deposit ratios, reversed - {i(10), i(11), i(6), i(5), i(4), i(5), i(4)}, - {i(10), i(11), i(5), i(5), i(4), i(5), i(4)}, - // this test case fails if we don't use min share ratio - {i(10), i(11), i(4), i(5), i(4), i(4), i(3)}, - - {i(10e6), i(11e6), i(5e6), i(5e6), i(4545454), i(5e6), i(4767312)}, - {i(11e6), i(10e6), i(5e6), i(5e6), i(5e6), i(4545454), i(4767312)}, - - // pool size near max of sdkmath.Int, ensure intermidiate calculations do not overflow - {exp(i(10), 70), exp(i(10), 70), i(1e18), i(1e18), i(1e18), i(1e18), i(1e18)}, - } - - for _, tc := range testCases { - name := fmt.Sprintf("initialA=%s initialB=%s desiredA=%s desiredB=%s", tc.initialA, tc.initialB, tc.desiredA, tc.desiredB) - t.Run(name, func(t *testing.T) { - pool, err := types.NewBasePool(tc.initialA, tc.initialB) - require.NoError(t, err) - initialShares := pool.TotalShares() - - actualA, actualB, actualShares := pool.AddLiquidity(tc.desiredA, tc.desiredB) - - // assert correct values are retruned - assert.Equal(t, tc.expectedA, actualA, "deposited A liquidity not equal") - assert.Equal(t, tc.expectedB, actualB, "deposited B liquidity not equal") - assert.Equal(t, tc.expectedShares, actualShares, "calculated shares not equal") - - // assert pool liquidity and shares are updated - assert.Equal(t, tc.initialA.Add(actualA), pool.ReservesA(), "total reserves A not equal") - assert.Equal(t, tc.initialB.Add(actualB), pool.ReservesB(), "total reserves B not equal") - assert.Equal(t, initialShares.Add(actualShares), pool.TotalShares(), "total shares not equal") - - leftA := actualShares.BigInt() - leftA.Mul(leftA, tc.initialA.BigInt()) - rightA := initialShares.BigInt() - rightA.Mul(rightA, actualA.BigInt()) - - leftB := actualShares.BigInt() - leftB.Mul(leftB, tc.initialB.BigInt()) - rightB := initialShares.BigInt() - rightB.Mul(rightB, actualB.BigInt()) - - // assert that the share ratio is less than or equal to the deposit ratio - // actualShares / initialShares <= actualA / initialA - assert.True(t, leftA.Cmp(rightA) <= 0, "share ratio is greater than deposit A ratio") - // actualShares / initialShares <= actualB / initialB - assert.True(t, leftB.Cmp(rightB) <= 0, "share ratio is greater than deposit B ratio") - - // assert that share value of returned shares is not greater than the deposited amount - shareValueA, shareValueB := pool.ShareValue(actualShares) - assert.True(t, shareValueA.LTE(actualA), "share value A greater than deposited A") - assert.True(t, shareValueB.LTE(actualB), "share value B greater than deposited B") - }) - } -} - -func TestBasePool_RemoveLiquidity(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - shares sdkmath.Int - expectedA sdkmath.Int - expectedB sdkmath.Int - }{ - {i(1), i(1), i(1), i(1), i(1)}, - {i(100), i(100), i(50), i(50), i(50)}, - {i(100), i(10000000), i(10435), i(32), i(3299917)}, - {i(10000000), i(100), i(10435), i(3299917), i(32)}, - {i(1.345678e18), i(4.313456e18), i(3.134541e17), i(175078108044025869), i(561197935621412888)}, - // ensure no overflows in intermediate values - {exp(i(10), 70), exp(i(10), 70), i(1e18), i(1e18), i(1e18)}, - {exp(i(2), 253), exp(i(2), 253), exp(i(2), 253), exp(i(2), 253), exp(i(2), 253)}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s shares=%s", tc.reservesA, tc.reservesB, tc.shares), func(t *testing.T) { - pool, err := types.NewBasePool(tc.reservesA, tc.reservesB) - assert.NoError(t, err) - initialShares := pool.TotalShares() - - a, b := pool.RemoveLiquidity(tc.shares) - - // pool creators experience zero truncation error and always - // and always receive their original balance on a 100% withdraw - // when there are no other deposits that result in a fractional share ownership - assert.Equal(t, tc.expectedA, a, "withdrawn A not equal") - assert.Equal(t, tc.expectedB, b, "withdrawn B not equal") - - // asset that pool state is updated - assert.Equal(t, tc.reservesA.Sub(a), pool.ReservesA(), "reserves A after withdraw not equal") - assert.Equal(t, tc.reservesB.Sub(b), pool.ReservesB(), "reserves B after withdraw not equal") - assert.Equal(t, initialShares.Sub(tc.shares), pool.TotalShares(), "total shares after withdraw not equal") - }) - } -} - -func TestBasePool_Panic_OutOfBounds(t *testing.T) { - pool, err := types.NewBasePool(sdkmath.NewInt(100), sdkmath.NewInt(100)) - require.NoError(t, err) - - assert.Panics(t, func() { pool.ShareValue(pool.TotalShares().Add(sdkmath.NewInt(1))) }, "ShareValue did not panic when shares > totalShares") - assert.Panics(t, func() { pool.RemoveLiquidity(pool.TotalShares().Add(sdkmath.NewInt(1))) }, "RemoveLiquidity did not panic when shares > totalShares") -} - -func TestBasePool_EmptyAndRefill(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - }{ - {i(1), i(1)}, - {i(100), i(100)}, - {i(100), i(10000000)}, - {i(1e5), i(5e6)}, - {i(1e6), i(5e6)}, - {i(1e15), i(7e15)}, - {i(1), i(6e18)}, - {i(1.345678e18), i(4.313456e18)}, - {i(145345664).Mul(exp(i(10), 26)), i(6432294561).Mul(exp(i(10), 20))}, - {i(465432423).Mul(exp(i(10), 50)), i(4565432).Mul(exp(i(10), 50))}, - {exp(i(2), 253), exp(i(2), 253)}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s", tc.reservesA, tc.reservesB), func(t *testing.T) { - pool, err := types.NewBasePool(tc.reservesA, tc.reservesB) - require.NoError(t, err) - - initialShares := pool.TotalShares() - pool.RemoveLiquidity(initialShares) - - assert.True(t, pool.IsEmpty()) - assert.True(t, pool.TotalShares().IsZero(), "total shares are not depleted") - - pool.AddLiquidity(tc.reservesA, tc.reservesB) - assert.Equal(t, initialShares, pool.TotalShares(), "total shares not equal") - }) - } -} - -func TestBasePool_Panics_AddLiquidity(t *testing.T) { - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.AddLiquidity(i(0), i(1e6)) - }, "did not panic when reserve A is zero") - - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.AddLiquidity(i(-1), i(1e6)) - }, "did not panic when reserve A is negative") - - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.AddLiquidity(i(1e6), i(0)) - }, "did not panic when reserve B is zero") - - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.AddLiquidity(i(1e6), i(0)) - }, "did not panic when reserve B is zero") -} - -func TestBasePool_Panics_RemoveLiquidity(t *testing.T) { - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.RemoveLiquidity(i(0)) - }, "did not panic when shares are zero") - - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.RemoveLiquidity(i(-1)) - }, "did not panic when shares are negative") -} - -func TestBasePool_ReservesOnlyDepletedWithLastShare(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - }{ - {i(5), i(5)}, - {i(100), i(100)}, - {i(100), i(10000000)}, - {i(1e5), i(5e6)}, - {i(1e6), i(5e6)}, - {i(1e15), i(7e15)}, - {i(1), i(6e18)}, - {i(1.345678e18), i(4.313456e18)}, - {i(145345664).Mul(exp(i(10), 26)), i(6432294561).Mul(exp(i(10), 20))}, - {i(465432423).Mul(exp(i(10), 50)), i(4565432).Mul(exp(i(10), 50))}, - {exp(i(2), 253), exp(i(2), 253)}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s", tc.reservesA, tc.reservesB), func(t *testing.T) { - pool, err := types.NewBasePool(tc.reservesA, tc.reservesB) - require.NoError(t, err) - - initialShares := pool.TotalShares() - pool.RemoveLiquidity(initialShares.Sub(i(1))) - - assert.False(t, pool.ReservesA().IsZero(), "reserves A equal to zero") - assert.False(t, pool.ReservesB().IsZero(), "reserves B equal to zero") - - pool.RemoveLiquidity(i(1)) - assert.True(t, pool.IsEmpty()) - }) - } -} - -func TestBasePool_Swap_ExactInput(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - exactInput sdkmath.Int - fee sdk.Dec - expectedOutput sdkmath.Int - expectedFee sdkmath.Int - }{ - // test small pools - {i(10), i(10), i(1), d("0.003"), i(0), i(1)}, - {i(10), i(10), i(3), d("0.003"), i(1), i(1)}, - {i(10), i(10), i(10), d("0.003"), i(4), i(1)}, - {i(10), i(10), i(91), d("0.003"), i(9), i(1)}, - // test fee values and ceil - {i(1e6), i(1e6), i(1000), d("0.003"), i(996), i(3)}, - {i(1e6), i(1e6), i(1000), d("0.0031"), i(995), i(4)}, - {i(1e6), i(1e6), i(1000), d("0.0039"), i(995), i(4)}, - {i(1e6), i(1e6), i(1000), d("0.001"), i(998), i(1)}, - {i(1e6), i(1e6), i(1000), d("0.025"), i(974), i(25)}, - {i(1e6), i(1e6), i(1000), d("0.1"), i(899), i(100)}, - {i(1e6), i(1e6), i(1000), d("0.5"), i(499), i(500)}, - // test various random pools and swaps - {i(10e6), i(500e6), i(1e6), d("0.0025"), i(45351216), i(2500)}, - {i(10e6), i(500e6), i(8e6), d("0.003456"), i(221794899), i(27648)}, - // test very large pools and swaps - {exp(i(2), 250), exp(i(2), 250), exp(i(2), 249), d("0.003"), s("601876423139828614225164081027182620796370196819963934493551943901658899790"), s("2713877091499598330239944961141122840311015265600950719674787125185463976")}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s exactInput=%s fee=%s", tc.reservesA, tc.reservesB, tc.exactInput, tc.fee), func(t *testing.T) { - poolA, err := types.NewBasePool(tc.reservesA, tc.reservesB) - require.NoError(t, err) - swapA, feeA := poolA.SwapExactAForB(tc.exactInput, tc.fee) - - poolB, err := types.NewBasePool(tc.reservesB, tc.reservesA) - require.NoError(t, err) - swapB, feeB := poolB.SwapExactBForA(tc.exactInput, tc.fee) - - // pool must be symmetric - if we swap reserves, then swap opposite direction - // then the results should be equal - require.Equal(t, swapA, swapB, "expected swap methods to have equal swap results") - require.Equal(t, feeA, feeB, "expected swap methods to have equal fee results") - require.Equal(t, poolA.ReservesA(), poolB.ReservesB(), "expected reserves A to be equal") - require.Equal(t, poolA.ReservesB(), poolB.ReservesA(), "expected reserves B to be equal") - - assert.Equal(t, tc.expectedOutput, swapA, "returned swap not equal") - assert.Equal(t, tc.expectedFee, feeA, "returned fee not equal") - - expectedReservesA := tc.reservesA.Add(tc.exactInput) - expectedReservesB := tc.reservesB.Sub(tc.expectedOutput) - - assert.Equal(t, expectedReservesA, poolA.ReservesA(), "expected new reserves A not equal") - assert.Equal(t, expectedReservesB, poolA.ReservesB(), "expected new reserves B not equal") - }) - } -} - -func TestBasePool_Swap_ExactOutput(t *testing.T) { - testCases := []struct { - reservesA sdkmath.Int - reservesB sdkmath.Int - exactOutput sdkmath.Int - fee sdk.Dec - expectedInput sdkmath.Int - expectedFee sdkmath.Int - }{ - // test small pools - {i(10), i(10), i(1), d("0.003"), i(3), i(1)}, - {i(10), i(10), i(9), d("0.003"), i(91), i(1)}, - // test fee values and ceil - {i(1e6), i(1e6), i(996), d("0.003"), i(1000), i(3)}, - {i(1e6), i(1e6), i(995), d("0.0031"), i(1000), i(4)}, - {i(1e6), i(1e6), i(995), d("0.0039"), i(1000), i(4)}, - {i(1e6), i(1e6), i(998), d("0.001"), i(1000), i(1)}, - {i(1e6), i(1e6), i(974), d("0.025"), i(1000), i(25)}, - {i(1e6), i(1e6), i(899), d("0.1"), i(1000), i(100)}, - {i(1e6), i(1e6), i(499), d("0.5"), i(1000), i(500)}, - // test various random pools and swaps - {i(10e6), i(500e6), i(45351216), d("0.0025"), i(1e6), i(2500)}, - {i(10e6), i(500e6), i(221794899), d("0.003456"), i(8e6), i(27648)}, - // test very large pools and swaps - {exp(i(2), 250), exp(i(2), 250), s("601876423139828614225164081027182620796370196819963934493551943901658899790"), d("0.003"), s("904625697166532776746648320380374280103671755200316906558262375061821325311"), s("2713877091499598330239944961141122840311015265600950719674787125185463976")}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s exactOutput=%s fee=%s", tc.reservesA, tc.reservesB, tc.exactOutput, tc.fee), func(t *testing.T) { - poolA, err := types.NewBasePool(tc.reservesA, tc.reservesB) - require.NoError(t, err) - swapA, feeA := poolA.SwapAForExactB(tc.exactOutput, tc.fee) - - poolB, err := types.NewBasePool(tc.reservesB, tc.reservesA) - require.NoError(t, err) - swapB, feeB := poolB.SwapBForExactA(tc.exactOutput, tc.fee) - - // pool must be symmetric - if we swap reserves, then swap opposite direction - // then the results should be equal - require.Equal(t, swapA, swapB, "expected swap methods to have equal swap results") - require.Equal(t, feeA, feeB, "expected swap methods to have equal fee results") - require.Equal(t, poolA.ReservesA(), poolB.ReservesB(), "expected reserves A to be equal") - require.Equal(t, poolA.ReservesB(), poolB.ReservesA(), "expected reserves B to be equal") - - assert.Equal(t, tc.expectedInput.String(), swapA.String(), "returned swap not equal") - assert.Equal(t, tc.expectedFee, feeA, "returned fee not equal") - - expectedReservesA := tc.reservesA.Add(tc.expectedInput) - expectedReservesB := tc.reservesB.Sub(tc.exactOutput) - - assert.Equal(t, expectedReservesA, poolA.ReservesA(), "expected new reserves A not equal") - assert.Equal(t, expectedReservesB, poolA.ReservesB(), "expected new reserves B not equal") - }) - } -} - -func TestBasePool_Panics_Swap_ExactInput(t *testing.T) { - testCases := []struct { - swap sdkmath.Int - fee sdk.Dec - }{ - {i(0), d("0.003")}, - {i(-1), d("0.003")}, - {i(1), d("1")}, - {i(1), d("-0.003")}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("swap=%s fee=%s", tc.swap, tc.fee), func(t *testing.T) { - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.SwapExactAForB(tc.swap, tc.fee) - }, "SwapExactAForB did not panic") - - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.SwapExactBForA(tc.swap, tc.fee) - }, "SwapExactBForA did not panic") - }) - } -} - -func TestBasePool_Panics_Swap_ExactOutput(t *testing.T) { - testCases := []struct { - swap sdkmath.Int - fee sdk.Dec - }{ - {i(0), d("0.003")}, - {i(-1), d("0.003")}, - {i(1), d("1")}, - {i(1), d("-0.003")}, - {i(1000000), d("0.003")}, - {i(1000001), d("0.003")}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("swap=%s fee=%s", tc.swap, tc.fee), func(t *testing.T) { - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.SwapAForExactB(tc.swap, tc.fee) - }, "SwapAForExactB did not panic") - - assert.Panics(t, func() { - pool, err := types.NewBasePool(i(1e6), i(1e6)) - require.NoError(t, err) - - pool.SwapBForExactA(tc.swap, tc.fee) - }, "SwapBForExactA did not panic") - }) - } -} diff --git a/x/swap/types/codec.go b/x/swap/types/codec.go deleted file mode 100644 index 2d1d5c12..00000000 --- a/x/swap/types/codec.go +++ /dev/null @@ -1,47 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" -) - -// RegisterLegacyAminoCodec registers all the necessary types and interfaces for the -// governance module. -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgDeposit{}, "swap/MsgDeposit", nil) - cdc.RegisterConcrete(&MsgWithdraw{}, "swap/MsgWithdraw", nil) - cdc.RegisterConcrete(&MsgSwapExactForTokens{}, "swap/MsgSwapExactForTokens", nil) - cdc.RegisterConcrete(&MsgSwapForExactTokens{}, "swap/MsgSwapForExactTokens", nil) -} - -// RegisterInterfaces registers proto messages under their interfaces for unmarshalling, -// in addition to registerting the msg service for handling tx msgs -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgDeposit{}, - &MsgWithdraw{}, - &MsgSwapExactForTokens{}, - &MsgSwapForExactTokens{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - // ModuleCdc represents the legacy amino codec for the module - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - RegisterLegacyAminoCodec(authzcodec.Amino) -} diff --git a/x/swap/types/common_test.go b/x/swap/types/common_test.go deleted file mode 100644 index ec6e519f..00000000 --- a/x/swap/types/common_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package types_test - -import ( - "github.com/0glabs/0g-chain/app" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func init() { - kavaConfig := sdk.GetConfig() - app.SetBech32AddressPrefixes(kavaConfig) - app.SetBip44CoinType(kavaConfig) - kavaConfig.Seal() -} diff --git a/x/swap/types/denominated_pool.go b/x/swap/types/denominated_pool.go deleted file mode 100644 index c816ce13..00000000 --- a/x/swap/types/denominated_pool.go +++ /dev/null @@ -1,160 +0,0 @@ -package types - -import ( - "fmt" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// DenominatedPool implements a denominated constant-product liquidity pool -type DenominatedPool struct { - // all pool operations are implemented in a unitless base pool - pool *BasePool - // track units of the reserveA and reserveB in base pool - denomA string - denomB string -} - -// NewDenominatedPool creates a new denominated pool from reserve coins -func NewDenominatedPool(reserves sdk.Coins) (*DenominatedPool, error) { - if len(reserves) != 2 { - return nil, errorsmod.Wrap(ErrInvalidPool, "reserves must have two denominations") - } - - // Coins should always sorted, so this is deterministic, though it does not need to be. - // The base pool calculation results do not depend on reserve order. - reservesA := reserves[0] - reservesB := reserves[1] - - pool, err := NewBasePool(reservesA.Amount, reservesB.Amount) - if err != nil { - return nil, err - } - - return &DenominatedPool{ - pool: pool, - denomA: reservesA.Denom, - denomB: reservesB.Denom, - }, nil -} - -// NewDenominatedPoolWithExistingShares creates a new denominated pool from reserve coins -func NewDenominatedPoolWithExistingShares(reserves sdk.Coins, totalShares sdkmath.Int) (*DenominatedPool, error) { - if len(reserves) != 2 { - return nil, errorsmod.Wrap(ErrInvalidPool, "reserves must have two denominations") - } - - // Coins should always sorted, so this is deterministic, though it does not need to be. - // The base pool calculation results do not depend on reserve order. - reservesA := reserves[0] - reservesB := reserves[1] - - pool, err := NewBasePoolWithExistingShares(reservesA.Amount, reservesB.Amount, totalShares) - if err != nil { - return nil, err - } - - return &DenominatedPool{ - pool: pool, - denomA: reservesA.Denom, - denomB: reservesB.Denom, - }, nil -} - -// Reserves returns the reserves held in the pool -func (p *DenominatedPool) Reserves() sdk.Coins { - return p.coins(p.pool.ReservesA(), p.pool.ReservesB()) -} - -// TotalShares returns the total shares for the pool -func (p *DenominatedPool) TotalShares() sdkmath.Int { - return p.pool.TotalShares() -} - -// IsEmpty returns true if the pool is empty -func (p *DenominatedPool) IsEmpty() bool { - return p.pool.IsEmpty() -} - -// AddLiquidity adds liquidity to the reserves and returns the added amount and shares created -func (p *DenominatedPool) AddLiquidity(deposit sdk.Coins) (sdk.Coins, sdkmath.Int) { - desiredA := deposit.AmountOf(p.denomA) - desiredB := deposit.AmountOf(p.denomB) - - actualA, actualB, shares := p.pool.AddLiquidity(desiredA, desiredB) - - return p.coins(actualA, actualB), shares -} - -// RemoveLiquidity removes liquidity from the pool -func (p *DenominatedPool) RemoveLiquidity(shares sdkmath.Int) sdk.Coins { - withdrawnA, withdrawnB := p.pool.RemoveLiquidity(shares) - - return p.coins(withdrawnA, withdrawnB) -} - -// ShareValue returns the value of the provided shares -func (p *DenominatedPool) ShareValue(shares sdkmath.Int) sdk.Coins { - valueA, valueB := p.pool.ShareValue(shares) - - return p.coins(valueA, valueB) -} - -// SwapWithExactInput trades an exact input coin for the other. Returns the positive other coin amount -// that is removed from the pool and the portion of the input coin that is used for the fee. -// It panics if the input denom does not match the pool reserves. -func (p *DenominatedPool) SwapWithExactInput(swapInput sdk.Coin, fee sdk.Dec) (sdk.Coin, sdk.Coin) { - var ( - swapOutput sdkmath.Int - feePaid sdkmath.Int - ) - - switch swapInput.Denom { - case p.denomA: - swapOutput, feePaid = p.pool.SwapExactAForB(swapInput.Amount, fee) - return p.coinB(swapOutput), p.coinA(feePaid) - case p.denomB: - swapOutput, feePaid = p.pool.SwapExactBForA(swapInput.Amount, fee) - return p.coinA(swapOutput), p.coinB(feePaid) - default: - panic(fmt.Sprintf("invalid denomination: denom '%s' does not match pool reserves", swapInput.Denom)) - } -} - -// SwapWithExactOutput trades a coin for an exact output coin b. Returns the positive input coin -// that is added to the pool, and the portion of that input that is used to pay the fee. -// Panics if the output denom does not match the pool reserves. -func (p *DenominatedPool) SwapWithExactOutput(swapOutput sdk.Coin, fee sdk.Dec) (sdk.Coin, sdk.Coin) { - var ( - swapInput sdkmath.Int - feePaid sdkmath.Int - ) - - switch swapOutput.Denom { - case p.denomA: - swapInput, feePaid = p.pool.SwapBForExactA(swapOutput.Amount, fee) - return p.coinB(swapInput), p.coinB(feePaid) - case p.denomB: - swapInput, feePaid = p.pool.SwapAForExactB(swapOutput.Amount, fee) - return p.coinA(swapInput), p.coinA(feePaid) - default: - panic(fmt.Sprintf("invalid denomination: denom '%s' does not match pool reserves", swapOutput.Denom)) - } -} - -// coins returns a new coins slice with correct reserve denoms from ordered sdk.Ints -func (p *DenominatedPool) coins(amountA, amountB sdkmath.Int) sdk.Coins { - return sdk.NewCoins(p.coinA(amountA), p.coinB(amountB)) -} - -// coinA returns a new coin denominated in denomA -func (p *DenominatedPool) coinA(amount sdkmath.Int) sdk.Coin { - return sdk.NewCoin(p.denomA, amount) -} - -// coinA returns a new coin denominated in denomB -func (p *DenominatedPool) coinB(amount sdkmath.Int) sdk.Coin { - return sdk.NewCoin(p.denomB, amount) -} diff --git a/x/swap/types/denominated_pool_test.go b/x/swap/types/denominated_pool_test.go deleted file mode 100644 index 9e3047e8..00000000 --- a/x/swap/types/denominated_pool_test.go +++ /dev/null @@ -1,183 +0,0 @@ -package types_test - -import ( - "fmt" - "testing" - - types "github.com/0glabs/0g-chain/x/swap/types" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// create a new ukava coin from int64 -func ukava(amount int64) sdk.Coin { - return sdk.NewCoin("ukava", sdkmath.NewInt(amount)) -} - -// create a new usdx coin from int64 -func usdx(amount int64) sdk.Coin { - return sdk.NewCoin("usdx", sdkmath.NewInt(amount)) -} - -// create a new hard coin from int64 -func hard(amount int64) sdk.Coin { - return sdk.NewCoin("hard", sdkmath.NewInt(amount)) -} - -func TestDenominatedPool_NewDenominatedPool_Validation(t *testing.T) { - testCases := []struct { - reservesA sdk.Coin - reservesB sdk.Coin - expectedErr string - }{ - {ukava(0), usdx(1e6), "reserves must have two denominations: invalid pool"}, - {ukava(1e6), usdx(0), "reserves must have two denominations: invalid pool"}, - {usdx(0), ukava(1e6), "reserves must have two denominations: invalid pool"}, - {usdx(0), ukava(1e6), "reserves must have two denominations: invalid pool"}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s", tc.reservesA, tc.reservesB), func(t *testing.T) { - pool, err := types.NewDenominatedPool(sdk.NewCoins(tc.reservesA, tc.reservesB)) - require.EqualError(t, err, tc.expectedErr) - assert.Nil(t, pool) - }) - } -} - -func TestDenominatedPool_NewDenominatedPoolWithExistingShares_Validation(t *testing.T) { - testCases := []struct { - reservesA sdk.Coin - reservesB sdk.Coin - totalShares sdkmath.Int - expectedErr string - }{ - {ukava(0), usdx(1e6), i(1), "reserves must have two denominations: invalid pool"}, - {usdx(0), ukava(1e6), i(1), "reserves must have two denominations: invalid pool"}, - {ukava(1e6), usdx(1e6), i(0), "total shares must be greater than zero: invalid pool"}, - {usdx(1e6), ukava(1e6), i(-1), "total shares must be greater than zero: invalid pool"}, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("reservesA=%s reservesB=%s", tc.reservesA, tc.reservesB), func(t *testing.T) { - pool, err := types.NewDenominatedPoolWithExistingShares(sdk.NewCoins(tc.reservesA, tc.reservesB), tc.totalShares) - require.EqualError(t, err, tc.expectedErr) - assert.Nil(t, pool) - }) - } -} - -func TestDenominatedPool_InitialState(t *testing.T) { - reserves := sdk.NewCoins(ukava(1e6), usdx(5e6)) - totalShares := i(2236067) - - pool, err := types.NewDenominatedPool(reserves) - require.NoError(t, err) - - assert.Equal(t, pool.Reserves(), reserves) - assert.Equal(t, pool.TotalShares(), totalShares) -} - -func TestDenominatedPool_InitialState_ExistingShares(t *testing.T) { - reserves := sdk.NewCoins(ukava(1e6), usdx(5e6)) - totalShares := i(2e6) - - pool, err := types.NewDenominatedPoolWithExistingShares(reserves, totalShares) - require.NoError(t, err) - - assert.Equal(t, pool.Reserves(), reserves) - assert.Equal(t, pool.TotalShares(), totalShares) -} - -func TestDenominatedPool_ShareValue(t *testing.T) { - reserves := sdk.NewCoins(ukava(10e6), usdx(50e6)) - - pool, err := types.NewDenominatedPool(reserves) - require.NoError(t, err) - - assert.Equal(t, reserves, pool.ShareValue(pool.TotalShares())) - - halfReserves := sdk.NewCoins(ukava(4999999), usdx(24999998)) - assert.Equal(t, halfReserves, pool.ShareValue(pool.TotalShares().Quo(i(2)))) -} - -func TestDenominatedPool_AddLiquidity(t *testing.T) { - reserves := sdk.NewCoins(ukava(10e6), usdx(50e6)) - desired := sdk.NewCoins(ukava(1e6), usdx(1e6)) - - pool, err := types.NewDenominatedPool(reserves) - require.NoError(t, err) - initialShares := pool.TotalShares() - - deposit, shares := pool.AddLiquidity(desired) - require.True(t, shares.IsPositive()) - require.True(t, deposit.IsAllPositive()) - - assert.Equal(t, reserves.Add(deposit...), pool.Reserves()) - assert.Equal(t, initialShares.Add(shares), pool.TotalShares()) -} - -func TestDenominatedPool_RemoveLiquidity(t *testing.T) { - reserves := sdk.NewCoins(ukava(10e6), usdx(50e6)) - - pool, err := types.NewDenominatedPool(reserves) - require.NoError(t, err) - - withdraw := pool.RemoveLiquidity(pool.TotalShares()) - - assert.True(t, pool.Reserves().IsZero()) - assert.True(t, pool.TotalShares().IsZero()) - assert.True(t, pool.IsEmpty()) - assert.Equal(t, reserves, withdraw) -} - -func TestDenominatedPool_SwapWithExactInput(t *testing.T) { - reserves := sdk.NewCoins(ukava(10e6), usdx(50e6)) - - pool, err := types.NewDenominatedPool(reserves) - require.NoError(t, err) - - output, fee := pool.SwapWithExactInput(ukava(1e6), d("0.003")) - - assert.Equal(t, usdx(4533054), output) - assert.Equal(t, ukava(3000), fee) - assert.Equal(t, sdk.NewCoins(ukava(11e6), usdx(45466946)), pool.Reserves()) - - pool, err = types.NewDenominatedPool(reserves) - require.NoError(t, err) - - output, fee = pool.SwapWithExactInput(usdx(5e6), d("0.003")) - - assert.Equal(t, ukava(906610), output) - assert.Equal(t, usdx(15000), fee) - assert.Equal(t, sdk.NewCoins(ukava(9093390), usdx(55e6)), pool.Reserves()) - - assert.Panics(t, func() { pool.SwapWithExactInput(hard(1e6), d("0.003")) }, "SwapWithExactInput did not panic on invalid denomination") -} - -func TestDenominatedPool_SwapWithExactOuput(t *testing.T) { - reserves := sdk.NewCoins(ukava(10e6), usdx(50e6)) - - pool, err := types.NewDenominatedPool(reserves) - require.NoError(t, err) - - input, fee := pool.SwapWithExactOutput(ukava(1e6), d("0.003")) - - assert.Equal(t, usdx(5572273), input) - assert.Equal(t, usdx(16717), fee) - assert.Equal(t, sdk.NewCoins(ukava(9e6), usdx(55572273)), pool.Reserves()) - - pool, err = types.NewDenominatedPool(reserves) - require.NoError(t, err) - - input, fee = pool.SwapWithExactOutput(usdx(5e6), d("0.003")) - - assert.Equal(t, ukava(1114456), input) - assert.Equal(t, ukava(3344), fee) - assert.Equal(t, sdk.NewCoins(ukava(11114456), usdx(45e6)), pool.Reserves()) - - assert.Panics(t, func() { pool.SwapWithExactOutput(hard(1e6), d("0.003")) }, "SwapWithExactOutput did not panic on invalid denomination") -} diff --git a/x/swap/types/errors.go b/x/swap/types/errors.go deleted file mode 100644 index 5c116d71..00000000 --- a/x/swap/types/errors.go +++ /dev/null @@ -1,18 +0,0 @@ -package types - -import errorsmod "cosmossdk.io/errors" - -// swap module errors -var ( - ErrNotAllowed = errorsmod.Register(ModuleName, 2, "not allowed") - ErrInvalidDeadline = errorsmod.Register(ModuleName, 3, "invalid deadline") - ErrDeadlineExceeded = errorsmod.Register(ModuleName, 4, "deadline exceeded") - ErrSlippageExceeded = errorsmod.Register(ModuleName, 5, "slippage exceeded") - ErrInvalidPool = errorsmod.Register(ModuleName, 6, "invalid pool") - ErrInvalidSlippage = errorsmod.Register(ModuleName, 7, "invalid slippage") - ErrInsufficientLiquidity = errorsmod.Register(ModuleName, 8, "insufficient liquidity") - ErrInvalidShares = errorsmod.Register(ModuleName, 9, "invalid shares") - ErrDepositNotFound = errorsmod.Register(ModuleName, 10, "deposit not found") - ErrInvalidCoin = errorsmod.Register(ModuleName, 11, "invalid coin") - ErrNotImplemented = errorsmod.Register(ModuleName, 12, "not implemented") -) diff --git a/x/swap/types/events.go b/x/swap/types/events.go deleted file mode 100644 index 8bb9519d..00000000 --- a/x/swap/types/events.go +++ /dev/null @@ -1,18 +0,0 @@ -package types - -// Event types for swap module -const ( - AttributeValueCategory = ModuleName - EventTypeSwapDeposit = "swap_deposit" - EventTypeSwapWithdraw = "swap_withdraw" - EventTypeSwapTrade = "swap_trade" - AttributeKeyPoolID = "pool_id" - AttributeKeyDepositor = "depositor" - AttributeKeyShares = "shares" - AttributeKeyOwner = "owner" - AttributeKeyRequester = "requester" - AttributeKeySwapInput = "input" - AttributeKeySwapOutput = "output" - AttributeKeyFeePaid = "fee" - AttributeKeyExactDirection = "exact" -) diff --git a/x/swap/types/expected_keepers.go b/x/swap/types/expected_keepers.go deleted file mode 100644 index 258b9aea..00000000 --- a/x/swap/types/expected_keepers.go +++ /dev/null @@ -1,32 +0,0 @@ -package types - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// AccountKeeper defines the expected account keeper (noalias) -type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI - SetModuleAccount(sdk.Context, types.ModuleAccountI) - - // moved in from supply - GetModuleAddress(name string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, name string) types.ModuleAccountI -} - -// BankKeeper defines the expected interface needed to retrieve account balances. -type BankKeeper interface { - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error -} - -// SwapHooks are event hooks called when a user's deposit to a swap pool changes. -type SwapHooks interface { - AfterPoolDepositCreated(ctx sdk.Context, poolID string, depositor sdk.AccAddress, sharedOwned sdkmath.Int) - BeforePoolDepositModified(ctx sdk.Context, poolID string, depositor sdk.AccAddress, sharedOwned sdkmath.Int) -} diff --git a/x/swap/types/genesis.go b/x/swap/types/genesis.go deleted file mode 100644 index 6738e950..00000000 --- a/x/swap/types/genesis.go +++ /dev/null @@ -1,78 +0,0 @@ -package types - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type poolShares struct { - totalShares sdkmath.Int - totalSharesOwned sdkmath.Int -} - -var ( - // DefaultPoolRecords is used to set default records in default genesis state - DefaultPoolRecords = PoolRecords{} - // DefaultShareRecords is used to set default records in default genesis state - DefaultShareRecords = ShareRecords{} -) - -// NewGenesisState creates a new genesis state. -func NewGenesisState(params Params, poolRecords PoolRecords, shareRecords ShareRecords) GenesisState { - return GenesisState{ - Params: params, - PoolRecords: poolRecords, - ShareRecords: shareRecords, - } -} - -// Validate validates the module's genesis state -func (gs GenesisState) Validate() error { - if err := gs.Params.Validate(); err != nil { - return err - } - if err := gs.PoolRecords.Validate(); err != nil { - return err - } - if err := gs.ShareRecords.Validate(); err != nil { - return err - } - - totalShares := make(map[string]poolShares) - for _, pr := range gs.PoolRecords { - totalShares[pr.PoolID] = poolShares{ - totalShares: pr.TotalShares, - totalSharesOwned: sdk.ZeroInt(), - } - } - for _, sr := range gs.ShareRecords { - if shares, found := totalShares[sr.PoolID]; found { - shares.totalSharesOwned = shares.totalSharesOwned.Add(sr.SharesOwned) - totalShares[sr.PoolID] = shares - } else { - totalShares[sr.PoolID] = poolShares{ - totalShares: sdk.ZeroInt(), - totalSharesOwned: sr.SharesOwned, - } - } - } - - for poolID, ps := range totalShares { - if !ps.totalShares.Equal(ps.totalSharesOwned) { - return fmt.Errorf("total depositor shares %s not equal to pool '%s' total shares %s", ps.totalSharesOwned.String(), poolID, ps.totalShares.String()) - } - } - - return nil -} - -// DefaultGenesisState returns a default genesis state -func DefaultGenesisState() GenesisState { - return NewGenesisState( - DefaultParams(), - DefaultPoolRecords, - DefaultShareRecords, - ) -} diff --git a/x/swap/types/genesis.pb.go b/x/swap/types/genesis.pb.go deleted file mode 100644 index 72acb655..00000000 --- a/x/swap/types/genesis.pb.go +++ /dev/null @@ -1,454 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/swap/v1beta1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// GenesisState defines the swap module's genesis state. -type GenesisState struct { - // params defines all the parameters related to swap - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - // pool_records defines the available pools - PoolRecords PoolRecords `protobuf:"bytes,2,rep,name=pool_records,json=poolRecords,proto3,castrepeated=PoolRecords" json:"pool_records"` - // share_records defines the owned shares of each pool - ShareRecords ShareRecords `protobuf:"bytes,3,rep,name=share_records,json=shareRecords,proto3,castrepeated=ShareRecords" json:"share_records"` -} - -func (m *GenesisState) Reset() { *m = GenesisState{} } -func (m *GenesisState) String() string { return proto.CompactTextString(m) } -func (*GenesisState) ProtoMessage() {} -func (*GenesisState) Descriptor() ([]byte, []int) { - return fileDescriptor_b1a1a1687f484a21, []int{0} -} -func (m *GenesisState) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisState) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisState.Merge(m, src) -} -func (m *GenesisState) XXX_Size() int { - return m.Size() -} -func (m *GenesisState) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisState.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisState proto.InternalMessageInfo - -func (m *GenesisState) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -func (m *GenesisState) GetPoolRecords() PoolRecords { - if m != nil { - return m.PoolRecords - } - return nil -} - -func (m *GenesisState) GetShareRecords() ShareRecords { - if m != nil { - return m.ShareRecords - } - return nil -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "kava.swap.v1beta1.GenesisState") -} - -func init() { proto.RegisterFile("kava/swap/v1beta1/genesis.proto", fileDescriptor_b1a1a1687f484a21) } - -var fileDescriptor_b1a1a1687f484a21 = []byte{ - // 289 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcf, 0x4e, 0x2c, 0x4b, - 0xd4, 0x2f, 0x2e, 0x4f, 0x2c, 0xd0, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0x4f, - 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x04, 0x29, 0xd0, - 0x03, 0x29, 0xd0, 0x83, 0x2a, 0x90, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0xcb, 0xea, 0x83, 0x58, - 0x10, 0x85, 0x52, 0x32, 0x98, 0x26, 0x81, 0x75, 0x81, 0x65, 0x95, 0x7e, 0x32, 0x72, 0xf1, 0xb8, - 0x43, 0x0c, 0x0e, 0x2e, 0x49, 0x2c, 0x49, 0x15, 0x32, 0xe7, 0x62, 0x2b, 0x48, 0x2c, 0x4a, 0xcc, - 0x2d, 0x96, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x36, 0x92, 0xd4, 0xc3, 0xb0, 0x48, 0x2f, 0x00, 0xac, - 0xc0, 0x89, 0xe5, 0xc4, 0x3d, 0x79, 0x86, 0x20, 0xa8, 0x72, 0xa1, 0x50, 0x2e, 0x9e, 0x82, 0xfc, - 0xfc, 0x9c, 0xf8, 0xa2, 0xd4, 0xe4, 0xfc, 0xa2, 0x94, 0x62, 0x09, 0x26, 0x05, 0x66, 0x0d, 0x6e, - 0x23, 0x59, 0x6c, 0xda, 0xf3, 0xf3, 0x73, 0x82, 0xc0, 0xaa, 0x9c, 0x84, 0x41, 0x46, 0xac, 0xba, - 0x2f, 0xcf, 0x8d, 0x10, 0x2b, 0x0e, 0xe2, 0x2e, 0x40, 0x70, 0x84, 0x22, 0xb9, 0x78, 0x8b, 0x33, - 0x12, 0x8b, 0x52, 0xe1, 0xe6, 0x32, 0x83, 0xcd, 0x95, 0xc3, 0x62, 0x6e, 0x30, 0x48, 0x1d, 0xd4, - 0x60, 0x11, 0xa8, 0xc1, 0x3c, 0x48, 0x82, 0xc5, 0x41, 0x3c, 0xc5, 0x48, 0x3c, 0x27, 0xc7, 0x13, - 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, 0x39, 0x86, - 0x0b, 0x8f, 0xe5, 0x18, 0x6e, 0x3c, 0x96, 0x63, 0x88, 0x52, 0x4f, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, - 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x37, 0x48, 0xcf, 0x49, 0x4c, 0x2a, 0xd6, 0x37, 0x48, 0xd7, 0x4d, - 0xce, 0x48, 0xcc, 0xcc, 0xd3, 0xaf, 0x80, 0x84, 0x65, 0x49, 0x65, 0x41, 0x6a, 0x71, 0x12, 0x1b, - 0x38, 0x14, 0x8d, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x9e, 0xfc, 0xbc, 0xdc, 0xaf, 0x01, 0x00, - 0x00, -} - -func (m *GenesisState) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ShareRecords) > 0 { - for iNdEx := len(m.ShareRecords) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ShareRecords[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.PoolRecords) > 0 { - for iNdEx := len(m.PoolRecords) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.PoolRecords[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *GenesisState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.PoolRecords) > 0 { - for _, e := range m.PoolRecords { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.ShareRecords) > 0 { - for _, e := range m.ShareRecords { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *GenesisState) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolRecords", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PoolRecords = append(m.PoolRecords, PoolRecord{}) - if err := m.PoolRecords[len(m.PoolRecords)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ShareRecords", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ShareRecords = append(m.ShareRecords, ShareRecord{}) - if err := m.ShareRecords[len(m.ShareRecords)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/swap/types/genesis_test.go b/x/swap/types/genesis_test.go deleted file mode 100644 index 8e33e594..00000000 --- a/x/swap/types/genesis_test.go +++ /dev/null @@ -1,336 +0,0 @@ -package types_test - -import ( - "encoding/json" - "testing" - - "github.com/0glabs/0g-chain/x/swap/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "sigs.k8s.io/yaml" -) - -func TestGenesis_Default(t *testing.T) { - defaultGenesis := types.DefaultGenesisState() - - require.NoError(t, defaultGenesis.Validate()) - - defaultParams := types.DefaultParams() - assert.Equal(t, defaultParams, defaultGenesis.Params) -} - -func TestGenesis_Validate_SwapFee(t *testing.T) { - type args struct { - name string - swapFee sdk.Dec - expectErr bool - } - // More comprehensive swap fee tests are in prams_test.go - testCases := []args{ - { - "normal", - sdk.MustNewDecFromStr("0.25"), - false, - }, - { - "negative", - sdk.MustNewDecFromStr("-0.5"), - true, - }, - { - "greater than 1.0", - sdk.MustNewDecFromStr("1.001"), - true, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - genesisState := types.GenesisState{ - Params: types.Params{ - AllowedPools: types.DefaultAllowedPools, - SwapFee: tc.swapFee, - }, - } - - err := genesisState.Validate() - if tc.expectErr { - assert.NotNil(t, err) - } else { - assert.Nil(t, err) - } - }) - } -} - -func TestGenesis_Validate_AllowedPools(t *testing.T) { - type args struct { - name string - pairs types.AllowedPools - expectErr bool - } - // More comprehensive pair validation tests are in pair_test.go, params_test.go - testCases := []args{ - { - "normal", - types.DefaultAllowedPools, - false, - }, - { - "invalid", - types.AllowedPools{ - { - TokenA: "same", - TokenB: "same", - }, - }, - true, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - genesisState := types.GenesisState{ - Params: types.Params{ - AllowedPools: tc.pairs, - SwapFee: types.DefaultSwapFee, - }, - } - - err := genesisState.Validate() - if tc.expectErr { - assert.NotNil(t, err) - } else { - assert.Nil(t, err) - } - }) - } -} - -func TestGenesis_JSONEncoding(t *testing.T) { - raw := `{ - "params": { - "allowed_pools": [ - { - "token_a": "ukava", - "token_b": "usdx" - }, - { - "token_a": "hard", - "token_b": "busd" - } - ], - "swap_fee": "0.003000000000000000" - }, - "pool_records": [ - { - "pool_id": "ukava:usdx", - "reserves_a": { "denom": "ukava", "amount": "1000000" }, - "reserves_b": { "denom": "usdx", "amount": "5000000" }, - "total_shares": "3000000" - }, - { - "pool_id": "hard:usdx", - "reserves_a": { "denom": "ukava", "amount": "1000000" }, - "reserves_b": { "denom": "usdx", "amount": "2000000" }, - "total_shares": "2000000" - } - ], - "share_records": [ - { - "depositor": "kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w", - "pool_id": "ukava:usdx", - "shares_owned": "100000" - }, - { - "depositor": "kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea", - "pool_id": "hard:usdx", - "shares_owned": "200000" - } - ] - }` - - var state types.GenesisState - err := json.Unmarshal([]byte(raw), &state) - require.NoError(t, err) - - assert.Equal(t, 2, len(state.Params.AllowedPools)) - assert.Equal(t, sdk.MustNewDecFromStr("0.003"), state.Params.SwapFee) - assert.Equal(t, 2, len(state.PoolRecords)) - assert.Equal(t, 2, len(state.ShareRecords)) -} - -func TestGenesis_YAMLEncoding(t *testing.T) { - expected := `params: - allowed_pools: - - token_a: ukava - token_b: usdx - - token_a: hard - token_b: busd - swap_fee: "0.003000000000000000" -pool_records: -- pool_id: ukava:usdx - reserves_a: - amount: "1000000" - denom: ukava - reserves_b: - amount: "5000000" - denom: usdx - total_shares: "3000000" -- pool_id: hard:usdx - reserves_a: - amount: "1000000" - denom: hard - reserves_b: - amount: "2000000" - denom: usdx - total_shares: "1500000" -share_records: -- depositor: kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w - pool_id: ukava:usdx - shares_owned: "100000" -- depositor: kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea - pool_id: hard:usdx - shares_owned: "200000" -` - - depositor_1, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - require.NoError(t, err) - depositor_2, err := sdk.AccAddressFromBech32("kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea") - require.NoError(t, err) - - state := types.NewGenesisState( - types.NewParams( - types.NewAllowedPools( - types.NewAllowedPool("ukava", "usdx"), - types.NewAllowedPool("hard", "busd"), - ), - sdk.MustNewDecFromStr("0.003"), - ), - types.PoolRecords{ - types.NewPoolRecord(sdk.NewCoins(ukava(1e6), usdx(5e6)), i(3e6)), - types.NewPoolRecord(sdk.NewCoins(hard(1e6), usdx(2e6)), i(15e5)), - }, - types.ShareRecords{ - types.NewShareRecord(depositor_1, types.PoolID("ukava", "usdx"), i(1e5)), - types.NewShareRecord(depositor_2, types.PoolID("hard", "usdx"), i(2e5)), - }, - ) - - data, err := yaml.Marshal(state) - require.NoError(t, err) - - assert.Equal(t, expected, string(data)) -} - -func TestGenesis_ValidatePoolRecords(t *testing.T) { - invalidPoolRecord := types.NewPoolRecord(sdk.NewCoins(ukava(1e6), usdx(5e6)), i(-1)) - - state := types.NewGenesisState( - types.DefaultParams(), - types.PoolRecords{invalidPoolRecord}, - types.ShareRecords{}, - ) - - assert.Error(t, state.Validate()) -} - -func TestGenesis_ValidateShareRecords(t *testing.T) { - depositor, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - require.NoError(t, err) - - invalidShareRecord := types.NewShareRecord(depositor, "", i(-1)) - - state := types.NewGenesisState( - types.DefaultParams(), - types.PoolRecords{}, - types.ShareRecords{invalidShareRecord}, - ) - - assert.Error(t, state.Validate()) -} - -func TestGenesis_Validate_PoolShareIntegration(t *testing.T) { - depositor_1, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - require.NoError(t, err) - depositor_2, err := sdk.AccAddressFromBech32("kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea") - require.NoError(t, err) - - testCases := []struct { - name string - poolRecords types.PoolRecords - shareRecords types.ShareRecords - expectedErr string - }{ - { - name: "single pool record, zero share records", - poolRecords: types.PoolRecords{ - types.NewPoolRecord(sdk.NewCoins(ukava(1e6), usdx(5e6)), i(3e6)), - }, - shareRecords: types.ShareRecords{}, - expectedErr: "total depositor shares 0 not equal to pool 'ukava:usdx' total shares 3000000", - }, - { - name: "zero pool records, one share record", - poolRecords: types.PoolRecords{}, - shareRecords: types.ShareRecords{ - types.NewShareRecord(depositor_1, types.PoolID("ukava", "usdx"), i(5e6)), - }, - expectedErr: "total depositor shares 5000000 not equal to pool 'ukava:usdx' total shares 0", - }, - { - name: "one pool record, one share record", - poolRecords: types.PoolRecords{ - types.NewPoolRecord(sdk.NewCoins(ukava(1e6), usdx(5e6)), i(3e6)), - }, - shareRecords: types.ShareRecords{ - types.NewShareRecord(depositor_1, "ukava:usdx", i(15e5)), - }, - expectedErr: "total depositor shares 1500000 not equal to pool 'ukava:usdx' total shares 3000000", - }, - { - name: "more than one pool records, more than one share record", - poolRecords: types.PoolRecords{ - types.NewPoolRecord(sdk.NewCoins(ukava(1e6), usdx(5e6)), i(3e6)), - types.NewPoolRecord(sdk.NewCoins(hard(1e6), usdx(2e6)), i(2e6)), - }, - shareRecords: types.ShareRecords{ - types.NewShareRecord(depositor_1, types.PoolID("ukava", "usdx"), i(15e5)), - types.NewShareRecord(depositor_2, types.PoolID("ukava", "usdx"), i(15e5)), - types.NewShareRecord(depositor_1, types.PoolID("hard", "usdx"), i(1e6)), - }, - expectedErr: "total depositor shares 1000000 not equal to pool 'hard:usdx' total shares 2000000", - }, - { - name: "valid case with many pool records and share records", - poolRecords: types.PoolRecords{ - types.NewPoolRecord(sdk.NewCoins(ukava(1e6), usdx(5e6)), i(3e6)), - types.NewPoolRecord(sdk.NewCoins(hard(1e6), usdx(2e6)), i(2e6)), - types.NewPoolRecord(sdk.NewCoins(hard(7e6), ukava(10e6)), i(8e6)), - }, - shareRecords: types.ShareRecords{ - types.NewShareRecord(depositor_1, types.PoolID("ukava", "usdx"), i(15e5)), - types.NewShareRecord(depositor_2, types.PoolID("ukava", "usdx"), i(15e5)), - types.NewShareRecord(depositor_1, types.PoolID("hard", "usdx"), i(2e6)), - types.NewShareRecord(depositor_1, types.PoolID("hard", "ukava"), i(3e6)), - types.NewShareRecord(depositor_2, types.PoolID("hard", "ukava"), i(5e6)), - }, - expectedErr: "", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - state := types.NewGenesisState(types.DefaultParams(), tc.poolRecords, tc.shareRecords) - err := state.Validate() - - if tc.expectedErr == "" { - assert.NoError(t, err) - } else { - assert.EqualError(t, err, tc.expectedErr) - } - }) - } -} diff --git a/x/swap/types/keys.go b/x/swap/types/keys.go deleted file mode 100644 index a3e52a58..00000000 --- a/x/swap/types/keys.go +++ /dev/null @@ -1,47 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // ModuleName name that will be used throughout the module - ModuleName = "swap" - - // ModuleAccountName name of module account used to hold liquidity - ModuleAccountName = "swap" - - // StoreKey Top level store key where all module items will be stored - StoreKey = ModuleName - - // RouterKey Top level router key - RouterKey = ModuleName - - // DefaultParamspace default name for parameter store - DefaultParamspace = ModuleName -) - -// key prefixes for store -var ( - PoolKeyPrefix = []byte{0x01} - DepositorPoolSharesPrefix = []byte{0x02} - - sep = []byte("|") -) - -// PoolKey returns a key generated from a poolID -func PoolKey(poolID string) []byte { - return []byte(poolID) -} - -// DepositorPoolSharesKey returns a key from a depositor and poolID -func DepositorPoolSharesKey(depositor sdk.AccAddress, poolID string) []byte { - return createKey(depositor, sep, []byte(poolID)) -} - -func createKey(bytes ...[]byte) (r []byte) { - for _, b := range bytes { - r = append(r, b...) - } - return -} diff --git a/x/swap/types/keys_test.go b/x/swap/types/keys_test.go deleted file mode 100644 index e59c347c..00000000 --- a/x/swap/types/keys_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/0glabs/0g-chain/x/swap/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" -) - -func TestKeys(t *testing.T) { - key := types.PoolKey(types.PoolID("ukava", "usdx")) - assert.Equal(t, types.PoolID("ukava", "usdx"), string(key)) - - key = types.DepositorPoolSharesKey(sdk.AccAddress("testaddress1"), types.PoolID("ukava", "usdx")) - assert.Equal(t, string(sdk.AccAddress("testaddress1"))+"|"+types.PoolID("ukava", "usdx"), string(key)) -} diff --git a/x/swap/types/mocks/swap_hooks.go b/x/swap/types/mocks/swap_hooks.go deleted file mode 100644 index 674f17cb..00000000 --- a/x/swap/types/mocks/swap_hooks.go +++ /dev/null @@ -1,25 +0,0 @@ -// Code generated by mockery 2.7.4. DO NOT EDIT. - -package mocks - -import ( - math "cosmossdk.io/math" - mock "github.com/stretchr/testify/mock" - - types "github.com/cosmos/cosmos-sdk/types" -) - -// SwapHooks is an autogenerated mock type for the SwapHooks type -type SwapHooks struct { - mock.Mock -} - -// AfterPoolDepositCreated provides a mock function with given fields: ctx, poolID, depositor, sharedOwned -func (_m *SwapHooks) AfterPoolDepositCreated(ctx types.Context, poolID string, depositor types.AccAddress, sharedOwned math.Int) { - _m.Called(ctx, poolID, depositor, sharedOwned) -} - -// BeforePoolDepositModified provides a mock function with given fields: ctx, poolID, depositor, sharedOwned -func (_m *SwapHooks) BeforePoolDepositModified(ctx types.Context, poolID string, depositor types.AccAddress, sharedOwned math.Int) { - _m.Called(ctx, poolID, depositor, sharedOwned) -} diff --git a/x/swap/types/msg.go b/x/swap/types/msg.go deleted file mode 100644 index b415a01c..00000000 --- a/x/swap/types/msg.go +++ /dev/null @@ -1,342 +0,0 @@ -package types - -import ( - "time" - - errorsmod "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -const ( - // TypeMsgDeposit represents the type string for MsgDeposit - TypeMsgDeposit = "swap_deposit" - // TypeMsgWithdraw represents the type string for MsgWithdraw - TypeMsgWithdraw = "swap_withdraw" - // TypeSwapExactForTokens represents the type string for MsgSwapExactForTokens - TypeSwapExactForTokens = "swap_exact_for_tokens" - // TypeSwapForExactTokens represents the type string for MsgSwapForExactTokens - TypeSwapForExactTokens = "swap_for_exact_tokens" -) - -var ( - _ sdk.Msg = &MsgDeposit{} - _ MsgWithDeadline = &MsgDeposit{} - _ sdk.Msg = &MsgWithdraw{} - _ MsgWithDeadline = &MsgWithdraw{} - _ sdk.Msg = &MsgSwapExactForTokens{} - _ MsgWithDeadline = &MsgSwapExactForTokens{} - _ sdk.Msg = &MsgSwapForExactTokens{} - _ MsgWithDeadline = &MsgSwapForExactTokens{} -) - -// MsgWithDeadline allows messages to define a deadline of when they are considered invalid -type MsgWithDeadline interface { - GetDeadline() time.Time - DeadlineExceeded(blockTime time.Time) bool -} - -// NewMsgDeposit returns a new MsgDeposit -func NewMsgDeposit(depositor string, tokenA sdk.Coin, tokenB sdk.Coin, slippage sdk.Dec, deadline int64) *MsgDeposit { - return &MsgDeposit{ - Depositor: depositor, - TokenA: tokenA, - TokenB: tokenB, - Slippage: slippage, - Deadline: deadline, - } -} - -// Route return the message type used for routing the message. -func (msg MsgDeposit) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgDeposit) Type() string { return TypeMsgDeposit } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgDeposit) ValidateBasic() error { - if msg.Depositor == "" { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "depositor address cannot be empty") - } - - if _, err := sdk.AccAddressFromBech32(msg.Depositor); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid depositor address: %s", err) - } - - if !msg.TokenA.IsValid() || msg.TokenA.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "token a deposit amount %s", msg.TokenA) - } - - if !msg.TokenB.IsValid() || msg.TokenB.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "token b deposit amount %s", msg.TokenB) - } - - if msg.TokenA.Denom == msg.TokenB.Denom { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, "denominations can not be equal") - } - - if msg.Slippage.IsNil() { - return errorsmod.Wrapf(ErrInvalidSlippage, "slippage must be set") - } - - if msg.Slippage.IsNegative() { - return errorsmod.Wrapf(ErrInvalidSlippage, "slippage can not be negative") - } - - if msg.Deadline <= 0 { - return errorsmod.Wrapf(ErrInvalidDeadline, "deadline %d", msg.Deadline) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgDeposit) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgDeposit) GetSigners() []sdk.AccAddress { - depositor, _ := sdk.AccAddressFromBech32(msg.Depositor) - return []sdk.AccAddress{depositor} -} - -// GetDeadline returns the time at which the msg is considered invalid -func (msg MsgDeposit) GetDeadline() time.Time { - return time.Unix(msg.Deadline, 0) -} - -// DeadlineExceeded returns if the msg has exceeded it's deadline -func (msg MsgDeposit) DeadlineExceeded(blockTime time.Time) bool { - return blockTime.Unix() >= msg.Deadline -} - -// NewMsgWithdraw returns a new MsgWithdraw -func NewMsgWithdraw(from string, shares sdkmath.Int, minTokenA, minTokenB sdk.Coin, deadline int64) *MsgWithdraw { - return &MsgWithdraw{ - From: from, - Shares: shares, - MinTokenA: minTokenA, - MinTokenB: minTokenB, - Deadline: deadline, - } -} - -// Route return the message type used for routing the message. -func (msg MsgWithdraw) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgWithdraw) Type() string { return TypeMsgWithdraw } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgWithdraw) ValidateBasic() error { - if msg.From == "" { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "from address cannot be empty") - } - - if _, err := sdk.AccAddressFromBech32(msg.From); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid from address: %s", err) - } - - if msg.Shares.IsNil() { - return errorsmod.Wrapf(ErrInvalidShares, "shares must be set") - } - - if msg.Shares.IsZero() || msg.Shares.IsNegative() { - return errorsmod.Wrapf(ErrInvalidShares, msg.Shares.String()) - } - - if !msg.MinTokenA.IsValid() || msg.MinTokenA.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "min token a amount %s", msg.MinTokenA) - } - - if !msg.MinTokenB.IsValid() || msg.MinTokenB.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "min token b amount %s", msg.MinTokenB) - } - - if msg.MinTokenA.Denom == msg.MinTokenB.Denom { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, "denominations can not be equal") - } - - if msg.Deadline <= 0 { - return errorsmod.Wrapf(ErrInvalidDeadline, "deadline %d", msg.Deadline) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgWithdraw) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgWithdraw) GetSigners() []sdk.AccAddress { - from, _ := sdk.AccAddressFromBech32(msg.From) - return []sdk.AccAddress{from} -} - -// GetDeadline returns the time at which the msg is considered invalid -func (msg MsgWithdraw) GetDeadline() time.Time { - return time.Unix(msg.Deadline, 0) -} - -// DeadlineExceeded returns if the msg has exceeded it's deadline -func (msg MsgWithdraw) DeadlineExceeded(blockTime time.Time) bool { - return blockTime.Unix() >= msg.Deadline -} - -// NewMsgSwapExactForTokens returns a new MsgSwapExactForTokens -func NewMsgSwapExactForTokens(requester string, exactTokenA sdk.Coin, tokenB sdk.Coin, slippage sdk.Dec, deadline int64) *MsgSwapExactForTokens { - return &MsgSwapExactForTokens{ - Requester: requester, - ExactTokenA: exactTokenA, - TokenB: tokenB, - Slippage: slippage, - Deadline: deadline, - } -} - -// Route return the message type used for routing the message. -func (msg MsgSwapExactForTokens) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgSwapExactForTokens) Type() string { return TypeSwapExactForTokens } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgSwapExactForTokens) ValidateBasic() error { - if msg.Requester == "" { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "requester address cannot be empty") - } - - if _, err := sdk.AccAddressFromBech32(msg.Requester); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid requester address: %s", err) - } - - if !msg.ExactTokenA.IsValid() || msg.ExactTokenA.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "exact token a deposit amount %s", msg.ExactTokenA) - } - - if !msg.TokenB.IsValid() || msg.TokenB.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "token b deposit amount %s", msg.TokenB) - } - - if msg.ExactTokenA.Denom == msg.TokenB.Denom { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, "denominations can not be equal") - } - - if msg.Slippage.IsNil() { - return errorsmod.Wrapf(ErrInvalidSlippage, "slippage must be set") - } - - if msg.Slippage.IsNegative() { - return errorsmod.Wrapf(ErrInvalidSlippage, "slippage can not be negative") - } - - if msg.Deadline <= 0 { - return errorsmod.Wrapf(ErrInvalidDeadline, "deadline %d", msg.Deadline) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgSwapExactForTokens) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgSwapExactForTokens) GetSigners() []sdk.AccAddress { - requester, _ := sdk.AccAddressFromBech32(msg.Requester) - return []sdk.AccAddress{requester} -} - -// GetDeadline returns the time at which the msg is considered invalid -func (msg MsgSwapExactForTokens) GetDeadline() time.Time { - return time.Unix(msg.Deadline, 0) -} - -// DeadlineExceeded returns if the msg has exceeded it's deadline -func (msg MsgSwapExactForTokens) DeadlineExceeded(blockTime time.Time) bool { - return blockTime.Unix() >= msg.Deadline -} - -// NewMsgSwapForExactTokens returns a new MsgSwapForExactTokens -func NewMsgSwapForExactTokens(requester string, tokenA sdk.Coin, exactTokenB sdk.Coin, slippage sdk.Dec, deadline int64) *MsgSwapForExactTokens { - return &MsgSwapForExactTokens{ - Requester: requester, - TokenA: tokenA, - ExactTokenB: exactTokenB, - Slippage: slippage, - Deadline: deadline, - } -} - -// Route return the message type used for routing the message. -func (msg MsgSwapForExactTokens) Route() string { return RouterKey } - -// Type returns a human-readable string for the message, intended for utilization within tags. -func (msg MsgSwapForExactTokens) Type() string { return TypeSwapForExactTokens } - -// ValidateBasic does a simple validation check that doesn't require access to any other information. -func (msg MsgSwapForExactTokens) ValidateBasic() error { - if msg.Requester == "" { - return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "requester address cannot be empty") - } - - if _, err := sdk.AccAddressFromBech32(msg.Requester); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid requester address: %s", err) - } - - if !msg.TokenA.IsValid() || msg.TokenA.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "token a deposit amount %s", msg.TokenA) - } - - if !msg.ExactTokenB.IsValid() || msg.ExactTokenB.IsZero() { - return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "exact token b deposit amount %s", msg.ExactTokenB) - } - - if msg.TokenA.Denom == msg.ExactTokenB.Denom { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, "denominations can not be equal") - } - - if msg.Slippage.IsNil() { - return errorsmod.Wrapf(ErrInvalidSlippage, "slippage must be set") - } - - if msg.Slippage.IsNegative() { - return errorsmod.Wrapf(ErrInvalidSlippage, "slippage can not be negative") - } - - if msg.Deadline <= 0 { - return errorsmod.Wrapf(ErrInvalidDeadline, "deadline %d", msg.Deadline) - } - - return nil -} - -// GetSignBytes gets the canonical byte representation of the Msg. -func (msg MsgSwapForExactTokens) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(&msg) - return sdk.MustSortJSON(bz) -} - -// GetSigners returns the addresses of signers that must sign. -func (msg MsgSwapForExactTokens) GetSigners() []sdk.AccAddress { - requester, _ := sdk.AccAddressFromBech32(msg.Requester) - return []sdk.AccAddress{requester} -} - -// GetDeadline returns the time at which the msg is considered invalid -func (msg MsgSwapForExactTokens) GetDeadline() time.Time { - return time.Unix(msg.Deadline, 0) -} - -// DeadlineExceeded returns if the msg has exceeded it's deadline -func (msg MsgSwapForExactTokens) DeadlineExceeded(blockTime time.Time) bool { - return blockTime.Unix() >= msg.Deadline -} diff --git a/x/swap/types/msg_test.go b/x/swap/types/msg_test.go deleted file mode 100644 index e1ebbc8c..00000000 --- a/x/swap/types/msg_test.go +++ /dev/null @@ -1,766 +0,0 @@ -package types_test - -import ( - "testing" - "time" - - "github.com/0glabs/0g-chain/x/swap/types" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestMsgDeposit_Attributes(t *testing.T) { - msg := types.MsgDeposit{} - assert.Equal(t, "swap", msg.Route()) - assert.Equal(t, "swap_deposit", msg.Type()) -} - -func TestMsgDeposit_Signing(t *testing.T) { - signData := `{"type":"swap/MsgDeposit","value":{"deadline":"1623606299","depositor":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","slippage":"0.010000000000000000","token_a":{"amount":"1000000","denom":"ukava"},"token_b":{"amount":"5000000","denom":"usdx"}}}` - signBytes := []byte(signData) - - addr, err := sdk.AccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - require.NoError(t, err) - - msg := types.NewMsgDeposit(addr.String(), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), 1623606299) - assert.Equal(t, []sdk.AccAddress{addr}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsgDeposit_Validation(t *testing.T) { - addr, err := sdk.AccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - require.NoError(t, err) - - validMsg := types.NewMsgDeposit( - addr.String(), - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - sdk.MustNewDecFromStr("0.01"), - 1623606299, - ) - require.NoError(t, validMsg.ValidateBasic()) - - testCases := []struct { - name string - depositor string - tokenA sdk.Coin - tokenB sdk.Coin - slippage sdk.Dec - deadline int64 - expectedErr string - }{ - { - name: "empty address", - depositor: "", - tokenA: validMsg.TokenA, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "depositor address cannot be empty: invalid address", - }, - { - name: "invalid address", - depositor: "kava1abcde", - tokenA: validMsg.TokenA, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "invalid depositor address: decoding bech32 failed: invalid separator index 4: invalid address", - }, - { - name: "negative token a", - depositor: validMsg.Depositor, - tokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(-1)}, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "token a deposit amount -1ukava: invalid coins", - }, - { - name: "zero token a", - depositor: validMsg.Depositor, - tokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(0)}, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "token a deposit amount 0ukava: invalid coins", - }, - { - name: "negative token b", - depositor: validMsg.Depositor, - tokenA: validMsg.TokenA, - tokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(-1)}, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "token b deposit amount -1ukava: invalid coins", - }, - { - name: "zero token b", - depositor: validMsg.Depositor, - tokenA: validMsg.TokenA, - tokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(0)}, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "token b deposit amount 0ukava: invalid coins", - }, - { - name: "denoms can not be the same", - depositor: validMsg.Depositor, - tokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(1e6)}, - tokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(1e6)}, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "denominations can not be equal: invalid coins", - }, - { - name: "zero deadline", - depositor: validMsg.Depositor, - tokenA: validMsg.TokenA, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: 0, - expectedErr: "deadline 0: invalid deadline", - }, - { - name: "negative deadline", - depositor: validMsg.Depositor, - tokenA: validMsg.TokenA, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: -1, - expectedErr: "deadline -1: invalid deadline", - }, - { - name: "negative slippage", - depositor: validMsg.Depositor, - tokenA: validMsg.TokenA, - tokenB: validMsg.TokenB, - slippage: sdk.MustNewDecFromStr("-0.01"), - deadline: validMsg.Deadline, - expectedErr: "slippage can not be negative: invalid slippage", - }, - { - name: "nil slippage", - depositor: validMsg.Depositor, - tokenA: validMsg.TokenA, - tokenB: validMsg.TokenB, - slippage: sdk.Dec{}, - deadline: validMsg.Deadline, - expectedErr: "slippage must be set: invalid slippage", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - msg := types.NewMsgDeposit(tc.depositor, tc.tokenA, tc.tokenB, tc.slippage, tc.deadline) - err := msg.ValidateBasic() - assert.EqualError(t, err, tc.expectedErr) - }) - } -} - -func TestMsgDeposit_Deadline(t *testing.T) { - blockTime := time.Now() - - testCases := []struct { - name string - deadline int64 - isExceeded bool - }{ - { - name: "deadline in future", - deadline: blockTime.Add(1 * time.Second).Unix(), - isExceeded: false, - }, - { - name: "deadline in past", - deadline: blockTime.Add(-1 * time.Second).Unix(), - isExceeded: true, - }, - { - name: "deadline is equal", - deadline: blockTime.Unix(), - isExceeded: true, - }, - } - - for _, tc := range testCases { - msg := types.NewMsgDeposit( - sdk.AccAddress("test1").String(), - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - sdk.MustNewDecFromStr("0.01"), - tc.deadline, - ) - require.NoError(t, msg.ValidateBasic()) - assert.Equal(t, tc.isExceeded, msg.DeadlineExceeded(blockTime)) - assert.Equal(t, time.Unix(tc.deadline, 0), msg.GetDeadline()) - } -} - -func TestMsgWithdraw_Attributes(t *testing.T) { - msg := types.MsgWithdraw{} - assert.Equal(t, "swap", msg.Route()) - assert.Equal(t, "swap_withdraw", msg.Type()) -} - -func TestMsgWithdraw_Signing(t *testing.T) { - signData := `{"type":"swap/MsgWithdraw","value":{"deadline":"1623606299","from":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","min_token_a":{"amount":"1000000","denom":"ukava"},"min_token_b":{"amount":"2000000","denom":"usdx"},"shares":"1500000"}}` - signBytes := []byte(signData) - - addr, err := sdk.AccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - require.NoError(t, err) - - msg := types.NewMsgWithdraw( - addr.String(), - sdkmath.NewInt(1500000), - sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), - sdk.NewCoin("usdx", sdkmath.NewInt(2000000)), - 1623606299, - ) - assert.Equal(t, []sdk.AccAddress{addr}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsgWithdraw_Validation(t *testing.T) { - validMsg := types.NewMsgWithdraw( - sdk.AccAddress("test1").String(), - sdkmath.NewInt(1500000), - sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), - sdk.NewCoin("usdx", sdkmath.NewInt(2000000)), - 1623606299, - ) - require.NoError(t, validMsg.ValidateBasic()) - - testCases := []struct { - name string - from string - shares sdkmath.Int - minTokenA sdk.Coin - minTokenB sdk.Coin - deadline int64 - expectedErr string - }{ - { - name: "empty address", - from: "", - shares: validMsg.Shares, - minTokenA: validMsg.MinTokenA, - minTokenB: validMsg.MinTokenB, - deadline: validMsg.Deadline, - expectedErr: "from address cannot be empty: invalid address", - }, - { - name: "invalid address", - from: "kava1abcde", - shares: validMsg.Shares, - minTokenA: validMsg.MinTokenA, - minTokenB: validMsg.MinTokenB, - deadline: validMsg.Deadline, - expectedErr: "invalid from address: decoding bech32 failed: invalid separator index 4: invalid address", - }, - { - name: "zero token a", - from: validMsg.From, - shares: validMsg.Shares, - minTokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(0)}, - minTokenB: validMsg.MinTokenB, - deadline: validMsg.Deadline, - expectedErr: "min token a amount 0ukava: invalid coins", - }, - { - name: "negative token b", - from: validMsg.From, - shares: validMsg.Shares, - minTokenA: validMsg.MinTokenA, - minTokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(-1)}, - deadline: validMsg.Deadline, - expectedErr: "min token b amount -1ukava: invalid coins", - }, - { - name: "zero token b", - from: validMsg.From, - shares: validMsg.Shares, - minTokenA: validMsg.MinTokenA, - minTokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(0)}, - deadline: validMsg.Deadline, - expectedErr: "min token b amount 0ukava: invalid coins", - }, - { - name: "denoms can not be the same", - from: validMsg.From, - shares: validMsg.Shares, - minTokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(1e6)}, - minTokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(1e6)}, - deadline: validMsg.Deadline, - expectedErr: "denominations can not be equal: invalid coins", - }, - { - name: "zero shares", - from: validMsg.From, - shares: sdk.ZeroInt(), - minTokenA: validMsg.MinTokenA, - minTokenB: validMsg.MinTokenB, - deadline: validMsg.Deadline, - expectedErr: "0: invalid shares", - }, - { - name: "negative shares", - from: validMsg.From, - shares: sdkmath.NewInt(-1), - minTokenA: validMsg.MinTokenA, - minTokenB: validMsg.MinTokenB, - deadline: validMsg.Deadline, - expectedErr: "-1: invalid shares", - }, - { - name: "nil shares", - from: validMsg.From, - shares: sdkmath.Int{}, - minTokenA: validMsg.MinTokenA, - minTokenB: validMsg.MinTokenB, - deadline: validMsg.Deadline, - expectedErr: "shares must be set: invalid shares", - }, - { - name: "zero deadline", - from: validMsg.From, - shares: validMsg.Shares, - minTokenA: validMsg.MinTokenA, - minTokenB: validMsg.MinTokenB, - deadline: 0, - expectedErr: "deadline 0: invalid deadline", - }, - { - name: "negative deadline", - from: validMsg.From, - shares: validMsg.Shares, - minTokenA: validMsg.MinTokenA, - minTokenB: validMsg.MinTokenB, - deadline: -1, - expectedErr: "deadline -1: invalid deadline", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - msg := types.NewMsgWithdraw(tc.from, tc.shares, tc.minTokenA, tc.minTokenB, tc.deadline) - err := msg.ValidateBasic() - assert.EqualError(t, err, tc.expectedErr) - }) - } -} - -func TestMsgWithdraw_Deadline(t *testing.T) { - blockTime := time.Now() - - testCases := []struct { - name string - deadline int64 - isExceeded bool - }{ - { - name: "deadline in future", - deadline: blockTime.Add(1 * time.Second).Unix(), - isExceeded: false, - }, - { - name: "deadline in past", - deadline: blockTime.Add(-1 * time.Second).Unix(), - isExceeded: true, - }, - { - name: "deadline is equal", - deadline: blockTime.Unix(), - isExceeded: true, - }, - } - - for _, tc := range testCases { - msg := types.NewMsgWithdraw( - sdk.AccAddress("test1").String(), - sdkmath.NewInt(1500000), - sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), - sdk.NewCoin("usdx", sdkmath.NewInt(2000000)), - tc.deadline, - ) - require.NoError(t, msg.ValidateBasic()) - assert.Equal(t, tc.isExceeded, msg.DeadlineExceeded(blockTime)) - assert.Equal(t, time.Unix(tc.deadline, 0), msg.GetDeadline()) - } -} - -func TestMsgSwapExactForTokens_Attributes(t *testing.T) { - msg := types.MsgSwapExactForTokens{} - assert.Equal(t, "swap", msg.Route()) - assert.Equal(t, "swap_exact_for_tokens", msg.Type()) -} - -func TestMsgSwapExactForTokens_Signing(t *testing.T) { - signData := `{"type":"swap/MsgSwapExactForTokens","value":{"deadline":"1623606299","exact_token_a":{"amount":"1000000","denom":"ukava"},"requester":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","slippage":"0.010000000000000000","token_b":{"amount":"5000000","denom":"usdx"}}}` - signBytes := []byte(signData) - - addr, err := sdk.AccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - require.NoError(t, err) - - msg := types.NewMsgSwapExactForTokens(addr.String(), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), 1623606299) - assert.Equal(t, []sdk.AccAddress{addr}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsgSwapExactForTokens_Validation(t *testing.T) { - validMsg := types.NewMsgSwapExactForTokens( - sdk.AccAddress("test1").String(), - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - sdk.MustNewDecFromStr("0.01"), - 1623606299, - ) - require.NoError(t, validMsg.ValidateBasic()) - - testCases := []struct { - name string - requester string - exactTokenA sdk.Coin - tokenB sdk.Coin - slippage sdk.Dec - deadline int64 - expectedErr string - }{ - { - name: "empty address", - requester: sdk.AccAddress("").String(), - exactTokenA: validMsg.ExactTokenA, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "requester address cannot be empty: invalid address", - }, - { - name: "invalid address", - requester: "kava1abcde", - exactTokenA: validMsg.ExactTokenA, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "invalid requester address: decoding bech32 failed: invalid separator index 4: invalid address", - }, - { - name: "negative token a", - requester: validMsg.Requester, - exactTokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(-1)}, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "exact token a deposit amount -1ukava: invalid coins", - }, - { - name: "zero token a", - requester: validMsg.Requester, - exactTokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(0)}, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "exact token a deposit amount 0ukava: invalid coins", - }, - { - name: "negative token b", - requester: validMsg.Requester, - exactTokenA: validMsg.ExactTokenA, - tokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(-1)}, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "token b deposit amount -1ukava: invalid coins", - }, - { - name: "zero token b", - requester: validMsg.Requester, - exactTokenA: validMsg.ExactTokenA, - tokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(0)}, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "token b deposit amount 0ukava: invalid coins", - }, - { - name: "denoms can not be the same", - requester: validMsg.Requester, - exactTokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(1e6)}, - tokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(1e6)}, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "denominations can not be equal: invalid coins", - }, - { - name: "zero deadline", - requester: validMsg.Requester, - exactTokenA: validMsg.ExactTokenA, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: 0, - expectedErr: "deadline 0: invalid deadline", - }, - { - name: "negative deadline", - requester: validMsg.Requester, - exactTokenA: validMsg.ExactTokenA, - tokenB: validMsg.TokenB, - slippage: validMsg.Slippage, - deadline: -1, - expectedErr: "deadline -1: invalid deadline", - }, - { - name: "negative slippage", - requester: validMsg.Requester, - exactTokenA: validMsg.ExactTokenA, - tokenB: validMsg.TokenB, - slippage: sdk.MustNewDecFromStr("-0.01"), - deadline: validMsg.Deadline, - expectedErr: "slippage can not be negative: invalid slippage", - }, - { - name: "nil slippage", - requester: validMsg.Requester, - exactTokenA: validMsg.ExactTokenA, - tokenB: validMsg.TokenB, - slippage: sdk.Dec{}, - deadline: validMsg.Deadline, - expectedErr: "slippage must be set: invalid slippage", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - msg := types.NewMsgSwapExactForTokens(tc.requester, tc.exactTokenA, tc.tokenB, tc.slippage, tc.deadline) - err := msg.ValidateBasic() - assert.EqualError(t, err, tc.expectedErr) - }) - } -} - -func TestMsgSwapExactForTokens_Deadline(t *testing.T) { - blockTime := time.Now() - - testCases := []struct { - name string - deadline int64 - isExceeded bool - }{ - { - name: "deadline in future", - deadline: blockTime.Add(1 * time.Second).Unix(), - isExceeded: false, - }, - { - name: "deadline in past", - deadline: blockTime.Add(-1 * time.Second).Unix(), - isExceeded: true, - }, - { - name: "deadline is equal", - deadline: blockTime.Unix(), - isExceeded: true, - }, - } - - for _, tc := range testCases { - msg := types.NewMsgSwapExactForTokens( - sdk.AccAddress("test1").String(), - sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), - sdk.NewCoin("usdx", sdkmath.NewInt(2000000)), - sdk.MustNewDecFromStr("0.01"), - tc.deadline, - ) - require.NoError(t, msg.ValidateBasic()) - assert.Equal(t, tc.isExceeded, msg.DeadlineExceeded(blockTime)) - assert.Equal(t, time.Unix(tc.deadline, 0), msg.GetDeadline()) - } -} - -func TestMsgSwapForExactTokens_Attributes(t *testing.T) { - msg := types.MsgSwapForExactTokens{} - assert.Equal(t, "swap", msg.Route()) - assert.Equal(t, "swap_for_exact_tokens", msg.Type()) -} - -func TestMsgSwapForExactTokens_Signing(t *testing.T) { - signData := `{"type":"swap/MsgSwapForExactTokens","value":{"deadline":"1623606299","exact_token_b":{"amount":"5000000","denom":"usdx"},"requester":"kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d","slippage":"0.010000000000000000","token_a":{"amount":"1000000","denom":"ukava"}}}` - signBytes := []byte(signData) - - addr, err := sdk.AccAddressFromBech32("kava1gepm4nwzz40gtpur93alv9f9wm5ht4l0hzzw9d") - require.NoError(t, err) - - msg := types.NewMsgSwapForExactTokens(addr.String(), sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), sdk.MustNewDecFromStr("0.01"), 1623606299) - assert.Equal(t, []sdk.AccAddress{addr}, msg.GetSigners()) - assert.Equal(t, signBytes, msg.GetSignBytes()) -} - -func TestMsgSwapForExactTokens_Validation(t *testing.T) { - validMsg := types.NewMsgSwapForExactTokens( - sdk.AccAddress("test1").String(), - sdk.NewCoin("ukava", sdkmath.NewInt(1e6)), - sdk.NewCoin("usdx", sdkmath.NewInt(5e6)), - sdk.MustNewDecFromStr("0.01"), - 1623606299, - ) - require.NoError(t, validMsg.ValidateBasic()) - - testCases := []struct { - name string - requester string - tokenA sdk.Coin - exactTokenB sdk.Coin - slippage sdk.Dec - deadline int64 - expectedErr string - }{ - { - name: "empty address", - requester: sdk.AccAddress("").String(), - tokenA: validMsg.TokenA, - exactTokenB: validMsg.ExactTokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "requester address cannot be empty: invalid address", - }, - { - name: "invalid address", - requester: "kava1abcde", - tokenA: validMsg.TokenA, - exactTokenB: validMsg.ExactTokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "invalid requester address: decoding bech32 failed: invalid separator index 4: invalid address", - }, - { - name: "negative token a", - requester: validMsg.Requester, - tokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(-1)}, - exactTokenB: validMsg.ExactTokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "token a deposit amount -1ukava: invalid coins", - }, - { - name: "zero token a", - requester: validMsg.Requester, - tokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(0)}, - exactTokenB: validMsg.ExactTokenB, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "token a deposit amount 0ukava: invalid coins", - }, - { - name: "negative token b", - requester: validMsg.Requester, - tokenA: validMsg.TokenA, - exactTokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(-1)}, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "exact token b deposit amount -1ukava: invalid coins", - }, - { - name: "zero token b", - requester: validMsg.Requester, - tokenA: validMsg.TokenA, - exactTokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(0)}, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "exact token b deposit amount 0ukava: invalid coins", - }, - { - name: "denoms can not be the same", - requester: validMsg.Requester, - tokenA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(1e6)}, - exactTokenB: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(1e6)}, - slippage: validMsg.Slippage, - deadline: validMsg.Deadline, - expectedErr: "denominations can not be equal: invalid coins", - }, - { - name: "zero deadline", - requester: validMsg.Requester, - tokenA: validMsg.TokenA, - exactTokenB: validMsg.ExactTokenB, - slippage: validMsg.Slippage, - deadline: 0, - expectedErr: "deadline 0: invalid deadline", - }, - { - name: "negative deadline", - requester: validMsg.Requester, - tokenA: validMsg.TokenA, - exactTokenB: validMsg.ExactTokenB, - slippage: validMsg.Slippage, - deadline: -1, - expectedErr: "deadline -1: invalid deadline", - }, - { - name: "negative slippage", - requester: validMsg.Requester, - tokenA: validMsg.TokenA, - exactTokenB: validMsg.ExactTokenB, - slippage: sdk.MustNewDecFromStr("-0.01"), - deadline: validMsg.Deadline, - expectedErr: "slippage can not be negative: invalid slippage", - }, - { - name: "nil slippage", - requester: validMsg.Requester, - tokenA: validMsg.TokenA, - exactTokenB: validMsg.ExactTokenB, - slippage: sdk.Dec{}, - deadline: validMsg.Deadline, - expectedErr: "slippage must be set: invalid slippage", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - msg := types.NewMsgSwapForExactTokens(tc.requester, tc.tokenA, tc.exactTokenB, tc.slippage, tc.deadline) - err := msg.ValidateBasic() - assert.EqualError(t, err, tc.expectedErr) - }) - } -} - -func TestMsgSwapForExactTokens_Deadline(t *testing.T) { - blockTime := time.Now() - - testCases := []struct { - name string - deadline int64 - isExceeded bool - }{ - { - name: "deadline in future", - deadline: blockTime.Add(1 * time.Second).Unix(), - isExceeded: false, - }, - { - name: "deadline in past", - deadline: blockTime.Add(-1 * time.Second).Unix(), - isExceeded: true, - }, - { - name: "deadline is equal", - deadline: blockTime.Unix(), - isExceeded: true, - }, - } - - for _, tc := range testCases { - msg := types.NewMsgSwapForExactTokens( - sdk.AccAddress("test1").String(), - sdk.NewCoin("ukava", sdkmath.NewInt(1000000)), - sdk.NewCoin("usdx", sdkmath.NewInt(2000000)), - sdk.MustNewDecFromStr("0.01"), - tc.deadline, - ) - require.NoError(t, msg.ValidateBasic()) - assert.Equal(t, tc.isExceeded, msg.DeadlineExceeded(blockTime)) - assert.Equal(t, time.Unix(tc.deadline, 0), msg.GetDeadline()) - } -} diff --git a/x/swap/types/params.go b/x/swap/types/params.go deleted file mode 100644 index 6cd67964..00000000 --- a/x/swap/types/params.go +++ /dev/null @@ -1,173 +0,0 @@ -package types - -import ( - "fmt" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" -) - -// Parameter keys and default values -var ( - KeyAllowedPools = []byte("AllowedPools") - KeySwapFee = []byte("SwapFee") - DefaultAllowedPools = AllowedPools{} - DefaultSwapFee = sdk.ZeroDec() - MaxSwapFee = sdk.OneDec() -) - -// NewParams returns a new params object -func NewParams(pairs AllowedPools, swapFee sdk.Dec) Params { - return Params{ - AllowedPools: pairs, - SwapFee: swapFee, - } -} - -// DefaultParams returns default params for swap module -func DefaultParams() Params { - return NewParams( - DefaultAllowedPools, - DefaultSwapFee, - ) -} - -// String implements fmt.Stringer -func (p Params) String() string { - return fmt.Sprintf(`Params: - AllowedPools: %s - SwapFee: %s`, - p.AllowedPools, p.SwapFee) -} - -// ParamKeyTable for swap module. -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs implements params.ParamSet -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyAllowedPools, &p.AllowedPools, validateAllowedPoolsParams), - paramtypes.NewParamSetPair(KeySwapFee, &p.SwapFee, validateSwapFee), - } -} - -// Validate checks that the parameters have valid values. -func (p Params) Validate() error { - if err := validateAllowedPoolsParams(p.AllowedPools); err != nil { - return err - } - - return validateSwapFee(p.SwapFee) -} - -func validateAllowedPoolsParams(i interface{}) error { - p, ok := i.(AllowedPools) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return p.Validate() -} - -func validateSwapFee(i interface{}) error { - swapFee, ok := i.(sdk.Dec) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if swapFee.IsNil() || swapFee.IsNegative() || swapFee.GTE(MaxSwapFee) { - return fmt.Errorf(fmt.Sprintf("invalid swap fee: %s", swapFee)) - } - - return nil -} - -// NewAllowedPool returns a new AllowedPool object -func NewAllowedPool(tokenA, tokenB string) AllowedPool { - return AllowedPool{ - TokenA: tokenA, - TokenB: tokenB, - } -} - -// Validate validates allowedPool attributes and returns an error if invalid -func (p AllowedPool) Validate() error { - err := sdk.ValidateDenom(p.TokenA) - if err != nil { - return err - } - - err = sdk.ValidateDenom(p.TokenB) - if err != nil { - return err - } - - // Ensure there is no colon in the token denoms as they are used as separators - // and is now valid in Cosmos denoms. - if strings.Contains(p.TokenA, ":") { - return fmt.Errorf("tokenA cannot have colons in the denom: %s", p.TokenA) - } - - if strings.Contains(p.TokenB, ":") { - return fmt.Errorf("tokenB cannot have colons in the denom: %s", p.TokenB) - } - - if p.TokenA == p.TokenB { - return fmt.Errorf( - "pool cannot have two tokens of the same type, received '%s' and '%s'", - p.TokenA, p.TokenB, - ) - } - - if p.TokenA > p.TokenB { - return fmt.Errorf( - "invalid token order: '%s' must come before '%s'", - p.TokenB, p.TokenA, - ) - } - - return nil -} - -// Name returns the name for the allowed pool -func (p AllowedPool) Name() string { - return PoolID(p.TokenA, p.TokenB) -} - -// String pretty prints the allowedPool -func (p AllowedPool) String() string { - return fmt.Sprintf(`AllowedPool: - Name: %s - Token A: %s - Token B: %s -`, p.Name(), p.TokenA, p.TokenB) -} - -// AllowedPools is a slice of AllowedPool -type AllowedPools []AllowedPool - -// NewAllowedPools returns AllowedPools from the provided values -func NewAllowedPools(allowedPools ...AllowedPool) AllowedPools { - return AllowedPools(allowedPools) -} - -// Validate validates each allowedPool and returns an error if there are any duplicates -func (p AllowedPools) Validate() error { - seenAllowedPools := make(map[string]bool) - for _, allowedPool := range p { - err := allowedPool.Validate() - if err != nil { - return err - } - - if seen := seenAllowedPools[allowedPool.Name()]; seen { - return fmt.Errorf("duplicate pool: %s", allowedPool.Name()) - } - seenAllowedPools[allowedPool.Name()] = true - } - - return nil -} diff --git a/x/swap/types/params_test.go b/x/swap/types/params_test.go deleted file mode 100644 index b74b30a6..00000000 --- a/x/swap/types/params_test.go +++ /dev/null @@ -1,396 +0,0 @@ -package types_test - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "strings" - "testing" - - "github.com/0glabs/0g-chain/x/swap/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "sigs.k8s.io/yaml" -) - -func TestParams_UnmarshalJSON(t *testing.T) { - pools := types.NewAllowedPools( - types.NewAllowedPool("hard", "ukava"), - types.NewAllowedPool("hard", "usdx"), - ) - poolData, err := json.Marshal(pools) - require.NoError(t, err) - - fee, err := sdk.NewDecFromStr("0.5") - require.NoError(t, err) - feeData, err := json.Marshal(fee) - require.NoError(t, err) - - data := fmt.Sprintf(`{ - "allowed_pools": %s, - "swap_fee": %s -}`, string(poolData), string(feeData)) - - var params types.Params - err = json.Unmarshal([]byte(data), ¶ms) - require.NoError(t, err) - - assert.Equal(t, pools, params.AllowedPools) - assert.Equal(t, fee, params.SwapFee) -} - -func TestParams_MarshalYAML(t *testing.T) { - pools := types.NewAllowedPools( - types.NewAllowedPool("hard", "ukava"), - types.NewAllowedPool("hard", "usdx"), - ) - fee, err := sdk.NewDecFromStr("0.5") - require.NoError(t, err) - - p := types.Params{ - AllowedPools: pools, - SwapFee: fee, - } - - data, err := yaml.Marshal(p) - require.NoError(t, err) - - var params map[string]interface{} - err = yaml.Unmarshal(data, ¶ms) - require.NoError(t, err) - - _, ok := params["allowed_pools"] - require.True(t, ok) - _, ok = params["swap_fee"] - require.True(t, ok) -} - -func TestParams_Default(t *testing.T) { - defaultParams := types.DefaultParams() - - require.NoError(t, defaultParams.Validate()) - - assert.Equal(t, types.DefaultAllowedPools, defaultParams.AllowedPools) - assert.Equal(t, types.DefaultSwapFee, defaultParams.SwapFee) - - assert.Equal(t, 0, len(defaultParams.AllowedPools)) - assert.Equal(t, sdk.ZeroDec(), defaultParams.SwapFee) -} - -func TestParams_ParamSetPairs_AllowedPools(t *testing.T) { - assert.Equal(t, []byte("AllowedPools"), types.KeyAllowedPools) - defaultParams := types.DefaultParams() - - var paramSetPair *paramstypes.ParamSetPair - for _, pair := range defaultParams.ParamSetPairs() { - if bytes.Equal(pair.Key, types.KeyAllowedPools) { - paramSetPair = &pair - break - } - } - require.NotNil(t, paramSetPair) - - pairs, ok := paramSetPair.Value.(*types.AllowedPools) - require.True(t, ok) - assert.Equal(t, pairs, &defaultParams.AllowedPools) - - assert.Nil(t, paramSetPair.ValidatorFn(*pairs)) - assert.EqualError(t, paramSetPair.ValidatorFn(struct{}{}), "invalid parameter type: struct {}") -} - -func TestParams_ParamSetPairs_SwapFee(t *testing.T) { - assert.Equal(t, []byte("SwapFee"), types.KeySwapFee) - defaultParams := types.DefaultParams() - - var paramSetPair *paramstypes.ParamSetPair - for _, pair := range defaultParams.ParamSetPairs() { - if bytes.Equal(pair.Key, types.KeySwapFee) { - paramSetPair = &pair - break - } - } - require.NotNil(t, paramSetPair) - - swapFee, ok := paramSetPair.Value.(*sdk.Dec) - require.True(t, ok) - assert.Equal(t, swapFee, &defaultParams.SwapFee) - - assert.Nil(t, paramSetPair.ValidatorFn(*swapFee)) - assert.EqualError(t, paramSetPair.ValidatorFn(struct{}{}), "invalid parameter type: struct {}") -} - -func TestParams_Validation(t *testing.T) { - testCases := []struct { - name string - key []byte - testFn func(params *types.Params) - expectedErr string - }{ - { - name: "duplicate pools", - key: types.KeyAllowedPools, - testFn: func(params *types.Params) { - params.AllowedPools = types.NewAllowedPools(types.NewAllowedPool("ukava", "ukava")) - }, - expectedErr: "pool cannot have two tokens of the same type, received 'ukava' and 'ukava'", - }, - { - name: "nil swap fee", - key: types.KeySwapFee, - testFn: func(params *types.Params) { - params.SwapFee = sdk.Dec{} - }, - expectedErr: "invalid swap fee: ", - }, - { - name: "negative swap fee", - key: types.KeySwapFee, - testFn: func(params *types.Params) { - params.SwapFee = sdk.NewDec(-1) - }, - expectedErr: "invalid swap fee: -1.000000000000000000", - }, - { - name: "swap fee greater than 1", - key: types.KeySwapFee, - testFn: func(params *types.Params) { - params.SwapFee = sdk.MustNewDecFromStr("1.000000000000000001") - }, - expectedErr: "invalid swap fee: 1.000000000000000001", - }, - { - name: "0 swap fee", - key: types.KeySwapFee, - testFn: func(params *types.Params) { - params.SwapFee = sdk.ZeroDec() - }, - expectedErr: "", - }, - { - name: "1 swap fee", - key: types.KeySwapFee, - testFn: func(params *types.Params) { - params.SwapFee = sdk.OneDec() - }, - expectedErr: "invalid swap fee: 1.000000000000000000", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - params := types.DefaultParams() - tc.testFn(¶ms) - - err := params.Validate() - - if tc.expectedErr == "" { - assert.Nil(t, err) - } else { - assert.EqualError(t, err, tc.expectedErr) - } - - var paramSetPair *paramstypes.ParamSetPair - for _, pair := range params.ParamSetPairs() { - if bytes.Equal(pair.Key, tc.key) { - paramSetPair = &pair - break - } - } - require.NotNil(t, paramSetPair) - value := reflect.ValueOf(paramSetPair.Value).Elem().Interface() - - // assert validation error is same as param set validation - assert.Equal(t, err, paramSetPair.ValidatorFn(value)) - }) - } -} - -func TestParams_String(t *testing.T) { - params := types.NewParams( - types.NewAllowedPools( - types.NewAllowedPool("hard", "ukava"), - types.NewAllowedPool("ukava", "usdx"), - ), - sdk.MustNewDecFromStr("0.5"), - ) - - require.NoError(t, params.Validate()) - - output := params.String() - assert.Contains(t, output, types.PoolID("hard", "ukava")) - assert.Contains(t, output, types.PoolID("ukava", "usdx")) - assert.Contains(t, output, "0.5") -} - -func TestAllowedPool_Validation(t *testing.T) { - testCases := []struct { - name string - allowedPool types.AllowedPool - expectedErr string - }{ - { - name: "blank token a", - allowedPool: types.NewAllowedPool("", "ukava"), - expectedErr: "invalid denom: ", - }, - { - name: "blank token b", - allowedPool: types.NewAllowedPool("ukava", ""), - expectedErr: "invalid denom: ", - }, - { - name: "invalid token a", - allowedPool: types.NewAllowedPool("1ukava", "ukava"), - expectedErr: "invalid denom: 1ukava", - }, - { - name: "invalid token b", - allowedPool: types.NewAllowedPool("ukava", "1ukava"), - expectedErr: "invalid denom: 1ukava", - }, - { - name: "matching tokens", - allowedPool: types.NewAllowedPool("ukava", "ukava"), - expectedErr: "pool cannot have two tokens of the same type, received 'ukava' and 'ukava'", - }, - { - name: "invalid token order", - allowedPool: types.NewAllowedPool("usdx", "ukava"), - expectedErr: "invalid token order: 'ukava' must come before 'usdx'", - }, - { - name: "invalid token order due to capitalization", - allowedPool: types.NewAllowedPool("ukava", "UKAVA"), - expectedErr: "invalid token order: 'UKAVA' must come before 'ukava'", - }, - { - name: "invalid token a with colon", - allowedPool: types.NewAllowedPool("test:denom", "ukava"), - expectedErr: "tokenA cannot have colons in the denom: test:denom", - }, - { - name: "invalid token b with colon", - allowedPool: types.NewAllowedPool("ukava", "u:kava"), - expectedErr: "tokenB cannot have colons in the denom: u:kava", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.allowedPool.Validate() - assert.EqualError(t, err, tc.expectedErr) - }) - } -} - -func TestAllowedPool_TokenMatch_CaseSensitive(t *testing.T) { - allowedPool := types.NewAllowedPool("UKAVA", "ukava") - err := allowedPool.Validate() - assert.NoError(t, err) - - allowedPool = types.NewAllowedPool("haRd", "hard") - err = allowedPool.Validate() - assert.NoError(t, err) - - allowedPool = types.NewAllowedPool("Usdx", "uSdX") - err = allowedPool.Validate() - assert.NoError(t, err) -} - -func TestAllowedPool_String(t *testing.T) { - allowedPool := types.NewAllowedPool("hard", "ukava") - require.NoError(t, allowedPool.Validate()) - - output := `AllowedPool: - Name: hard:ukava - Token A: hard - Token B: ukava -` - assert.Equal(t, output, allowedPool.String()) -} - -func TestAllowedPool_Name(t *testing.T) { - testCases := []struct { - tokens string - name string - }{ - { - tokens: "atoken btoken", - name: "atoken:btoken", - }, - { - tokens: "aaa aaaa", - name: "aaa:aaaa", - }, - { - tokens: "aaaa aaab", - name: "aaaa:aaab", - }, - { - tokens: "a001 a002", - name: "a001:a002", - }, - { - tokens: "hard ukava", - name: "hard:ukava", - }, - { - tokens: "bnb hard", - name: "bnb:hard", - }, - { - tokens: "bnb xrpb", - name: "bnb:xrpb", - }, - } - - for _, tc := range testCases { - t.Run(tc.tokens, func(t *testing.T) { - tokens := strings.Split(tc.tokens, " ") - require.Equal(t, 2, len(tokens)) - - allowedPool := types.NewAllowedPool(tokens[0], tokens[1]) - require.NoError(t, allowedPool.Validate()) - - assert.Equal(t, tc.name, allowedPool.Name()) - }) - } -} - -func TestAllowedPools_Validate(t *testing.T) { - testCases := []struct { - name string - allowedPools types.AllowedPools - expectedErr string - }{ - { - name: "duplicate pool", - allowedPools: types.NewAllowedPools( - types.NewAllowedPool("hard", "ukava"), - types.NewAllowedPool("hard", "ukava"), - ), - expectedErr: "duplicate pool: hard:ukava", - }, - { - name: "duplicate pools", - allowedPools: types.NewAllowedPools( - types.NewAllowedPool("hard", "ukava"), - types.NewAllowedPool("bnb", "usdx"), - types.NewAllowedPool("btcb", "xrpb"), - types.NewAllowedPool("bnb", "usdx"), - ), - expectedErr: "duplicate pool: bnb:usdx", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.allowedPools.Validate() - assert.EqualError(t, err, tc.expectedErr) - }) - } -} diff --git a/x/swap/types/query.pb.go b/x/swap/types/query.pb.go deleted file mode 100644 index 85e6da04..00000000 --- a/x/swap/types/query.pb.go +++ /dev/null @@ -1,2192 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/swap/v1beta1/query.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - query "github.com/cosmos/cosmos-sdk/types/query" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// QueryParamsRequest defines the request type for querying x/swap parameters. -type QueryParamsRequest struct { -} - -func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } -func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryParamsRequest) ProtoMessage() {} -func (*QueryParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_652c07bb38685396, []int{0} -} -func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsRequest.Merge(m, src) -} -func (m *QueryParamsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo - -// QueryParamsResponse defines the response type for querying x/swap parameters. -type QueryParamsResponse struct { - // params represents the swap module parameters - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` -} - -func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } -func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryParamsResponse) ProtoMessage() {} -func (*QueryParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_652c07bb38685396, []int{1} -} -func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsResponse.Merge(m, src) -} -func (m *QueryParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo - -// QueryPoolsRequest is the request type for the Query/Pools RPC method. -type QueryPoolsRequest struct { - // pool_id filters pools by id - PoolId string `protobuf:"bytes,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryPoolsRequest) Reset() { *m = QueryPoolsRequest{} } -func (m *QueryPoolsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryPoolsRequest) ProtoMessage() {} -func (*QueryPoolsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_652c07bb38685396, []int{2} -} -func (m *QueryPoolsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPoolsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPoolsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryPoolsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPoolsRequest.Merge(m, src) -} -func (m *QueryPoolsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryPoolsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPoolsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPoolsRequest proto.InternalMessageInfo - -func (m *QueryPoolsRequest) GetPoolId() string { - if m != nil { - return m.PoolId - } - return "" -} - -func (m *QueryPoolsRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryPoolsResponse is the response type for the Query/Pools RPC method. -type QueryPoolsResponse struct { - // pools represents returned pools - Pools []PoolResponse `protobuf:"bytes,1,rep,name=pools,proto3" json:"pools"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryPoolsResponse) Reset() { *m = QueryPoolsResponse{} } -func (m *QueryPoolsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryPoolsResponse) ProtoMessage() {} -func (*QueryPoolsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_652c07bb38685396, []int{3} -} -func (m *QueryPoolsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPoolsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPoolsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryPoolsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPoolsResponse.Merge(m, src) -} -func (m *QueryPoolsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryPoolsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPoolsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPoolsResponse proto.InternalMessageInfo - -func (m *QueryPoolsResponse) GetPools() []PoolResponse { - if m != nil { - return m.Pools - } - return nil -} - -func (m *QueryPoolsResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// Pool represents the state of a single pool -type PoolResponse struct { - // name represents the name of the pool - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // coins represents the total reserves of the pool - Coins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=coins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"coins"` - // total_shares represents the total shares of the pool - TotalShares github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=total_shares,json=totalShares,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"total_shares"` -} - -func (m *PoolResponse) Reset() { *m = PoolResponse{} } -func (m *PoolResponse) String() string { return proto.CompactTextString(m) } -func (*PoolResponse) ProtoMessage() {} -func (*PoolResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_652c07bb38685396, []int{4} -} -func (m *PoolResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *PoolResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_PoolResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *PoolResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_PoolResponse.Merge(m, src) -} -func (m *PoolResponse) XXX_Size() int { - return m.Size() -} -func (m *PoolResponse) XXX_DiscardUnknown() { - xxx_messageInfo_PoolResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_PoolResponse proto.InternalMessageInfo - -// QueryDepositsRequest is the request type for the Query/Deposits RPC method. -type QueryDepositsRequest struct { - // owner optionally filters deposits by owner - Owner string `protobuf:"bytes,1,opt,name=owner,proto3" json:"owner,omitempty"` - // pool_id optionally fitlers deposits by pool id - PoolId string `protobuf:"bytes,2,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,3,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDepositsRequest) Reset() { *m = QueryDepositsRequest{} } -func (m *QueryDepositsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsRequest) ProtoMessage() {} -func (*QueryDepositsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_652c07bb38685396, []int{5} -} -func (m *QueryDepositsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryDepositsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsRequest.Merge(m, src) -} -func (m *QueryDepositsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsRequest proto.InternalMessageInfo - -// QueryDepositsResponse is the response type for the Query/Deposits RPC method. -type QueryDepositsResponse struct { - // deposits returns the deposits matching the requested parameters - Deposits []DepositResponse `protobuf:"bytes,1,rep,name=deposits,proto3" json:"deposits"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryDepositsResponse) Reset() { *m = QueryDepositsResponse{} } -func (m *QueryDepositsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryDepositsResponse) ProtoMessage() {} -func (*QueryDepositsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_652c07bb38685396, []int{6} -} -func (m *QueryDepositsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryDepositsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryDepositsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryDepositsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryDepositsResponse.Merge(m, src) -} -func (m *QueryDepositsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryDepositsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryDepositsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryDepositsResponse proto.InternalMessageInfo - -// DepositResponse defines a single deposit query response type. -type DepositResponse struct { - // depositor represents the owner of the deposit - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - // pool_id represents the pool the deposit is for - PoolId string `protobuf:"bytes,2,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` - // shares_owned presents the shares owned by the depositor for the pool - SharesOwned github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=shares_owned,json=sharesOwned,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"shares_owned"` - // shares_value represents the coin value of the shares_owned - SharesValue github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,4,rep,name=shares_value,json=sharesValue,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"shares_value"` -} - -func (m *DepositResponse) Reset() { *m = DepositResponse{} } -func (m *DepositResponse) String() string { return proto.CompactTextString(m) } -func (*DepositResponse) ProtoMessage() {} -func (*DepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_652c07bb38685396, []int{7} -} -func (m *DepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DepositResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *DepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_DepositResponse.Merge(m, src) -} -func (m *DepositResponse) XXX_Size() int { - return m.Size() -} -func (m *DepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_DepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_DepositResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "kava.swap.v1beta1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "kava.swap.v1beta1.QueryParamsResponse") - proto.RegisterType((*QueryPoolsRequest)(nil), "kava.swap.v1beta1.QueryPoolsRequest") - proto.RegisterType((*QueryPoolsResponse)(nil), "kava.swap.v1beta1.QueryPoolsResponse") - proto.RegisterType((*PoolResponse)(nil), "kava.swap.v1beta1.PoolResponse") - proto.RegisterType((*QueryDepositsRequest)(nil), "kava.swap.v1beta1.QueryDepositsRequest") - proto.RegisterType((*QueryDepositsResponse)(nil), "kava.swap.v1beta1.QueryDepositsResponse") - proto.RegisterType((*DepositResponse)(nil), "kava.swap.v1beta1.DepositResponse") -} - -func init() { proto.RegisterFile("kava/swap/v1beta1/query.proto", fileDescriptor_652c07bb38685396) } - -var fileDescriptor_652c07bb38685396 = []byte{ - // 753 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x55, 0xcf, 0x4f, 0x13, 0x4f, - 0x14, 0xef, 0xf6, 0xd7, 0x17, 0xa6, 0x24, 0xdf, 0x30, 0x62, 0x6c, 0x0b, 0x6c, 0xb1, 0x0a, 0x34, - 0x26, 0xdd, 0x05, 0x4c, 0x34, 0x51, 0x2f, 0x54, 0x82, 0xe1, 0xa4, 0x2e, 0xc6, 0x83, 0x97, 0x66, - 0xda, 0x9d, 0x2c, 0x1b, 0xb6, 0x3b, 0xcb, 0xce, 0xb4, 0x88, 0x27, 0xc3, 0xc9, 0xa3, 0x89, 0x37, - 0x4f, 0x9e, 0x8d, 0xde, 0xf8, 0x0f, 0xbc, 0x70, 0x24, 0x78, 0x31, 0x1e, 0xd0, 0x80, 0x47, 0xff, - 0x08, 0x33, 0x3f, 0xb6, 0x94, 0x76, 0xb1, 0x6a, 0x38, 0x75, 0x77, 0xde, 0x7b, 0x9f, 0xcf, 0xe7, - 0xbd, 0xf7, 0xd9, 0x29, 0x98, 0xde, 0x44, 0x1d, 0x64, 0xd2, 0x6d, 0x14, 0x98, 0x9d, 0xc5, 0x06, - 0x66, 0x68, 0xd1, 0xdc, 0x6a, 0xe3, 0x70, 0xc7, 0x08, 0x42, 0xc2, 0x08, 0x1c, 0xe7, 0x61, 0x83, - 0x87, 0x0d, 0x15, 0x2e, 0xde, 0x68, 0x12, 0xda, 0x22, 0xd4, 0x6c, 0x20, 0x8a, 0x65, 0x6e, 0xb7, - 0x32, 0x40, 0x8e, 0xeb, 0x23, 0xe6, 0x12, 0x5f, 0x96, 0x17, 0xf5, 0xde, 0xdc, 0x28, 0xab, 0x49, - 0xdc, 0x28, 0x5e, 0x90, 0xf1, 0xba, 0x78, 0x33, 0xe5, 0x8b, 0x0a, 0x4d, 0x38, 0xc4, 0x21, 0xf2, - 0x9c, 0x3f, 0xa9, 0xd3, 0x29, 0x87, 0x10, 0xc7, 0xc3, 0x26, 0x0a, 0x5c, 0x13, 0xf9, 0x3e, 0x61, - 0x82, 0x2d, 0xaa, 0x99, 0x1a, 0x6c, 0x46, 0x48, 0x17, 0xd1, 0x72, 0x11, 0xc0, 0xc7, 0x5c, 0xee, - 0x23, 0x14, 0xa2, 0x16, 0xb5, 0xf0, 0x56, 0x1b, 0x53, 0x76, 0x27, 0xfd, 0xea, 0x5d, 0x29, 0x51, - 0x7e, 0x02, 0x2e, 0x9d, 0x89, 0xd1, 0x80, 0xf8, 0x14, 0xc3, 0xdb, 0x20, 0x1b, 0x88, 0x93, 0xbc, - 0x36, 0xa3, 0x55, 0x72, 0x4b, 0x05, 0x63, 0x60, 0x1e, 0x86, 0x2c, 0xa9, 0xa5, 0xf7, 0x8f, 0x4a, - 0x09, 0x4b, 0xa5, 0x2b, 0x54, 0x06, 0xc6, 0x25, 0x2a, 0x21, 0x5e, 0x44, 0x08, 0xaf, 0x80, 0xff, - 0x02, 0x42, 0xbc, 0xba, 0x6b, 0x0b, 0xd0, 0x51, 0x2b, 0xcb, 0x5f, 0xd7, 0x6c, 0xb8, 0x0a, 0xc0, - 0xe9, 0x00, 0xf3, 0x49, 0x41, 0x38, 0x67, 0xa8, 0xa1, 0xf0, 0x09, 0x1a, 0x72, 0x33, 0xa7, 0xc4, - 0x0e, 0x56, 0xa0, 0x56, 0x4f, 0x65, 0xf9, 0xad, 0x16, 0x35, 0x2a, 0x69, 0x55, 0x2f, 0x77, 0x41, - 0x86, 0x13, 0xf1, 0x56, 0x52, 0x95, 0xdc, 0x52, 0x29, 0xae, 0x15, 0x42, 0xbc, 0x28, 0x5f, 0x35, - 0x24, 0x6b, 0xe0, 0x83, 0x18, 0x6d, 0xf3, 0x43, 0xb5, 0x49, 0xa4, 0x33, 0xe2, 0x7e, 0x6a, 0x60, - 0xac, 0x97, 0x06, 0x42, 0x90, 0xf6, 0x51, 0x0b, 0xab, 0x59, 0x88, 0x67, 0x88, 0x40, 0x86, 0x9b, - 0x84, 0xe6, 0x93, 0x42, 0x6a, 0xe1, 0x0c, 0x51, 0x44, 0x71, 0x9f, 0xb8, 0x7e, 0x6d, 0x81, 0x8b, - 0x7c, 0xff, 0xad, 0x54, 0x71, 0x5c, 0xb6, 0xd1, 0x6e, 0x18, 0x4d, 0xd2, 0x52, 0x36, 0x52, 0x3f, - 0x55, 0x6a, 0x6f, 0x9a, 0x6c, 0x27, 0xc0, 0x54, 0x14, 0x50, 0x4b, 0x22, 0xc3, 0x3a, 0x18, 0x63, - 0x84, 0x21, 0xaf, 0x4e, 0x37, 0x50, 0x88, 0x69, 0x3e, 0xc5, 0xe9, 0x6b, 0xf7, 0x38, 0xdc, 0xd7, - 0xa3, 0xd2, 0xdc, 0x1f, 0xc0, 0xad, 0xf9, 0xec, 0x70, 0xaf, 0x0a, 0x94, 0xb4, 0x35, 0x9f, 0x59, - 0x39, 0x81, 0xb8, 0x2e, 0x00, 0x95, 0x03, 0x3e, 0x6a, 0x60, 0x42, 0xec, 0x62, 0x05, 0x07, 0x84, - 0xba, 0xac, 0xeb, 0x02, 0x03, 0x64, 0xc8, 0xb6, 0x8f, 0x43, 0xd9, 0x77, 0x2d, 0x7f, 0xb8, 0x57, - 0x9d, 0x50, 0x50, 0xcb, 0xb6, 0x1d, 0x62, 0x4a, 0xd7, 0x59, 0xe8, 0xfa, 0x8e, 0x25, 0xd3, 0x7a, - 0x5d, 0x93, 0xfc, 0x8d, 0x6b, 0x52, 0xff, 0xea, 0x1a, 0xa5, 0xf7, 0x83, 0x06, 0x2e, 0xf7, 0xe9, - 0x55, 0x7b, 0x5a, 0x01, 0x23, 0xb6, 0x3a, 0x53, 0x0e, 0x2a, 0xc7, 0x38, 0x48, 0x95, 0xf5, 0x99, - 0xa8, 0x5b, 0x79, 0x61, 0x3e, 0x52, 0x72, 0x3f, 0x25, 0xc1, 0xff, 0x7d, 0x94, 0xf0, 0x16, 0x18, - 0x55, 0x74, 0x64, 0xf8, 0x74, 0x4f, 0x53, 0xcf, 0x9f, 0xb0, 0x0b, 0xc6, 0xa4, 0x49, 0xea, 0x7c, - 0x15, 0xb6, 0xb2, 0xca, 0xea, 0x5f, 0x5b, 0x25, 0x5e, 0x41, 0x4e, 0x62, 0x3f, 0xe4, 0xd0, 0xd0, - 0xef, 0x52, 0x75, 0x90, 0xd7, 0xc6, 0xf9, 0xf4, 0xc5, 0xfb, 0x5f, 0xf1, 0x3d, 0xe5, 0xf8, 0x72, - 0x8a, 0x4b, 0x2f, 0x53, 0x20, 0x23, 0x96, 0x0e, 0x5f, 0x80, 0xac, 0xbc, 0xce, 0xe0, 0x6c, 0xcc, - 0x72, 0x07, 0x6f, 0xcf, 0xe2, 0xdc, 0xb0, 0x34, 0xb9, 0x94, 0xf2, 0xd5, 0xdd, 0xcf, 0x3f, 0xde, - 0x24, 0x27, 0x61, 0xc1, 0x1c, 0xbc, 0xa2, 0xe5, 0x95, 0x09, 0x3b, 0x20, 0x23, 0x2e, 0x2c, 0x78, - 0xfd, 0x5c, 0xcc, 0x9e, 0x6b, 0xb4, 0x38, 0x3b, 0x24, 0x4b, 0x11, 0xcf, 0x08, 0xe2, 0x22, 0xcc, - 0xc7, 0x11, 0x0b, 0xba, 0x5d, 0x0d, 0x8c, 0x44, 0x6e, 0x87, 0xf3, 0xe7, 0xa1, 0xf6, 0x7d, 0xbf, - 0xc5, 0xca, 0xf0, 0x44, 0xa5, 0xe0, 0x9a, 0x50, 0x30, 0x0d, 0x27, 0x63, 0x14, 0x44, 0xdf, 0x45, - 0x6d, 0x79, 0xff, 0x58, 0xd7, 0x0e, 0x8e, 0x75, 0xed, 0xfb, 0xb1, 0xae, 0xbd, 0x3e, 0xd1, 0x13, - 0x07, 0x27, 0x7a, 0xe2, 0xcb, 0x89, 0x9e, 0x78, 0x36, 0xdf, 0xb3, 0xd9, 0x05, 0xc7, 0x43, 0x0d, - 0x6a, 0x2e, 0x38, 0xd5, 0xe6, 0x06, 0x72, 0x7d, 0xf3, 0xb9, 0x44, 0x13, 0xeb, 0x6d, 0x64, 0xc5, - 0xbf, 0xdc, 0xcd, 0x5f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x27, 0xfc, 0x40, 0x60, 0xd2, 0x07, 0x00, - 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - // Params queries all parameters of the swap module. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Pools queries pools based on pool ID - Pools(ctx context.Context, in *QueryPoolsRequest, opts ...grpc.CallOption) (*QueryPoolsResponse, error) - // Deposits queries deposit details based on owner address and pool - Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { - out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, "/kava.swap.v1beta1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Pools(ctx context.Context, in *QueryPoolsRequest, opts ...grpc.CallOption) (*QueryPoolsResponse, error) { - out := new(QueryPoolsResponse) - err := c.cc.Invoke(ctx, "/kava.swap.v1beta1.Query/Pools", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Deposits(ctx context.Context, in *QueryDepositsRequest, opts ...grpc.CallOption) (*QueryDepositsResponse, error) { - out := new(QueryDepositsResponse) - err := c.cc.Invoke(ctx, "/kava.swap.v1beta1.Query/Deposits", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Params queries all parameters of the swap module. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Pools queries pools based on pool ID - Pools(context.Context, *QueryPoolsRequest) (*QueryPoolsResponse, error) - // Deposits queries deposit details based on owner address and pool - Deposits(context.Context, *QueryDepositsRequest) (*QueryDepositsResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") -} -func (*UnimplementedQueryServer) Pools(ctx context.Context, req *QueryPoolsRequest) (*QueryPoolsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Pools not implemented") -} -func (*UnimplementedQueryServer) Deposits(ctx context.Context, req *QueryDepositsRequest) (*QueryDepositsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposits not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryParamsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Params(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.swap.v1beta1.Query/Params", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Pools_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryPoolsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Pools(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.swap.v1beta1.Query/Pools", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Pools(ctx, req.(*QueryPoolsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Deposits_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryDepositsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Deposits(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.swap.v1beta1.Query/Deposits", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Deposits(ctx, req.(*QueryDepositsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.swap.v1beta1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Pools", - Handler: _Query_Pools_Handler, - }, - { - MethodName: "Deposits", - Handler: _Query_Deposits_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/swap/v1beta1/query.proto", -} - -func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryPoolsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryPoolsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPoolsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.PoolId) > 0 { - i -= len(m.PoolId) - copy(dAtA[i:], m.PoolId) - i = encodeVarintQuery(dAtA, i, uint64(len(m.PoolId))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryPoolsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryPoolsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPoolsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Pools) > 0 { - for iNdEx := len(m.Pools) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Pools[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *PoolResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PoolResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PoolResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.TotalShares.Size() - i -= size - if _, err := m.TotalShares.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Coins) > 0 { - for iNdEx := len(m.Coins) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Coins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Name) > 0 { - i -= len(m.Name) - copy(dAtA[i:], m.Name) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Name))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDepositsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryDepositsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - if len(m.PoolId) > 0 { - i -= len(m.PoolId) - copy(dAtA[i:], m.PoolId) - i = encodeVarintQuery(dAtA, i, uint64(len(m.PoolId))) - i-- - dAtA[i] = 0x12 - } - if len(m.Owner) > 0 { - i -= len(m.Owner) - copy(dAtA[i:], m.Owner) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Owner))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryDepositsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryDepositsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryDepositsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Deposits) > 0 { - for iNdEx := len(m.Deposits) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Deposits[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *DepositResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *DepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.SharesValue) > 0 { - for iNdEx := len(m.SharesValue) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SharesValue[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - { - size := m.SharesOwned.Size() - i -= size - if _, err := m.SharesOwned.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.PoolId) > 0 { - i -= len(m.PoolId) - copy(dAtA[i:], m.PoolId) - i = encodeVarintQuery(dAtA, i, uint64(len(m.PoolId))) - i-- - dAtA[i] = 0x12 - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryParamsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryPoolsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.PoolId) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryPoolsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Pools) > 0 { - for _, e := range m.Pools { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *PoolResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Name) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.Coins) > 0 { - for _, e := range m.Coins { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - l = m.TotalShares.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryDepositsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Owner) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.PoolId) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryDepositsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Deposits) > 0 { - for _, e := range m.Deposits { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *DepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.PoolId) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = m.SharesOwned.Size() - n += 1 + l + sovQuery(uint64(l)) - if len(m.SharesValue) > 0 { - for _, e := range m.SharesValue { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryPoolsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryPoolsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPoolsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PoolId = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryPoolsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryPoolsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPoolsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pools", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Pools = append(m.Pools, PoolResponse{}) - if err := m.Pools[len(m.Pools)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *PoolResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PoolResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PoolResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Name = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Coins", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Coins = append(m.Coins, types.Coin{}) - if err := m.Coins[len(m.Coins)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalShares", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TotalShares.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDepositsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryDepositsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Owner", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Owner = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PoolId = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryDepositsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryDepositsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryDepositsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Deposits", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Deposits = append(m.Deposits, DepositResponse{}) - if err := m.Deposits[len(m.Deposits)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DepositResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PoolId = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SharesOwned", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.SharesOwned.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SharesValue", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SharesValue = append(m.SharesValue, types.Coin{}) - if err := m.SharesValue[len(m.SharesValue)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/swap/types/query.pb.gw.go b/x/swap/types/query.pb.gw.go deleted file mode 100644 index d0c87d04..00000000 --- a/x/swap/types/query.pb.gw.go +++ /dev/null @@ -1,319 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: kava/swap/v1beta1/query.proto - -/* -Package types is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package types - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join - -func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Params(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Pools_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Pools_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPoolsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Pools_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Pools(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Pools_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPoolsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Pools_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Pools(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Deposits_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Deposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Deposits(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Deposits_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryDepositsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Deposits_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Deposits(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Pools_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Pools_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Pools_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Deposits_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Deposits_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Deposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Pools_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Pools_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Pools_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Deposits_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Deposits_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Deposits_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "swap", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Pools_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "swap", "v1beta1", "pools"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Deposits_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"kava", "swap", "v1beta1", "deposits"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Pools_0 = runtime.ForwardResponseMessage - - forward_Query_Deposits_0 = runtime.ForwardResponseMessage -) diff --git a/x/swap/types/state.go b/x/swap/types/state.go deleted file mode 100644 index 7c729fc8..00000000 --- a/x/swap/types/state.go +++ /dev/null @@ -1,180 +0,0 @@ -package types - -import ( - "errors" - "fmt" - "strings" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// PoolIDSep represents the separator used in pool ids to separate two denominations -const PoolIDSep = ":" - -// PoolIDFromCoins returns a poolID from a coins object -func PoolIDFromCoins(coins sdk.Coins) string { - return PoolID(coins[0].Denom, coins[1].Denom) -} - -// PoolID returns an alphabetically sorted pool name from two denoms. -// The name is commutative for any all pairs A,B: f(A,B) == f(B,A). -func PoolID(denomA string, denomB string) string { - if denomB < denomA { - return fmt.Sprintf("%s%s%s", denomB, PoolIDSep, denomA) - } - - return fmt.Sprintf("%s%s%s", denomA, PoolIDSep, denomB) -} - -// NewPoolRecord takes reserve coins and total shares, returning -// a new pool record with a id -func NewPoolRecord(reserves sdk.Coins, totalShares sdkmath.Int) PoolRecord { - if len(reserves) != 2 { - panic("reserves must have two denominations") - } - - poolID := PoolIDFromCoins(reserves) - - return PoolRecord{ - PoolID: poolID, - ReservesA: reserves[0], - ReservesB: reserves[1], - TotalShares: totalShares, - } -} - -// NewPoolRecordFromPool takes a pointer to a denominated pool and returns a -// pool record for storage in state. -func NewPoolRecordFromPool(pool *DenominatedPool) PoolRecord { - reserves := pool.Reserves() - poolID := PoolIDFromCoins(reserves) - - return PoolRecord{ - PoolID: poolID, - ReservesA: reserves[0], - ReservesB: reserves[1], - TotalShares: pool.TotalShares(), - } -} - -// Validate performs basic validation checks of the record data -func (p PoolRecord) Validate() error { - if p.PoolID == "" { - return errors.New("poolID must be set") - } - - tokens := strings.Split(p.PoolID, PoolIDSep) - if len(tokens) != 2 || tokens[0] == "" || tokens[1] == "" || tokens[1] < tokens[0] || tokens[0] == tokens[1] { - return fmt.Errorf("poolID '%s' is invalid", p.PoolID) - } - if sdk.ValidateDenom(tokens[0]) != nil || sdk.ValidateDenom(tokens[1]) != nil { - return fmt.Errorf("poolID '%s' is invalid", p.PoolID) - } - if tokens[0] != p.ReservesA.Denom || tokens[1] != p.ReservesB.Denom { - return fmt.Errorf("poolID '%s' does not match reserves", p.PoolID) - } - - if !p.ReservesA.IsPositive() { - return fmt.Errorf("pool '%s' has invalid reserves: %s", p.PoolID, p.ReservesA) - } - - if !p.ReservesB.IsPositive() { - return fmt.Errorf("pool '%s' has invalid reserves: %s", p.PoolID, p.ReservesB) - } - - if !p.TotalShares.IsPositive() { - return fmt.Errorf("pool '%s' has invalid total shares: %s", p.PoolID, p.TotalShares) - } - - return nil -} - -// Reserves returns the total reserves for a pool -func (p PoolRecord) Reserves() sdk.Coins { - return sdk.NewCoins(p.ReservesA, p.ReservesB) -} - -// PoolRecords is a slice of PoolRecord -type PoolRecords []PoolRecord - -// Validate performs basic validation checks on all records in the slice -func (prs PoolRecords) Validate() error { - seenPoolIDs := make(map[string]bool) - - for _, p := range prs { - if err := p.Validate(); err != nil { - return err - } - - if seenPoolIDs[p.PoolID] { - return fmt.Errorf("duplicate poolID '%s'", p.PoolID) - } - - seenPoolIDs[p.PoolID] = true - } - - return nil -} - -// NewShareRecord takes a depositor, poolID, and shares and returns -// a new share record for storage in state. -func NewShareRecord(depositor sdk.AccAddress, poolID string, sharesOwned sdkmath.Int) ShareRecord { - return ShareRecord{ - Depositor: depositor, - PoolID: poolID, - SharesOwned: sharesOwned, - } -} - -// Validate performs basic validation checks of the record data -func (sr ShareRecord) Validate() error { - if sr.PoolID == "" { - return errors.New("poolID must be set") - } - - tokens := strings.Split(sr.PoolID, PoolIDSep) - if len(tokens) != 2 || tokens[0] == "" || tokens[1] == "" || tokens[1] < tokens[0] || tokens[0] == tokens[1] { - return fmt.Errorf("poolID '%s' is invalid", sr.PoolID) - } - if sdk.ValidateDenom(tokens[0]) != nil || sdk.ValidateDenom(tokens[1]) != nil { - return fmt.Errorf("poolID '%s' is invalid", sr.PoolID) - } - - if sr.Depositor.Empty() { - return fmt.Errorf("share record cannot have empty depositor address") - } - - if !sr.SharesOwned.IsPositive() { - return fmt.Errorf("depositor '%s' and pool '%s' has invalid total shares: %s", sr.Depositor, sr.PoolID, sr.SharesOwned.String()) - } - - return nil -} - -// ShareRecords is a slice of ShareRecord -type ShareRecords []ShareRecord - -// Validate performs basic validation checks on all records in the slice -func (srs ShareRecords) Validate() error { - seenDepositors := make(map[string]map[string]bool) - - for _, sr := range srs { - if err := sr.Validate(); err != nil { - return err - } - - if seenPools, found := seenDepositors[sr.Depositor.String()]; found { - if seenPools[sr.PoolID] { - return fmt.Errorf("duplicate depositor '%s' and poolID '%s'", sr.Depositor, sr.PoolID) - } - seenPools[sr.PoolID] = true - } else { - seenPools := make(map[string]bool) - seenPools[sr.PoolID] = true - seenDepositors[sr.Depositor.String()] = seenPools - } - } - - return nil -} diff --git a/x/swap/types/state_test.go b/x/swap/types/state_test.go deleted file mode 100644 index 5d26a9ab..00000000 --- a/x/swap/types/state_test.go +++ /dev/null @@ -1,531 +0,0 @@ -package types_test - -import ( - "encoding/json" - "testing" - - types "github.com/0glabs/0g-chain/x/swap/types" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "sigs.k8s.io/yaml" -) - -func TestState_PoolID(t *testing.T) { - testCases := []struct { - reserveA string - reserveB string - expectedID string - }{ - {"atoken", "btoken", "atoken:btoken"}, - {"btoken", "atoken", "atoken:btoken"}, - {"aaa", "aaaa", "aaa:aaaa"}, - {"aaaa", "aaa", "aaa:aaaa"}, - {"aaaa", "aaab", "aaaa:aaab"}, - {"aaab", "aaaa", "aaaa:aaab"}, - {"a001", "a002", "a001:a002"}, - {"a002", "a001", "a001:a002"}, - {"AAAA", "aaaa", "AAAA:aaaa"}, - {"aaaa", "AAAA", "AAAA:aaaa"}, - } - - for _, tc := range testCases { - assert.Equal(t, tc.expectedID, types.PoolID(tc.reserveA, tc.reserveB)) - assert.Equal(t, tc.expectedID, types.PoolID(tc.reserveB, tc.reserveA)) - - assert.Equal(t, tc.expectedID, types.PoolIDFromCoins(sdk.NewCoins(sdk.NewCoin(tc.reserveA, i(1)), sdk.NewCoin(tc.reserveB, i(1))))) - assert.Equal(t, tc.expectedID, types.PoolIDFromCoins(sdk.NewCoins(sdk.NewCoin(tc.reserveB, i(1)), sdk.NewCoin(tc.reserveA, i(1))))) - } -} - -func TestState_NewPoolRecord(t *testing.T) { - reserves := sdk.NewCoins(usdx(50e6), ukava(10e6)) - totalShares := sdkmath.NewInt(30e6) - - poolRecord := types.NewPoolRecord(reserves, totalShares) - - assert.Equal(t, reserves[0], poolRecord.ReservesA) - assert.Equal(t, reserves[1], poolRecord.ReservesB) - assert.Equal(t, reserves, poolRecord.Reserves()) - assert.Equal(t, totalShares, poolRecord.TotalShares) - - assert.PanicsWithValue(t, "reserves must have two denominations", func() { - reserves := sdk.NewCoins(ukava(10e6)) - _ = types.NewPoolRecord(reserves, totalShares) - }, "expected panic with 1 coin in reserves") - - assert.PanicsWithValue(t, "reserves must have two denominations", func() { - reserves := sdk.NewCoins(ukava(10e6), hard(1e6), usdx(20e6)) - _ = types.NewPoolRecord(reserves, totalShares) - }, "expected panic with 3 coins in reserves") -} - -func TestState_NewPoolRecordFromPool(t *testing.T) { - reserves := sdk.NewCoins(usdx(50e6), ukava(10e6)) - - pool, err := types.NewDenominatedPool(reserves) - require.NoError(t, err) - - record := types.NewPoolRecordFromPool(pool) - - assert.Equal(t, types.PoolID("ukava", "usdx"), record.PoolID) - assert.Equal(t, ukava(10e6), record.ReservesA) - assert.Equal(t, record.ReservesB, usdx(50e6)) - assert.Equal(t, pool.TotalShares(), record.TotalShares) - assert.Equal(t, sdk.NewCoins(ukava(10e6), usdx(50e6)), record.Reserves()) - assert.Nil(t, record.Validate()) -} - -func TestState_PoolRecord_JSONEncoding(t *testing.T) { - raw := `{ - "pool_id": "ukava:usdx", - "reserves_a": { "denom": "ukava", "amount": "1000000" }, - "reserves_b": { "denom": "usdx", "amount": "5000000" }, - "total_shares": "3000000" - }` - - var record types.PoolRecord - err := json.Unmarshal([]byte(raw), &record) - require.NoError(t, err) - - assert.Equal(t, types.PoolID("ukava", "usdx"), record.PoolID) - assert.Equal(t, ukava(1e6), record.ReservesA) - assert.Equal(t, usdx(5e6), record.ReservesB) - assert.Equal(t, i(3e6), record.TotalShares) -} - -func TestState_PoolRecord_YamlEncoding(t *testing.T) { - expected := `pool_id: ukava:usdx -reserves_a: - amount: "1000000" - denom: ukava -reserves_b: - amount: "5000000" - denom: usdx -total_shares: "3000000" -` - record := types.NewPoolRecord(sdk.NewCoins(ukava(1e6), usdx(5e6)), i(3e6)) - data, err := yaml.Marshal(record) - require.NoError(t, err) - - assert.Equal(t, expected, string(data)) -} - -func TestState_PoolRecord_Validations(t *testing.T) { - validRecord := types.NewPoolRecord( - sdk.NewCoins(usdx(500e6), ukava(100e6)), - i(300e6), - ) - testCases := []struct { - name string - poolID string - reservesA sdk.Coin - reservesB sdk.Coin - totalShares sdkmath.Int - expectedErr string - }{ - { - name: "empty pool id", - poolID: "", - reservesA: validRecord.ReservesA, - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "poolID must be set", - }, - { - name: "no poolID tokens", - poolID: "ukavausdx", - reservesA: validRecord.ReservesA, - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "poolID 'ukavausdx' is invalid", - }, - { - name: "poolID empty tokens", - poolID: ":", - reservesA: validRecord.ReservesA, - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "poolID ':' is invalid", - }, - { - name: "poolID empty token a", - poolID: ":usdx", - reservesA: validRecord.ReservesA, - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "poolID ':usdx' is invalid", - }, - { - name: "poolID empty token b", - poolID: "ukava:", - reservesA: validRecord.ReservesA, - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "poolID 'ukava:' is invalid", - }, - { - name: "poolID is not sorted", - poolID: "usdx:ukava", - reservesA: validRecord.ReservesA, - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "poolID 'usdx:ukava' is invalid", - }, - { - name: "poolID has duplicate denoms", - poolID: "ukava:ukava", - reservesA: validRecord.ReservesA, - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "poolID 'ukava:ukava' is invalid", - }, - { - name: "poolID does not match reserve A", - poolID: "ukava:usdx", - reservesA: hard(5e6), - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "poolID 'ukava:usdx' does not match reserves", - }, - { - name: "poolID does not match reserve B", - poolID: "ukava:usdx", - reservesA: validRecord.ReservesA, - reservesB: hard(5e6), - totalShares: validRecord.TotalShares, - expectedErr: "poolID 'ukava:usdx' does not match reserves", - }, - { - name: "negative reserve a", - poolID: "ukava:usdx", - reservesA: sdk.Coin{Denom: "ukava", Amount: sdkmath.NewInt(-1)}, - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "pool 'ukava:usdx' has invalid reserves: -1ukava", - }, - { - name: "zero reserve a", - poolID: "ukava:usdx", - reservesA: sdk.Coin{Denom: "ukava", Amount: sdk.ZeroInt()}, - reservesB: validRecord.ReservesB, - totalShares: validRecord.TotalShares, - expectedErr: "pool 'ukava:usdx' has invalid reserves: 0ukava", - }, - { - name: "negative reserve b", - poolID: "ukava:usdx", - reservesA: validRecord.ReservesA, - reservesB: sdk.Coin{Denom: "usdx", Amount: sdkmath.NewInt(-1)}, - totalShares: validRecord.TotalShares, - expectedErr: "pool 'ukava:usdx' has invalid reserves: -1usdx", - }, - { - name: "zero reserve b", - poolID: "ukava:usdx", - reservesA: validRecord.ReservesA, - reservesB: sdk.Coin{Denom: "usdx", Amount: sdk.ZeroInt()}, - totalShares: validRecord.TotalShares, - expectedErr: "pool 'ukava:usdx' has invalid reserves: 0usdx", - }, - { - name: "negative total shares", - poolID: validRecord.PoolID, - reservesA: validRecord.ReservesA, - reservesB: validRecord.ReservesB, - totalShares: sdkmath.NewInt(-1), - expectedErr: "pool 'ukava:usdx' has invalid total shares: -1", - }, - { - name: "zero total shares", - poolID: validRecord.PoolID, - reservesA: validRecord.ReservesA, - reservesB: validRecord.ReservesB, - totalShares: sdk.ZeroInt(), - expectedErr: "pool 'ukava:usdx' has invalid total shares: 0", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - record := types.PoolRecord{ - PoolID: tc.poolID, - ReservesA: tc.reservesA, - ReservesB: tc.reservesB, - TotalShares: tc.totalShares, - } - err := record.Validate() - assert.EqualError(t, err, tc.expectedErr) - }) - } -} - -func TestState_PoolRecord_OrderedReserves(t *testing.T) { - invalidOrder := types.NewPoolRecord( - // force order to not be sorted - sdk.Coins{usdx(500e6), ukava(100e6)}, - i(300e6), - ) - assert.Error(t, invalidOrder.Validate()) - - validOrder := types.NewPoolRecord( - // force order to not be sorted - sdk.Coins{ukava(500e6), usdx(100e6)}, - i(300e6), - ) - assert.NoError(t, validOrder.Validate()) - - record_1 := types.NewPoolRecord(sdk.NewCoins(usdx(500e6), ukava(100e6)), i(300e6)) - record_2 := types.NewPoolRecord(sdk.NewCoins(ukava(100e6), usdx(500e6)), i(300e6)) - // ensure no regresssions in NewCoins ordering - assert.Equal(t, record_1, record_2) - assert.Equal(t, types.PoolID("ukava", "usdx"), record_1.PoolID) - assert.Equal(t, types.PoolID("ukava", "usdx"), record_2.PoolID) -} - -func TestState_PoolRecords_Validation(t *testing.T) { - validRecord := types.NewPoolRecord( - sdk.NewCoins(usdx(500e6), ukava(100e6)), - i(300e6), - ) - - invalidRecord := types.NewPoolRecord( - sdk.NewCoins(usdx(500e6), ukava(100e6)), - i(-1), - ) - - records := types.PoolRecords{ - validRecord, - } - assert.NoError(t, records.Validate()) - - records = append(records, invalidRecord) - err := records.Validate() - assert.Error(t, err) - assert.EqualError(t, err, "pool 'ukava:usdx' has invalid total shares: -1") -} - -func TestState_PoolRecords_ValidateUniquePools(t *testing.T) { - record_1 := types.NewPoolRecord( - sdk.NewCoins(usdx(500e6), ukava(100e6)), - i(300e6), - ) - - record_2 := types.NewPoolRecord( - sdk.NewCoins(usdx(5000e6), ukava(1000e6)), - i(3000e6), - ) - - record_3 := types.NewPoolRecord( - sdk.NewCoins(usdx(5000e6), hard(1000e6)), - i(3000e6), - ) - - validRecords := types.PoolRecords{record_1, record_3} - assert.NoError(t, validRecords.Validate()) - - invalidRecords := types.PoolRecords{record_1, record_2} - assert.EqualError(t, invalidRecords.Validate(), "duplicate poolID 'ukava:usdx'") -} - -func TestState_NewShareRecord(t *testing.T) { - depositor := sdk.AccAddress("some user") - poolID := types.PoolID("ukava", "usdx") - shares := sdkmath.NewInt(1e6) - - record := types.NewShareRecord(depositor, poolID, shares) - - assert.Equal(t, depositor, record.Depositor) - assert.Equal(t, poolID, record.PoolID) - assert.Equal(t, shares, record.SharesOwned) -} - -func TestState_ShareRecord_JSONEncoding(t *testing.T) { - raw := `{ - "depositor": "kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w", - "pool_id": "ukava:usdx", - "shares_owned": "3000000" - }` - - var record types.ShareRecord - err := json.Unmarshal([]byte(raw), &record) - require.NoError(t, err) - - assert.Equal(t, "kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w", record.Depositor.String()) - assert.Equal(t, types.PoolID("ukava", "usdx"), record.PoolID) - assert.Equal(t, i(3e6), record.SharesOwned) -} - -func TestState_ShareRecord_YamlEncoding(t *testing.T) { - expected := `depositor: kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w -pool_id: ukava:usdx -shares_owned: "3000000" -` - depositor, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - require.NoError(t, err) - - record := types.NewShareRecord(depositor, "ukava:usdx", i(3e6)) - data, err := yaml.Marshal(record) - require.NoError(t, err) - - assert.Equal(t, expected, string(data)) -} - -func TestState_InvalidShareRecordEmptyDepositor(t *testing.T) { - record := types.ShareRecord{ - Depositor: sdk.AccAddress{}, - PoolID: types.PoolID("ukava", "usdx"), - SharesOwned: sdkmath.NewInt(1e6), - } - require.Error(t, record.Validate()) -} - -func TestState_InvalidShareRecordNegativeShares(t *testing.T) { - record := types.ShareRecord{ - Depositor: sdk.AccAddress("some user ----------------"), - PoolID: types.PoolID("ukava", "usdx"), - SharesOwned: sdkmath.NewInt(-1e6), - } - require.Error(t, record.Validate()) -} - -func TestState_ShareRecord_Validations(t *testing.T) { - depositor, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - require.NoError(t, err) - validRecord := types.NewShareRecord( - depositor, - types.PoolID("ukava", "usdx"), - i(30e6), - ) - testCases := []struct { - name string - depositor sdk.AccAddress - poolID string - sharesOwned sdkmath.Int - expectedErr string - }{ - { - name: "empty pool id", - depositor: validRecord.Depositor, - poolID: "", - sharesOwned: validRecord.SharesOwned, - expectedErr: "poolID must be set", - }, - { - name: "no poolID tokens", - depositor: validRecord.Depositor, - poolID: "ukavausdx", - sharesOwned: validRecord.SharesOwned, - expectedErr: "poolID 'ukavausdx' is invalid", - }, - { - name: "poolID empty tokens", - depositor: validRecord.Depositor, - poolID: ":", - sharesOwned: validRecord.SharesOwned, - expectedErr: "poolID ':' is invalid", - }, - { - name: "poolID empty token a", - depositor: validRecord.Depositor, - poolID: ":usdx", - sharesOwned: validRecord.SharesOwned, - expectedErr: "poolID ':usdx' is invalid", - }, - { - name: "poolID empty token b", - depositor: validRecord.Depositor, - poolID: "ukava:", - sharesOwned: validRecord.SharesOwned, - expectedErr: "poolID 'ukava:' is invalid", - }, - { - name: "poolID is not sorted", - depositor: validRecord.Depositor, - poolID: "usdx:ukava", - sharesOwned: validRecord.SharesOwned, - expectedErr: "poolID 'usdx:ukava' is invalid", - }, - { - name: "poolID has duplicate denoms", - depositor: validRecord.Depositor, - poolID: "ukava:ukava", - sharesOwned: validRecord.SharesOwned, - expectedErr: "poolID 'ukava:ukava' is invalid", - }, - { - name: "negative total shares", - depositor: validRecord.Depositor, - poolID: validRecord.PoolID, - sharesOwned: sdkmath.NewInt(-1), - expectedErr: "depositor 'kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w' and pool 'ukava:usdx' has invalid total shares: -1", - }, - { - name: "zero total shares", - depositor: validRecord.Depositor, - poolID: validRecord.PoolID, - sharesOwned: sdk.ZeroInt(), - expectedErr: "depositor 'kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w' and pool 'ukava:usdx' has invalid total shares: 0", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - record := types.ShareRecord{ - Depositor: tc.depositor, - PoolID: tc.poolID, - SharesOwned: tc.sharesOwned, - } - err := record.Validate() - assert.EqualError(t, err, tc.expectedErr) - }) - } -} - -func TestState_ShareRecords_Validation(t *testing.T) { - depositor, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - require.NoError(t, err) - - validRecord := types.NewShareRecord( - depositor, - types.PoolID("hard", "usdx"), - i(300e6), - ) - - invalidRecord := types.NewShareRecord( - depositor, - types.PoolID("hard", "usdx"), - i(-1), - ) - - records := types.ShareRecords{ - validRecord, - } - assert.NoError(t, records.Validate()) - - records = append(records, invalidRecord) - err = records.Validate() - assert.Error(t, err) - assert.EqualError(t, err, "depositor 'kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w' and pool 'hard:usdx' has invalid total shares: -1") -} - -func TestState_ShareRecords_ValidateUniqueShareRecords(t *testing.T) { - depositor_1, err := sdk.AccAddressFromBech32("kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w") - require.NoError(t, err) - - depositor_2, err := sdk.AccAddressFromBech32("kava1esagqd83rhqdtpy5sxhklaxgn58k2m3s3mnpea") - require.NoError(t, err) - - record_1 := types.NewShareRecord(depositor_1, "ukava:usdx", i(20e6)) - record_2 := types.NewShareRecord(depositor_1, "ukava:usdx", i(10e6)) - record_3 := types.NewShareRecord(depositor_1, "hard:usdx", i(20e6)) - record_4 := types.NewShareRecord(depositor_2, "ukava:usdx", i(20e6)) - - validRecords := types.ShareRecords{record_1, record_3, record_4} - assert.NoError(t, validRecords.Validate()) - - invalidRecords := types.ShareRecords{record_1, record_3, record_2, record_4} - assert.EqualError(t, invalidRecords.Validate(), "duplicate depositor 'kava1mq9qxlhze029lm0frzw2xr6hem8c3k9ts54w0w' and poolID 'ukava:usdx'") -} diff --git a/x/swap/types/swap.pb.go b/x/swap/types/swap.pb.go deleted file mode 100644 index 6186cf0e..00000000 --- a/x/swap/types/swap.pb.go +++ /dev/null @@ -1,1227 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/swap/v1beta1/swap.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// Params defines the parameters for the swap module. -type Params struct { - // allowed_pools defines that pools that are allowed to be created - AllowedPools AllowedPools `protobuf:"bytes,1,rep,name=allowed_pools,json=allowedPools,proto3,castrepeated=AllowedPools" json:"allowed_pools"` - // swap_fee defines the swap fee for all pools - SwapFee github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=swap_fee,json=swapFee,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"swap_fee"` -} - -func (m *Params) Reset() { *m = Params{} } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_9df359be90eb28cb, []int{0} -} -func (m *Params) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Params.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Params) XXX_Merge(src proto.Message) { - xxx_messageInfo_Params.Merge(m, src) -} -func (m *Params) XXX_Size() int { - return m.Size() -} -func (m *Params) XXX_DiscardUnknown() { - xxx_messageInfo_Params.DiscardUnknown(m) -} - -var xxx_messageInfo_Params proto.InternalMessageInfo - -func (m *Params) GetAllowedPools() AllowedPools { - if m != nil { - return m.AllowedPools - } - return nil -} - -// AllowedPool defines a pool that is allowed to be created -type AllowedPool struct { - // token_a represents the a token allowed - TokenA string `protobuf:"bytes,1,opt,name=token_a,json=tokenA,proto3" json:"token_a,omitempty"` - // token_b represents the b token allowed - TokenB string `protobuf:"bytes,2,opt,name=token_b,json=tokenB,proto3" json:"token_b,omitempty"` -} - -func (m *AllowedPool) Reset() { *m = AllowedPool{} } -func (*AllowedPool) ProtoMessage() {} -func (*AllowedPool) Descriptor() ([]byte, []int) { - return fileDescriptor_9df359be90eb28cb, []int{1} -} -func (m *AllowedPool) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AllowedPool) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AllowedPool.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *AllowedPool) XXX_Merge(src proto.Message) { - xxx_messageInfo_AllowedPool.Merge(m, src) -} -func (m *AllowedPool) XXX_Size() int { - return m.Size() -} -func (m *AllowedPool) XXX_DiscardUnknown() { - xxx_messageInfo_AllowedPool.DiscardUnknown(m) -} - -var xxx_messageInfo_AllowedPool proto.InternalMessageInfo - -func (m *AllowedPool) GetTokenA() string { - if m != nil { - return m.TokenA - } - return "" -} - -func (m *AllowedPool) GetTokenB() string { - if m != nil { - return m.TokenB - } - return "" -} - -// PoolRecord represents the state of a liquidity pool -// and is used to store the state of a denominated pool -type PoolRecord struct { - // pool_id represents the unique id of the pool - PoolID string `protobuf:"bytes,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` - // reserves_a is the a token coin reserves - ReservesA types.Coin `protobuf:"bytes,2,opt,name=reserves_a,json=reservesA,proto3" json:"reserves_a"` - // reserves_b is the a token coin reserves - ReservesB types.Coin `protobuf:"bytes,3,opt,name=reserves_b,json=reservesB,proto3" json:"reserves_b"` - // total_shares is the total distrubuted shares of the pool - TotalShares github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,4,opt,name=total_shares,json=totalShares,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"total_shares"` -} - -func (m *PoolRecord) Reset() { *m = PoolRecord{} } -func (m *PoolRecord) String() string { return proto.CompactTextString(m) } -func (*PoolRecord) ProtoMessage() {} -func (*PoolRecord) Descriptor() ([]byte, []int) { - return fileDescriptor_9df359be90eb28cb, []int{2} -} -func (m *PoolRecord) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *PoolRecord) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_PoolRecord.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *PoolRecord) XXX_Merge(src proto.Message) { - xxx_messageInfo_PoolRecord.Merge(m, src) -} -func (m *PoolRecord) XXX_Size() int { - return m.Size() -} -func (m *PoolRecord) XXX_DiscardUnknown() { - xxx_messageInfo_PoolRecord.DiscardUnknown(m) -} - -var xxx_messageInfo_PoolRecord proto.InternalMessageInfo - -func (m *PoolRecord) GetPoolID() string { - if m != nil { - return m.PoolID - } - return "" -} - -func (m *PoolRecord) GetReservesA() types.Coin { - if m != nil { - return m.ReservesA - } - return types.Coin{} -} - -func (m *PoolRecord) GetReservesB() types.Coin { - if m != nil { - return m.ReservesB - } - return types.Coin{} -} - -// ShareRecord stores the shares owned for a depositor and pool -type ShareRecord struct { - // depositor represents the owner of the shares - Depositor github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=depositor,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"depositor,omitempty"` - // pool_id represents the pool the shares belong to - PoolID string `protobuf:"bytes,2,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` - // shares_owned represents the number of shares owned by depsoitor for the pool_id - SharesOwned github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=shares_owned,json=sharesOwned,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"shares_owned"` -} - -func (m *ShareRecord) Reset() { *m = ShareRecord{} } -func (m *ShareRecord) String() string { return proto.CompactTextString(m) } -func (*ShareRecord) ProtoMessage() {} -func (*ShareRecord) Descriptor() ([]byte, []int) { - return fileDescriptor_9df359be90eb28cb, []int{3} -} -func (m *ShareRecord) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ShareRecord) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ShareRecord.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *ShareRecord) XXX_Merge(src proto.Message) { - xxx_messageInfo_ShareRecord.Merge(m, src) -} -func (m *ShareRecord) XXX_Size() int { - return m.Size() -} -func (m *ShareRecord) XXX_DiscardUnknown() { - xxx_messageInfo_ShareRecord.DiscardUnknown(m) -} - -var xxx_messageInfo_ShareRecord proto.InternalMessageInfo - -func (m *ShareRecord) GetDepositor() github_com_cosmos_cosmos_sdk_types.AccAddress { - if m != nil { - return m.Depositor - } - return nil -} - -func (m *ShareRecord) GetPoolID() string { - if m != nil { - return m.PoolID - } - return "" -} - -func init() { - proto.RegisterType((*Params)(nil), "kava.swap.v1beta1.Params") - proto.RegisterType((*AllowedPool)(nil), "kava.swap.v1beta1.AllowedPool") - proto.RegisterType((*PoolRecord)(nil), "kava.swap.v1beta1.PoolRecord") - proto.RegisterType((*ShareRecord)(nil), "kava.swap.v1beta1.ShareRecord") -} - -func init() { proto.RegisterFile("kava/swap/v1beta1/swap.proto", fileDescriptor_9df359be90eb28cb) } - -var fileDescriptor_9df359be90eb28cb = []byte{ - // 526 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x53, 0x3f, 0x6f, 0xd3, 0x5e, - 0x14, 0x8d, 0xd3, 0x28, 0xf9, 0xe5, 0x25, 0xbf, 0x01, 0x53, 0x89, 0xb4, 0x42, 0x76, 0x15, 0x24, - 0xe8, 0x12, 0xbb, 0x2d, 0x1b, 0x42, 0x48, 0x36, 0x01, 0x91, 0x89, 0xca, 0x0c, 0x08, 0x16, 0xeb, - 0xd9, 0xbe, 0x4d, 0xac, 0x38, 0xbe, 0x96, 0xdf, 0x23, 0xa1, 0xdf, 0x02, 0x31, 0x31, 0x32, 0x33, - 0xf7, 0x13, 0x30, 0x75, 0xac, 0x3a, 0x21, 0x86, 0x80, 0x92, 0x6f, 0x01, 0x0b, 0x7a, 0x7f, 0x68, - 0x8d, 0x10, 0x12, 0x15, 0x93, 0xdf, 0xbd, 0xe7, 0x9d, 0x73, 0xee, 0x3d, 0xd6, 0x23, 0x37, 0xa7, - 0x74, 0x4e, 0x5d, 0xb6, 0xa0, 0x85, 0x3b, 0xdf, 0x8f, 0x80, 0xd3, 0x7d, 0x59, 0x38, 0x45, 0x89, - 0x1c, 0xcd, 0x6b, 0x02, 0x75, 0x64, 0x43, 0xa3, 0xdb, 0x56, 0x8c, 0x6c, 0x86, 0xcc, 0x8d, 0x28, - 0x83, 0x0b, 0x4a, 0x8c, 0x69, 0xae, 0x28, 0xdb, 0x5b, 0x0a, 0x0f, 0x65, 0xe5, 0xaa, 0x42, 0x43, - 0x9b, 0x63, 0x1c, 0xa3, 0xea, 0x8b, 0x93, 0xea, 0xf6, 0x3f, 0x1a, 0xa4, 0x79, 0x48, 0x4b, 0x3a, - 0x63, 0xe6, 0x0b, 0xf2, 0x3f, 0xcd, 0x32, 0x5c, 0x40, 0x12, 0x16, 0x88, 0x19, 0xeb, 0x19, 0x3b, - 0x1b, 0xbb, 0x9d, 0x03, 0xcb, 0xf9, 0x6d, 0x0c, 0xc7, 0x53, 0xf7, 0x0e, 0x11, 0x33, 0x7f, 0xf3, - 0x74, 0x69, 0xd7, 0x3e, 0x7c, 0xb1, 0xbb, 0x95, 0x26, 0x0b, 0xba, 0xb4, 0x52, 0x99, 0xcf, 0xc9, - 0x7f, 0x82, 0x1f, 0x1e, 0x01, 0xf4, 0xea, 0x3b, 0xc6, 0x6e, 0xdb, 0xbf, 0x2f, 0x58, 0x9f, 0x97, - 0xf6, 0xed, 0x71, 0xca, 0x27, 0xaf, 0x22, 0x27, 0xc6, 0x99, 0x1e, 0x57, 0x7f, 0x06, 0x2c, 0x99, - 0xba, 0xfc, 0xb8, 0x00, 0xe6, 0x0c, 0x21, 0x3e, 0x3f, 0x19, 0x10, 0xbd, 0xcd, 0x10, 0xe2, 0xa0, - 0x25, 0xd4, 0x1e, 0x03, 0xdc, 0x6b, 0xbc, 0x7b, 0x6f, 0xd7, 0xfa, 0x8f, 0x48, 0xa7, 0x62, 0x6e, - 0xde, 0x20, 0x2d, 0x8e, 0x53, 0xc8, 0x43, 0xda, 0x33, 0x84, 0x59, 0xd0, 0x94, 0xa5, 0x77, 0x09, - 0x44, 0x6a, 0x0a, 0x0d, 0xf8, 0x5a, 0xe6, 0x6d, 0x9d, 0x10, 0x21, 0x10, 0x40, 0x8c, 0x65, 0x62, - 0xde, 0x22, 0x2d, 0x91, 0x43, 0x98, 0x26, 0x4a, 0xc6, 0x27, 0xab, 0xa5, 0xdd, 0x14, 0x17, 0x46, - 0xc3, 0xa0, 0x29, 0xa0, 0x51, 0x62, 0x3e, 0x20, 0xa4, 0x04, 0x06, 0xe5, 0x1c, 0x58, 0x48, 0xa5, - 0x6a, 0xe7, 0x60, 0xcb, 0xd1, 0xa3, 0x8a, 0xbf, 0x74, 0x91, 0xd9, 0x43, 0x4c, 0x73, 0xbf, 0x21, - 0xd6, 0x0e, 0xda, 0x3f, 0x29, 0xde, 0x2f, 0xfc, 0xa8, 0xb7, 0x71, 0x45, 0xbe, 0x6f, 0x86, 0xa4, - 0xcb, 0x91, 0xd3, 0x2c, 0x64, 0x13, 0x5a, 0x02, 0xeb, 0x35, 0xae, 0x9c, 0xee, 0x28, 0xe7, 0x95, - 0x74, 0x47, 0x39, 0x0f, 0x3a, 0x52, 0xf1, 0x99, 0x14, 0xec, 0x7f, 0x37, 0x48, 0x47, 0x1e, 0x75, - 0x2a, 0x47, 0xa4, 0x9d, 0x40, 0x81, 0x2c, 0xe5, 0x58, 0xca, 0x5c, 0xba, 0xfe, 0x93, 0x6f, 0x4b, - 0x7b, 0xf0, 0x17, 0x4e, 0x5e, 0x1c, 0x7b, 0x49, 0x52, 0x02, 0x63, 0xe7, 0x27, 0x83, 0xeb, 0xda, - 0x50, 0x77, 0xfc, 0x63, 0x0e, 0x2c, 0xb8, 0x94, 0xae, 0xa6, 0x5f, 0xff, 0x63, 0xfa, 0x21, 0xe9, - 0xaa, 0xbd, 0x43, 0x5c, 0xe4, 0x90, 0xc8, 0xfc, 0xfe, 0x79, 0x7b, 0xa5, 0xf8, 0x54, 0x08, 0xfa, - 0xde, 0xe9, 0xca, 0x32, 0xce, 0x56, 0x96, 0xf1, 0x75, 0x65, 0x19, 0x6f, 0xd6, 0x56, 0xed, 0x6c, - 0x6d, 0xd5, 0x3e, 0xad, 0xad, 0xda, 0xcb, 0x3b, 0x15, 0xf1, 0xbd, 0x71, 0x46, 0x23, 0xe6, 0xee, - 0x8d, 0x07, 0xf1, 0x84, 0xa6, 0xb9, 0xfb, 0x5a, 0x3d, 0x69, 0xe9, 0x10, 0x35, 0xe5, 0x43, 0xbb, - 0xfb, 0x23, 0x00, 0x00, 0xff, 0xff, 0xbd, 0xb7, 0x43, 0xe0, 0xec, 0x03, 0x00, 0x00, -} - -func (m *Params) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Params) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.SwapFee.Size() - i -= size - if _, err := m.SwapFee.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintSwap(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.AllowedPools) > 0 { - for iNdEx := len(m.AllowedPools) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.AllowedPools[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintSwap(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *AllowedPool) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AllowedPool) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AllowedPool) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.TokenB) > 0 { - i -= len(m.TokenB) - copy(dAtA[i:], m.TokenB) - i = encodeVarintSwap(dAtA, i, uint64(len(m.TokenB))) - i-- - dAtA[i] = 0x12 - } - if len(m.TokenA) > 0 { - i -= len(m.TokenA) - copy(dAtA[i:], m.TokenA) - i = encodeVarintSwap(dAtA, i, uint64(len(m.TokenA))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *PoolRecord) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PoolRecord) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PoolRecord) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.TotalShares.Size() - i -= size - if _, err := m.TotalShares.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintSwap(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.ReservesB.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintSwap(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.ReservesA.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintSwap(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.PoolID) > 0 { - i -= len(m.PoolID) - copy(dAtA[i:], m.PoolID) - i = encodeVarintSwap(dAtA, i, uint64(len(m.PoolID))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *ShareRecord) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *ShareRecord) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ShareRecord) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.SharesOwned.Size() - i -= size - if _, err := m.SharesOwned.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintSwap(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.PoolID) > 0 { - i -= len(m.PoolID) - copy(dAtA[i:], m.PoolID) - i = encodeVarintSwap(dAtA, i, uint64(len(m.PoolID))) - i-- - dAtA[i] = 0x12 - } - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintSwap(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintSwap(dAtA []byte, offset int, v uint64) int { - offset -= sovSwap(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.AllowedPools) > 0 { - for _, e := range m.AllowedPools { - l = e.Size() - n += 1 + l + sovSwap(uint64(l)) - } - } - l = m.SwapFee.Size() - n += 1 + l + sovSwap(uint64(l)) - return n -} - -func (m *AllowedPool) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.TokenA) - if l > 0 { - n += 1 + l + sovSwap(uint64(l)) - } - l = len(m.TokenB) - if l > 0 { - n += 1 + l + sovSwap(uint64(l)) - } - return n -} - -func (m *PoolRecord) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.PoolID) - if l > 0 { - n += 1 + l + sovSwap(uint64(l)) - } - l = m.ReservesA.Size() - n += 1 + l + sovSwap(uint64(l)) - l = m.ReservesB.Size() - n += 1 + l + sovSwap(uint64(l)) - l = m.TotalShares.Size() - n += 1 + l + sovSwap(uint64(l)) - return n -} - -func (m *ShareRecord) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovSwap(uint64(l)) - } - l = len(m.PoolID) - if l > 0 { - n += 1 + l + sovSwap(uint64(l)) - } - l = m.SharesOwned.Size() - n += 1 + l + sovSwap(uint64(l)) - return n -} - -func sovSwap(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozSwap(x uint64) (n int) { - return sovSwap(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Params) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Params: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AllowedPools", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthSwap - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.AllowedPools = append(m.AllowedPools, AllowedPool{}) - if err := m.AllowedPools[len(m.AllowedPools)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SwapFee", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthSwap - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.SwapFee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipSwap(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthSwap - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *AllowedPool) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AllowedPool: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AllowedPool: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenA", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthSwap - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TokenA = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenB", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthSwap - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TokenB = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipSwap(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthSwap - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *PoolRecord) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PoolRecord: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PoolRecord: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthSwap - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PoolID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ReservesA", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthSwap - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ReservesA.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ReservesB", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthSwap - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ReservesB.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalShares", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthSwap - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TotalShares.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipSwap(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthSwap - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ShareRecord) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ShareRecord: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ShareRecord: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthSwap - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = append(m.Depositor[:0], dAtA[iNdEx:postIndex]...) - if m.Depositor == nil { - m.Depositor = []byte{} - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthSwap - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PoolID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SharesOwned", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSwap - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthSwap - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSwap - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.SharesOwned.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipSwap(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthSwap - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipSwap(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSwap - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSwap - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSwap - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthSwap - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupSwap - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthSwap - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthSwap = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowSwap = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupSwap = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/swap/types/tx.pb.go b/x/swap/types/tx.pb.go deleted file mode 100644 index f20e2072..00000000 --- a/x/swap/types/tx.pb.go +++ /dev/null @@ -1,2205 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: kava/swap/v1beta1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// MsgDeposit represents a message for depositing liquidity into a pool -type MsgDeposit struct { - // depositor represents the address to deposit funds from - Depositor string `protobuf:"bytes,1,opt,name=depositor,proto3" json:"depositor,omitempty"` - // token_a represents one token of deposit pair - TokenA types.Coin `protobuf:"bytes,2,opt,name=token_a,json=tokenA,proto3" json:"token_a"` - // token_b represents one token of deposit pair - TokenB types.Coin `protobuf:"bytes,3,opt,name=token_b,json=tokenB,proto3" json:"token_b"` - // slippage represents the max decimal percentage price change - Slippage github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=slippage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"slippage"` - // deadline represents the unix timestamp to complete the deposit by - Deadline int64 `protobuf:"varint,5,opt,name=deadline,proto3" json:"deadline,omitempty"` -} - -func (m *MsgDeposit) Reset() { *m = MsgDeposit{} } -func (m *MsgDeposit) String() string { return proto.CompactTextString(m) } -func (*MsgDeposit) ProtoMessage() {} -func (*MsgDeposit) Descriptor() ([]byte, []int) { - return fileDescriptor_5b753029ccc8a1ef, []int{0} -} -func (m *MsgDeposit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDeposit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDeposit.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgDeposit) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDeposit.Merge(m, src) -} -func (m *MsgDeposit) XXX_Size() int { - return m.Size() -} -func (m *MsgDeposit) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDeposit.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDeposit proto.InternalMessageInfo - -// MsgDepositResponse defines the Msg/Deposit response type. -type MsgDepositResponse struct { -} - -func (m *MsgDepositResponse) Reset() { *m = MsgDepositResponse{} } -func (m *MsgDepositResponse) String() string { return proto.CompactTextString(m) } -func (*MsgDepositResponse) ProtoMessage() {} -func (*MsgDepositResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5b753029ccc8a1ef, []int{1} -} -func (m *MsgDepositResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDepositResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDepositResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgDepositResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDepositResponse.Merge(m, src) -} -func (m *MsgDepositResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgDepositResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDepositResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDepositResponse proto.InternalMessageInfo - -// MsgWithdraw represents a message for withdrawing liquidity from a pool -type MsgWithdraw struct { - // from represents the address we are withdrawing for - From string `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"` - // shares represents the amount of shares to withdraw - Shares github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,opt,name=shares,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"shares"` - // min_token_a represents the minimum a token to withdraw - MinTokenA types.Coin `protobuf:"bytes,3,opt,name=min_token_a,json=minTokenA,proto3" json:"min_token_a"` - // min_token_a represents the minimum a token to withdraw - MinTokenB types.Coin `protobuf:"bytes,4,opt,name=min_token_b,json=minTokenB,proto3" json:"min_token_b"` - // deadline represents the unix timestamp to complete the withdraw by - Deadline int64 `protobuf:"varint,5,opt,name=deadline,proto3" json:"deadline,omitempty"` -} - -func (m *MsgWithdraw) Reset() { *m = MsgWithdraw{} } -func (m *MsgWithdraw) String() string { return proto.CompactTextString(m) } -func (*MsgWithdraw) ProtoMessage() {} -func (*MsgWithdraw) Descriptor() ([]byte, []int) { - return fileDescriptor_5b753029ccc8a1ef, []int{2} -} -func (m *MsgWithdraw) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdraw) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdraw.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgWithdraw) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdraw.Merge(m, src) -} -func (m *MsgWithdraw) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdraw) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdraw.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdraw proto.InternalMessageInfo - -// MsgWithdrawResponse defines the Msg/Withdraw response type. -type MsgWithdrawResponse struct { -} - -func (m *MsgWithdrawResponse) Reset() { *m = MsgWithdrawResponse{} } -func (m *MsgWithdrawResponse) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawResponse) ProtoMessage() {} -func (*MsgWithdrawResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5b753029ccc8a1ef, []int{3} -} -func (m *MsgWithdrawResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgWithdrawResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawResponse.Merge(m, src) -} -func (m *MsgWithdrawResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawResponse proto.InternalMessageInfo - -// MsgSwapExactForTokens represents a message for trading exact coinA for coinB -type MsgSwapExactForTokens struct { - // represents the address swaping the tokens - Requester string `protobuf:"bytes,1,opt,name=requester,proto3" json:"requester,omitempty"` - // exact_token_a represents the exact amount to swap for token_b - ExactTokenA types.Coin `protobuf:"bytes,2,opt,name=exact_token_a,json=exactTokenA,proto3" json:"exact_token_a"` - // token_b represents the desired token_b to swap for - TokenB types.Coin `protobuf:"bytes,3,opt,name=token_b,json=tokenB,proto3" json:"token_b"` - // slippage represents the maximum change in token_b allowed - Slippage github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=slippage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"slippage"` - // deadline represents the unix timestamp to complete the swap by - Deadline int64 `protobuf:"varint,5,opt,name=deadline,proto3" json:"deadline,omitempty"` -} - -func (m *MsgSwapExactForTokens) Reset() { *m = MsgSwapExactForTokens{} } -func (m *MsgSwapExactForTokens) String() string { return proto.CompactTextString(m) } -func (*MsgSwapExactForTokens) ProtoMessage() {} -func (*MsgSwapExactForTokens) Descriptor() ([]byte, []int) { - return fileDescriptor_5b753029ccc8a1ef, []int{4} -} -func (m *MsgSwapExactForTokens) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSwapExactForTokens) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSwapExactForTokens.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgSwapExactForTokens) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSwapExactForTokens.Merge(m, src) -} -func (m *MsgSwapExactForTokens) XXX_Size() int { - return m.Size() -} -func (m *MsgSwapExactForTokens) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSwapExactForTokens.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSwapExactForTokens proto.InternalMessageInfo - -// MsgSwapExactForTokensResponse defines the Msg/SwapExactForTokens response -// type. -type MsgSwapExactForTokensResponse struct { -} - -func (m *MsgSwapExactForTokensResponse) Reset() { *m = MsgSwapExactForTokensResponse{} } -func (m *MsgSwapExactForTokensResponse) String() string { return proto.CompactTextString(m) } -func (*MsgSwapExactForTokensResponse) ProtoMessage() {} -func (*MsgSwapExactForTokensResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5b753029ccc8a1ef, []int{5} -} -func (m *MsgSwapExactForTokensResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSwapExactForTokensResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSwapExactForTokensResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgSwapExactForTokensResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSwapExactForTokensResponse.Merge(m, src) -} -func (m *MsgSwapExactForTokensResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgSwapExactForTokensResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSwapExactForTokensResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSwapExactForTokensResponse proto.InternalMessageInfo - -// MsgSwapForExactTokens represents a message for trading coinA for an exact -// coinB -type MsgSwapForExactTokens struct { - // represents the address swaping the tokens - Requester string `protobuf:"bytes,1,opt,name=requester,proto3" json:"requester,omitempty"` - // token_a represents the desired token_a to swap for - TokenA types.Coin `protobuf:"bytes,2,opt,name=token_a,json=tokenA,proto3" json:"token_a"` - // exact_token_b represents the exact token b amount to swap for token a - ExactTokenB types.Coin `protobuf:"bytes,3,opt,name=exact_token_b,json=exactTokenB,proto3" json:"exact_token_b"` - // slippage represents the maximum change in token_a allowed - Slippage github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=slippage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"slippage"` - // deadline represents the unix timestamp to complete the swap by - Deadline int64 `protobuf:"varint,5,opt,name=deadline,proto3" json:"deadline,omitempty"` -} - -func (m *MsgSwapForExactTokens) Reset() { *m = MsgSwapForExactTokens{} } -func (m *MsgSwapForExactTokens) String() string { return proto.CompactTextString(m) } -func (*MsgSwapForExactTokens) ProtoMessage() {} -func (*MsgSwapForExactTokens) Descriptor() ([]byte, []int) { - return fileDescriptor_5b753029ccc8a1ef, []int{6} -} -func (m *MsgSwapForExactTokens) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSwapForExactTokens) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSwapForExactTokens.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgSwapForExactTokens) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSwapForExactTokens.Merge(m, src) -} -func (m *MsgSwapForExactTokens) XXX_Size() int { - return m.Size() -} -func (m *MsgSwapForExactTokens) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSwapForExactTokens.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSwapForExactTokens proto.InternalMessageInfo - -// MsgSwapForExactTokensResponse defines the Msg/SwapForExactTokensResponse -// response type. -type MsgSwapForExactTokensResponse struct { -} - -func (m *MsgSwapForExactTokensResponse) Reset() { *m = MsgSwapForExactTokensResponse{} } -func (m *MsgSwapForExactTokensResponse) String() string { return proto.CompactTextString(m) } -func (*MsgSwapForExactTokensResponse) ProtoMessage() {} -func (*MsgSwapForExactTokensResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5b753029ccc8a1ef, []int{7} -} -func (m *MsgSwapForExactTokensResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSwapForExactTokensResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSwapForExactTokensResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgSwapForExactTokensResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSwapForExactTokensResponse.Merge(m, src) -} -func (m *MsgSwapForExactTokensResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgSwapForExactTokensResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSwapForExactTokensResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSwapForExactTokensResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgDeposit)(nil), "kava.swap.v1beta1.MsgDeposit") - proto.RegisterType((*MsgDepositResponse)(nil), "kava.swap.v1beta1.MsgDepositResponse") - proto.RegisterType((*MsgWithdraw)(nil), "kava.swap.v1beta1.MsgWithdraw") - proto.RegisterType((*MsgWithdrawResponse)(nil), "kava.swap.v1beta1.MsgWithdrawResponse") - proto.RegisterType((*MsgSwapExactForTokens)(nil), "kava.swap.v1beta1.MsgSwapExactForTokens") - proto.RegisterType((*MsgSwapExactForTokensResponse)(nil), "kava.swap.v1beta1.MsgSwapExactForTokensResponse") - proto.RegisterType((*MsgSwapForExactTokens)(nil), "kava.swap.v1beta1.MsgSwapForExactTokens") - proto.RegisterType((*MsgSwapForExactTokensResponse)(nil), "kava.swap.v1beta1.MsgSwapForExactTokensResponse") -} - -func init() { proto.RegisterFile("kava/swap/v1beta1/tx.proto", fileDescriptor_5b753029ccc8a1ef) } - -var fileDescriptor_5b753029ccc8a1ef = []byte{ - // 617 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x95, 0x4d, 0x8f, 0xd2, 0x40, - 0x18, 0xc7, 0x29, 0x20, 0x0b, 0x43, 0x3c, 0x38, 0xb2, 0x49, 0xb7, 0xc9, 0x16, 0x42, 0xe2, 0xca, - 0x41, 0x5a, 0x76, 0x4d, 0x8c, 0x31, 0x26, 0x86, 0x2e, 0x4b, 0xe2, 0x81, 0x98, 0x74, 0x37, 0xd1, - 0x78, 0x21, 0xd3, 0x76, 0x2c, 0x0d, 0xd0, 0xa9, 0x9d, 0xd9, 0x05, 0xbf, 0x81, 0x27, 0xe3, 0x47, - 0xf0, 0xe6, 0x17, 0xe0, 0x43, 0x6c, 0x3c, 0x6d, 0xf6, 0x64, 0x3c, 0x6c, 0x0c, 0x7c, 0x11, 0xd3, - 0x57, 0x5e, 0xb6, 0x41, 0xd8, 0x93, 0x9e, 0xe8, 0xf4, 0xff, 0xfc, 0x9f, 0x99, 0xfe, 0x9e, 0x87, - 0x67, 0x80, 0xd0, 0x47, 0x17, 0x48, 0xa6, 0x23, 0xe4, 0xc8, 0x17, 0x87, 0x1a, 0x66, 0xe8, 0x50, - 0x66, 0x63, 0xc9, 0x71, 0x09, 0x23, 0xf0, 0x81, 0xa7, 0x49, 0x9e, 0x26, 0x85, 0x9a, 0x20, 0xea, - 0x84, 0x0e, 0x09, 0x95, 0x35, 0x44, 0x71, 0x6c, 0xd0, 0x89, 0x65, 0x07, 0x16, 0x61, 0x2f, 0xd0, - 0xbb, 0xfe, 0x4a, 0x0e, 0x16, 0xa1, 0x54, 0x32, 0x89, 0x49, 0x82, 0xf7, 0xde, 0x53, 0xf0, 0xb6, - 0x3a, 0x49, 0x03, 0xd0, 0xa1, 0x66, 0x0b, 0x3b, 0x84, 0x5a, 0x0c, 0x3e, 0x03, 0x05, 0x23, 0x78, - 0x24, 0x2e, 0xcf, 0x55, 0xb8, 0x5a, 0x41, 0xe1, 0xaf, 0x27, 0xf5, 0x52, 0x98, 0xa9, 0x69, 0x18, - 0x2e, 0xa6, 0xf4, 0x94, 0xb9, 0x96, 0x6d, 0xaa, 0xf3, 0x50, 0xf8, 0x1c, 0xec, 0x30, 0xd2, 0xc7, - 0x76, 0x17, 0xf1, 0xe9, 0x0a, 0x57, 0x2b, 0x1e, 0xed, 0x49, 0xa1, 0xc5, 0x3b, 0x69, 0x74, 0x7c, - 0xe9, 0x98, 0x58, 0xb6, 0x92, 0xbd, 0xbc, 0x29, 0xa7, 0xd4, 0x9c, 0x1f, 0xdf, 0x9c, 0x3b, 0x35, - 0x3e, 0xb3, 0x8d, 0x53, 0x81, 0xef, 0x40, 0x9e, 0x0e, 0x2c, 0xc7, 0x41, 0x26, 0xe6, 0xb3, 0xfe, - 0x51, 0x5f, 0x7a, 0xfa, 0xaf, 0x9b, 0xf2, 0x81, 0x69, 0xb1, 0xde, 0xb9, 0x26, 0xe9, 0x64, 0x18, - 0x32, 0x08, 0x7f, 0xea, 0xd4, 0xe8, 0xcb, 0xec, 0x93, 0x83, 0xa9, 0xd4, 0xc2, 0xfa, 0xf5, 0xa4, - 0x0e, 0xc2, 0xbd, 0x5a, 0x58, 0x57, 0xe3, 0x6c, 0x50, 0x00, 0x79, 0x03, 0x23, 0x63, 0x60, 0xd9, - 0x98, 0xbf, 0x57, 0xe1, 0x6a, 0x19, 0x35, 0x5e, 0xbf, 0xc8, 0x7e, 0xfe, 0x56, 0x4e, 0x55, 0x4b, - 0x00, 0xce, 0xa9, 0xa9, 0x98, 0x3a, 0xc4, 0xa6, 0xb8, 0xfa, 0x3d, 0x0d, 0x8a, 0x1d, 0x6a, 0xbe, - 0xb5, 0x58, 0xcf, 0x70, 0xd1, 0x08, 0x3e, 0x01, 0xd9, 0x0f, 0x2e, 0x19, 0xfe, 0x15, 0xa4, 0x1f, - 0x05, 0xdb, 0x20, 0x47, 0x7b, 0xc8, 0xc5, 0xd4, 0x47, 0x58, 0x50, 0xa4, 0x2d, 0xbe, 0xe6, 0xb5, - 0xcd, 0xd4, 0xd0, 0x0d, 0x5f, 0x81, 0xe2, 0xd0, 0xb2, 0xbb, 0x51, 0x3d, 0x36, 0xa4, 0x5a, 0x18, - 0x5a, 0xf6, 0x59, 0x50, 0x92, 0xa5, 0x04, 0x9a, 0xcf, 0x76, 0x9b, 0x04, 0xca, 0x06, 0xfc, 0x76, - 0xc1, 0xc3, 0x05, 0x50, 0x31, 0xc0, 0x1f, 0x69, 0xb0, 0xdb, 0xa1, 0xe6, 0xe9, 0x08, 0x39, 0x27, - 0x63, 0xa4, 0xb3, 0x36, 0x71, 0xfd, 0x94, 0xd4, 0x6b, 0x4c, 0x17, 0x7f, 0x3c, 0xc7, 0x94, 0xe1, - 0x0d, 0x1a, 0x33, 0x0e, 0x85, 0xc7, 0xe0, 0x3e, 0xf6, 0x32, 0x75, 0xb7, 0x6c, 0xcf, 0xa2, 0xef, - 0x3a, 0xfb, 0x9f, 0x7b, 0xb4, 0x0c, 0xf6, 0x13, 0x59, 0x26, 0xd1, 0x6e, 0x13, 0xf7, 0x24, 0xfe, - 0xe0, 0xbb, 0xd3, 0xbe, 0xfb, 0x18, 0x58, 0xa9, 0xd3, 0xc6, 0xa0, 0x17, 0xea, 0xf4, 0xaf, 0xd0, - 0x5e, 0x66, 0x19, 0xd1, 0x3e, 0xfa, 0x92, 0x01, 0x99, 0x0e, 0x35, 0xe1, 0x1b, 0xb0, 0x13, 0x4d, - 0xdb, 0x7d, 0xe9, 0xd6, 0x84, 0x97, 0xe6, 0x63, 0x45, 0x78, 0xb4, 0x56, 0x8e, 0x12, 0x43, 0x15, - 0xe4, 0xe3, 0x89, 0x23, 0x26, 0x5b, 0x22, 0x5d, 0x38, 0x58, 0xaf, 0xc7, 0x39, 0x1d, 0x00, 0x13, - 0xfe, 0x84, 0xb5, 0x64, 0xf7, 0xed, 0x48, 0xa1, 0xb1, 0x69, 0xe4, 0xea, 0x8e, 0x2b, 0x8d, 0xb8, - 0x66, 0xc7, 0xe5, 0xc8, 0x75, 0x3b, 0x26, 0x17, 0x44, 0x69, 0x5e, 0x4e, 0x45, 0xee, 0x6a, 0x2a, - 0x72, 0xbf, 0xa7, 0x22, 0xf7, 0x75, 0x26, 0xa6, 0xae, 0x66, 0x62, 0xea, 0xe7, 0x4c, 0x4c, 0xbd, - 0x7f, 0xbc, 0xd0, 0x2d, 0x0d, 0x73, 0x80, 0x34, 0x2a, 0x37, 0xcc, 0xba, 0xde, 0x43, 0x96, 0x2d, - 0x8f, 0x83, 0xcb, 0xda, 0x6f, 0x19, 0x2d, 0xe7, 0x5f, 0xa2, 0x4f, 0xff, 0x04, 0x00, 0x00, 0xff, - 0xff, 0x82, 0x53, 0x5e, 0x21, 0xc6, 0x07, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - // Deposit defines a method for depositing liquidity into a pool - Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) - // Withdraw defines a method for withdrawing liquidity into a pool - Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) - // SwapExactForTokens represents a message for trading exact coinA for coinB - SwapExactForTokens(ctx context.Context, in *MsgSwapExactForTokens, opts ...grpc.CallOption) (*MsgSwapExactForTokensResponse, error) - // SwapForExactTokens represents a message for trading coinA for an exact coinB - SwapForExactTokens(ctx context.Context, in *MsgSwapForExactTokens, opts ...grpc.CallOption) (*MsgSwapForExactTokensResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Deposit(ctx context.Context, in *MsgDeposit, opts ...grpc.CallOption) (*MsgDepositResponse, error) { - out := new(MsgDepositResponse) - err := c.cc.Invoke(ctx, "/kava.swap.v1beta1.Msg/Deposit", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) { - out := new(MsgWithdrawResponse) - err := c.cc.Invoke(ctx, "/kava.swap.v1beta1.Msg/Withdraw", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) SwapExactForTokens(ctx context.Context, in *MsgSwapExactForTokens, opts ...grpc.CallOption) (*MsgSwapExactForTokensResponse, error) { - out := new(MsgSwapExactForTokensResponse) - err := c.cc.Invoke(ctx, "/kava.swap.v1beta1.Msg/SwapExactForTokens", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) SwapForExactTokens(ctx context.Context, in *MsgSwapForExactTokens, opts ...grpc.CallOption) (*MsgSwapForExactTokensResponse, error) { - out := new(MsgSwapForExactTokensResponse) - err := c.cc.Invoke(ctx, "/kava.swap.v1beta1.Msg/SwapForExactTokens", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // Deposit defines a method for depositing liquidity into a pool - Deposit(context.Context, *MsgDeposit) (*MsgDepositResponse, error) - // Withdraw defines a method for withdrawing liquidity into a pool - Withdraw(context.Context, *MsgWithdraw) (*MsgWithdrawResponse, error) - // SwapExactForTokens represents a message for trading exact coinA for coinB - SwapExactForTokens(context.Context, *MsgSwapExactForTokens) (*MsgSwapExactForTokensResponse, error) - // SwapForExactTokens represents a message for trading coinA for an exact coinB - SwapForExactTokens(context.Context, *MsgSwapForExactTokens) (*MsgSwapForExactTokensResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Deposit(ctx context.Context, req *MsgDeposit) (*MsgDepositResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deposit not implemented") -} -func (*UnimplementedMsgServer) Withdraw(ctx context.Context, req *MsgWithdraw) (*MsgWithdrawResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Withdraw not implemented") -} -func (*UnimplementedMsgServer) SwapExactForTokens(ctx context.Context, req *MsgSwapExactForTokens) (*MsgSwapExactForTokensResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SwapExactForTokens not implemented") -} -func (*UnimplementedMsgServer) SwapForExactTokens(ctx context.Context, req *MsgSwapForExactTokens) (*MsgSwapForExactTokensResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SwapForExactTokens not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Deposit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgDeposit) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Deposit(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.swap.v1beta1.Msg/Deposit", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Deposit(ctx, req.(*MsgDeposit)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_Withdraw_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgWithdraw) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Withdraw(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.swap.v1beta1.Msg/Withdraw", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Withdraw(ctx, req.(*MsgWithdraw)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_SwapExactForTokens_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgSwapExactForTokens) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).SwapExactForTokens(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.swap.v1beta1.Msg/SwapExactForTokens", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).SwapExactForTokens(ctx, req.(*MsgSwapExactForTokens)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_SwapForExactTokens_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgSwapForExactTokens) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).SwapForExactTokens(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/kava.swap.v1beta1.Msg/SwapForExactTokens", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).SwapForExactTokens(ctx, req.(*MsgSwapForExactTokens)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "kava.swap.v1beta1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Deposit", - Handler: _Msg_Deposit_Handler, - }, - { - MethodName: "Withdraw", - Handler: _Msg_Withdraw_Handler, - }, - { - MethodName: "SwapExactForTokens", - Handler: _Msg_SwapExactForTokens_Handler, - }, - { - MethodName: "SwapForExactTokens", - Handler: _Msg_SwapForExactTokens_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "kava/swap/v1beta1/tx.proto", -} - -func (m *MsgDeposit) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgDeposit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDeposit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Deadline != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Deadline)) - i-- - dAtA[i] = 0x28 - } - { - size := m.Slippage.Size() - i -= size - if _, err := m.Slippage.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.TokenB.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.TokenA.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Depositor) > 0 { - i -= len(m.Depositor) - copy(dAtA[i:], m.Depositor) - i = encodeVarintTx(dAtA, i, uint64(len(m.Depositor))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgDepositResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgDepositResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDepositResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgWithdraw) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgWithdraw) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdraw) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Deadline != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Deadline)) - i-- - dAtA[i] = 0x28 - } - { - size, err := m.MinTokenB.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.MinTokenA.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.Shares.Size() - i -= size - if _, err := m.Shares.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.From) > 0 { - i -= len(m.From) - copy(dAtA[i:], m.From) - i = encodeVarintTx(dAtA, i, uint64(len(m.From))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgWithdrawResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgSwapExactForTokens) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgSwapExactForTokens) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSwapExactForTokens) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Deadline != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Deadline)) - i-- - dAtA[i] = 0x28 - } - { - size := m.Slippage.Size() - i -= size - if _, err := m.Slippage.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.TokenB.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.ExactTokenA.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Requester) > 0 { - i -= len(m.Requester) - copy(dAtA[i:], m.Requester) - i = encodeVarintTx(dAtA, i, uint64(len(m.Requester))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgSwapExactForTokensResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgSwapExactForTokensResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSwapExactForTokensResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgSwapForExactTokens) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgSwapForExactTokens) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSwapForExactTokens) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Deadline != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Deadline)) - i-- - dAtA[i] = 0x28 - } - { - size := m.Slippage.Size() - i -= size - if _, err := m.Slippage.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.ExactTokenB.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.TokenA.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Requester) > 0 { - i -= len(m.Requester) - copy(dAtA[i:], m.Requester) - i = encodeVarintTx(dAtA, i, uint64(len(m.Requester))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgSwapForExactTokensResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgSwapForExactTokensResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSwapForExactTokensResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgDeposit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Depositor) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.TokenA.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.TokenB.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.Slippage.Size() - n += 1 + l + sovTx(uint64(l)) - if m.Deadline != 0 { - n += 1 + sovTx(uint64(m.Deadline)) - } - return n -} - -func (m *MsgDepositResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgWithdraw) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.From) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Shares.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.MinTokenA.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.MinTokenB.Size() - n += 1 + l + sovTx(uint64(l)) - if m.Deadline != 0 { - n += 1 + sovTx(uint64(m.Deadline)) - } - return n -} - -func (m *MsgWithdrawResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgSwapExactForTokens) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Requester) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.ExactTokenA.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.TokenB.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.Slippage.Size() - n += 1 + l + sovTx(uint64(l)) - if m.Deadline != 0 { - n += 1 + sovTx(uint64(m.Deadline)) - } - return n -} - -func (m *MsgSwapExactForTokensResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgSwapForExactTokens) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Requester) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.TokenA.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.ExactTokenB.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.Slippage.Size() - n += 1 + l + sovTx(uint64(l)) - if m.Deadline != 0 { - n += 1 + sovTx(uint64(m.Deadline)) - } - return n -} - -func (m *MsgSwapForExactTokensResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgDeposit) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDeposit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDeposit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Depositor", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Depositor = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenA", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TokenA.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenB", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TokenB.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Slippage", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Slippage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Deadline", wireType) - } - m.Deadline = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Deadline |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDepositResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDepositResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDepositResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdraw) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdraw: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdraw: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.From = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Shares", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Shares.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MinTokenA", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MinTokenA.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MinTokenB", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MinTokenB.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Deadline", wireType) - } - m.Deadline = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Deadline |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgSwapExactForTokens) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgSwapExactForTokens: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSwapExactForTokens: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Requester", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Requester = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ExactTokenA", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ExactTokenA.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenB", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TokenB.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Slippage", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Slippage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Deadline", wireType) - } - m.Deadline = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Deadline |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgSwapExactForTokensResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgSwapExactForTokensResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSwapExactForTokensResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgSwapForExactTokens) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgSwapForExactTokens: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSwapForExactTokens: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Requester", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Requester = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenA", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TokenA.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ExactTokenB", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ExactTokenB.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Slippage", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Slippage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Deadline", wireType) - } - m.Deadline = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Deadline |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgSwapForExactTokensResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgSwapForExactTokensResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSwapForExactTokensResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -)