From fbbf447b362361f9655923d936c9abb27c99d30e Mon Sep 17 00:00:00 2001 From: forcodedancing Date: Tue, 8 Aug 2023 16:08:09 +0800 Subject: [PATCH 01/13] chore: payment refactor to use global store prices for billing --- app/app.go | 3 - e2e/tests/payment_test.go | 70 ++-- e2e/tests/sp_test.go | 61 ++-- e2e/tests/storage_bill_test.go | 135 +++---- proto/greenfield/sp/events.proto | 18 +- proto/greenfield/sp/query.proto | 24 +- proto/greenfield/sp/types.proto | 20 +- x/payment/keeper/keeper.go | 3 - x/payment/keeper/keeper_test.go | 4 - x/payment/keeper/msg_server_test.go | 4 - x/payment/keeper/price.go | 26 -- x/payment/keeper/price_test.go | 39 -- x/payment/types/expected_keepers.go | 8 - x/payment/types/expected_keepers_mocks.go | 90 +---- x/payment/types/price.go | 11 - x/sp/keeper/grpc_query.go | 20 +- x/sp/keeper/msg_server.go | 4 +- x/sp/keeper/sp_storage_price.go | 121 +++---- x/sp/keeper/sp_storage_price_test.go | 69 ++-- x/sp/types/events.pb.go | 259 ++++++++----- x/sp/types/keys.go | 24 +- x/sp/types/query.pb.go | 419 ++++++++++------------ x/sp/types/query.pb.gw.go | 78 ++-- x/sp/types/types.pb.go | 284 ++++++++++----- x/storage/keeper/keeper_object_test.go | 2 +- x/storage/keeper/payment.go | 44 +-- x/storage/keeper/payment_test.go | 12 +- x/storage/types/expected_keepers.go | 2 +- x/storage/types/expected_keepers_mocks.go | 30 +- 29 files changed, 896 insertions(+), 988 deletions(-) delete mode 100644 x/payment/keeper/price.go delete mode 100644 x/payment/keeper/price_test.go diff --git a/app/app.go b/app/app.go index 813de0583..ad3b6d2b4 100644 --- a/app/app.go +++ b/app/app.go @@ -455,11 +455,8 @@ func New( app.PaymentKeeper = *paymentmodulekeeper.NewKeeper( appCodec, keys[paymentmoduletypes.StoreKey], - app.BankKeeper, app.AccountKeeper, - app.SpKeeper, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) paymentModule := paymentmodule.NewAppModule(appCodec, app.PaymentKeeper, app.AccountKeeper, app.BankKeeper) diff --git a/e2e/tests/payment_test.go b/e2e/tests/payment_test.go index ea0c8ab30..16b5774eb 100644 --- a/e2e/tests/payment_test.go +++ b/e2e/tests/payment_test.go @@ -302,14 +302,14 @@ func (s *PaymentTestSuite) TestDeposit_ActiveAccount() { params := s.queryParams() reserveTime := params.VersionedParams.ReserveTime - queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, }) s.T().Logf("queryGetSpStoragePriceByTimeResp %s, err: %v", queryGetSpStoragePriceByTimeResp, err) s.Require().NoError(err) bucketChargedReadQuota := uint64(1000) - readPrice := queryGetSpStoragePriceByTimeResp.SpStoragePrice.ReadPrice + readPrice := queryGetSpStoragePriceByTimeResp.GlobalSpStorePrice.ReadPrice totalUserRate := readPrice.MulInt(sdkmath.NewIntFromUint64(bucketChargedReadQuota)).TruncateInt() taxRateParam := params.VersionedParams.ValidatorTaxRate taxStreamRate := taxRateParam.MulInt(totalUserRate).TruncateInt() @@ -388,14 +388,14 @@ func (s *PaymentTestSuite) TestDeposit_ResumeInOneBlock() { params := s.queryParams() reserveTime := params.VersionedParams.ReserveTime - queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, }) s.T().Logf("queryGetSpStoragePriceByTimeResp %s, err: %v", queryGetSpStoragePriceByTimeResp, err) s.Require().NoError(err) bucketChargedReadQuota := uint64(1000) - readPrice := queryGetSpStoragePriceByTimeResp.SpStoragePrice.ReadPrice + readPrice := queryGetSpStoragePriceByTimeResp.GlobalSpStorePrice.ReadPrice totalUserRate := readPrice.MulInt(sdkmath.NewIntFromUint64(bucketChargedReadQuota)).TruncateInt() taxRateParam := params.VersionedParams.ValidatorTaxRate taxStreamRate := taxRateParam.MulInt(totalUserRate).TruncateInt() @@ -505,14 +505,14 @@ func (s *PaymentTestSuite) TestDeposit_ResumeInBlocks() { userAddr := user.GetAddr().String() reserveTime := params.VersionedParams.ReserveTime - queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, }) s.T().Logf("queryGetSpStoragePriceByTimeResp %s, err: %v", queryGetSpStoragePriceByTimeResp, err) s.Require().NoError(err) bucketChargedReadQuota := uint64(1000) - readPrice := queryGetSpStoragePriceByTimeResp.SpStoragePrice.ReadPrice + readPrice := queryGetSpStoragePriceByTimeResp.GlobalSpStorePrice.ReadPrice totalUserRate := readPrice.MulInt(sdkmath.NewIntFromUint64(bucketChargedReadQuota)).TruncateInt() taxRateParam := params.VersionedParams.ValidatorTaxRate taxStreamRate := taxRateParam.MulInt(totalUserRate).TruncateInt() @@ -642,12 +642,13 @@ func (s *PaymentTestSuite) TestAutoSettle_InOneBlock() { bucketChargedReadQuota := uint64(1000) params := s.queryParams() reserveTime := params.VersionedParams.ReserveTime - queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, }) s.T().Logf("queryGetSpStoragePriceByTimeResp %s, err: %v", queryGetSpStoragePriceByTimeResp, err) s.Require().NoError(err) - readPrice := queryGetSpStoragePriceByTimeResp.SpStoragePrice.ReadPrice + + readPrice := queryGetSpStoragePriceByTimeResp.GlobalSpStorePrice.ReadPrice totalUserRate := readPrice.MulInt(sdkmath.NewIntFromUint64(bucketChargedReadQuota)).TruncateInt() taxRateParam := params.VersionedParams.ValidatorTaxRate taxStreamRate := taxRateParam.MulInt(totalUserRate).TruncateInt() @@ -779,14 +780,14 @@ func (s *PaymentTestSuite) TestAutoSettle_InBlocks() { userAddr := user.GetAddr().String() reserveTime := params.VersionedParams.ReserveTime - queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, }) s.T().Logf("queryGetSpStoragePriceByTimeResp %s, err: %v", queryGetSpStoragePriceByTimeResp, err) s.Require().NoError(err) bucketChargedReadQuota := uint64(1000) - readPrice := queryGetSpStoragePriceByTimeResp.SpStoragePrice.ReadPrice + readPrice := queryGetSpStoragePriceByTimeResp.GlobalSpStorePrice.ReadPrice totalUserRate := readPrice.MulInt(sdkmath.NewIntFromUint64(bucketChargedReadQuota)).TruncateInt() taxRateParam := params.VersionedParams.ValidatorTaxRate taxStreamRate := taxRateParam.MulInt(totalUserRate).TruncateInt() @@ -875,14 +876,14 @@ func (s *PaymentTestSuite) TestWithdraw() { params := s.queryParams() reserveTime := params.VersionedParams.ReserveTime - queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, }) s.T().Logf("queryGetSpStoragePriceByTimeResp %s, err: %v", queryGetSpStoragePriceByTimeResp, err) s.Require().NoError(err) bucketChargedReadQuota := uint64(100000) - readPrice := queryGetSpStoragePriceByTimeResp.SpStoragePrice.ReadPrice + readPrice := queryGetSpStoragePriceByTimeResp.GlobalSpStorePrice.ReadPrice totalUserRate := readPrice.MulInt(sdkmath.NewIntFromUint64(bucketChargedReadQuota)).TruncateInt() taxRateParam := params.VersionedParams.ValidatorTaxRate taxStreamRate := taxRateParam.MulInt(totalUserRate).TruncateInt() @@ -1218,9 +1219,8 @@ func (s *PaymentTestSuite) TestDiscontinue_InOneBlock_WithPriceChange() { streamRecordsBefore := s.getStreamRecords(streamAddresses) // query storage price - priceRes, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - Timestamp: 0, + priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorKey.GetAddr().String(), }) s.Require().NoError(err) s.T().Log("price", priceRes.SpStoragePrice) @@ -1421,9 +1421,8 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChange() { streamRecordsBefore := s.getStreamRecords(streamAddresses) // query storage price - priceRes, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - Timestamp: 0, + priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorKey.GetAddr().String(), }) s.Require().NoError(err) s.T().Log("price", priceRes.SpStoragePrice) @@ -1559,9 +1558,8 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChangeReserveTimeCh streamRecordsBefore := s.getStreamRecords(streamAddresses) // query storage price - priceRes, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - Timestamp: 0, + priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorKey.GetAddr().String(), }) s.Require().NoError(err) s.T().Log("price", priceRes.SpStoragePrice) @@ -1711,9 +1709,8 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChangeReserveTimeCh streamRecordsBefore := s.getStreamRecords(streamAddresses) // query storage price - priceRes, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - Timestamp: 0, + priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorKey.GetAddr().String(), }) s.Require().NoError(err) s.T().Log("price", priceRes.SpStoragePrice) @@ -2173,21 +2170,14 @@ func (s *PaymentTestSuite) calculateLockFee(sp *core.StorageProvider, bucketName func (s *PaymentTestSuite) getPrices(sp *core.StorageProvider, timestamp int64) (sdk.Dec, sdk.Dec, sdk.Dec) { ctx := context.Background() - spStoragePriceByTimeResp, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - Timestamp: timestamp, - }) - s.T().Logf("spStoragePriceByTimeResp %s, err: %v", spStoragePriceByTimeResp, err) - s.Require().NoError(err) - - secondaryStoragePriceByTimeResp, err := s.Client.QueryGetSecondarySpStorePriceByTime(ctx, &sptypes.QueryGetSecondarySpStorePriceByTimeRequest{ + spStoragePriceByTimeResp, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ Timestamp: timestamp, }) s.T().Logf("spStoragePriceByTimeResp %s, err: %v", spStoragePriceByTimeResp, err) s.Require().NoError(err) - return spStoragePriceByTimeResp.SpStoragePrice.ReadPrice, spStoragePriceByTimeResp.SpStoragePrice.StorePrice, - secondaryStoragePriceByTimeResp.SecondarySpStorePrice.StorePrice + return spStoragePriceByTimeResp.GlobalSpStorePrice.ReadPrice, spStoragePriceByTimeResp.GlobalSpStorePrice.PrimaryStorePrice, + spStoragePriceByTimeResp.GlobalSpStorePrice.SecondaryStorePrice } func (s *PaymentTestSuite) calculateReadRates(sp *core.StorageProvider, bucketName string) (sdkmath.Int, sdkmath.Int, sdkmath.Int) { diff --git a/e2e/tests/sp_test.go b/e2e/tests/sp_test.go index 1e365bce7..da1c20b80 100644 --- a/e2e/tests/sp_test.go +++ b/e2e/tests/sp_test.go @@ -157,12 +157,11 @@ func (s *StorageProviderTestSuite) TestDeposit() { func (s *StorageProviderTestSuite) TestSpStoragePrice() { ctx := context.Background() - s.CheckSecondarySpPrice() + s.CheckGlobalSpStorePrice() sp := s.BaseSuite.PickStorageProvider() spAddr := sp.OperatorKey.GetAddr().String() - spStoragePrice, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: spAddr, - Timestamp: 0, + spStoragePrice, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: spAddr, }) s.Require().NoError(err) s.T().Log(spStoragePrice) @@ -177,62 +176,68 @@ func (s *StorageProviderTestSuite) TestSpStoragePrice() { } _ = s.SendTxBlock(sp.OperatorKey, msgUpdateSpStoragePrice) // query and assert - spStoragePrice2, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: spAddr, - Timestamp: 0, + spStoragePrice2, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: spAddr, }) s.Require().NoError(err) s.T().Log(spStoragePrice2) // check price changed as expected s.Require().Equal(newReadPrice, spStoragePrice2.SpStoragePrice.ReadPrice) s.Require().Equal(newStorePrice, spStoragePrice2.SpStoragePrice.StorePrice) - s.CheckSecondarySpPrice() + s.CheckGlobalSpStorePrice() // query sp storage price by time before it exists, expect error - _, err = s.Client.QueryGetSecondarySpStorePriceByTime(ctx, &sptypes.QueryGetSecondarySpStorePriceByTimeRequest{ - Timestamp: 1, - }) - s.Require().Error(err) - _, err = s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: spAddr, + _, err = s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ Timestamp: 1, }) s.Require().Error(err) } -func (s *StorageProviderTestSuite) CheckSecondarySpPrice() { +func (s *StorageProviderTestSuite) CheckGlobalSpStorePrice() { ctx := context.Background() - queryGetSecondarySpStorePriceByTimeResp, err := s.Client.QueryGetSecondarySpStorePriceByTime(ctx, &sptypes.QueryGetSecondarySpStorePriceByTimeRequest{ + queryGlobalSpStorePriceByTimeResp, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ Timestamp: 0, }) s.Require().NoError(err) - s.T().Logf("Secondary SP store price: %s", core.YamlString(queryGetSecondarySpStorePriceByTimeResp.SecondarySpStorePrice)) + s.T().Logf("global SP store price: %s", core.YamlString(queryGlobalSpStorePriceByTimeResp.GlobalSpStorePrice)) // query all sps sps, err := s.Client.StorageProviders(ctx, &sptypes.QueryStorageProvidersRequest{}) s.Require().NoError(err) s.T().Logf("sps: %s", sps) spNum := int64(sps.Pagination.Total) - prices := make([]sdk.Dec, 0) + storePrices := make([]sdk.Dec, 0) + readPrices := make([]sdk.Dec, 0) for _, sp := range sps.Sps { - spStoragePrice, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorAddress, - Timestamp: 0, + spStoragePrice, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorAddress, }) s.Require().NoError(err) s.T().Logf("sp: %s, storage price: %s", sp.OperatorAddress, core.YamlString(spStoragePrice.SpStoragePrice)) - prices = append(prices, spStoragePrice.SpStoragePrice.StorePrice) + storePrices = append(storePrices, spStoragePrice.SpStoragePrice.StorePrice) + readPrices = append(readPrices, spStoragePrice.SpStoragePrice.ReadPrice) } - sort.Slice(prices, func(i, j int) bool { return prices[i].LT(prices[j]) }) - var median sdk.Dec + + sort.Slice(storePrices, func(i, j int) bool { return storePrices[i].LT(storePrices[j]) }) + var storeMedian sdk.Dec + if spNum%2 == 0 { + storeMedian = storePrices[spNum/2-1].Add(storePrices[spNum/2]).QuoInt64(2) + } else { + storeMedian = storePrices[spNum/2] + } + + sort.Slice(readPrices, func(i, j int) bool { return readPrices[i].LT(readPrices[j]) }) + var readMedian sdk.Dec if spNum%2 == 0 { - median = prices[spNum/2-1].Add(prices[spNum/2]).QuoInt64(2) + readMedian = readPrices[spNum/2-1].Add(readPrices[spNum/2]).QuoInt64(2) } else { - median = prices[spNum/2] + readMedian = readPrices[spNum/2] } + s.Require().Equal(storeMedian, queryGlobalSpStorePriceByTimeResp.GlobalSpStorePrice.PrimaryStorePrice) params, err := s.Client.SpQueryClient.Params(ctx, &sptypes.QueryParamsRequest{}) s.Require().NoError(err) - expectedSecondarySpStorePrice := params.Params.SecondarySpStorePriceRatio.Mul(median) - s.Require().Equal(expectedSecondarySpStorePrice, queryGetSecondarySpStorePriceByTimeResp.SecondarySpStorePrice.StorePrice) + expectedSecondarySpStorePrice := params.Params.SecondarySpStorePriceRatio.Mul(storeMedian) + s.Require().Equal(expectedSecondarySpStorePrice, queryGlobalSpStorePriceByTimeResp.GlobalSpStorePrice.SecondaryStorePrice) + s.Require().Equal(readMedian, queryGlobalSpStorePriceByTimeResp.GlobalSpStorePrice.ReadPrice) } func TestStorageProviderTestSuite(t *testing.T) { diff --git a/e2e/tests/storage_bill_test.go b/e2e/tests/storage_bill_test.go index 031556e14..6d5d5fabc 100644 --- a/e2e/tests/storage_bill_test.go +++ b/e2e/tests/storage_bill_test.go @@ -123,14 +123,13 @@ func (s *PaymentTestSuite) TestStorageBill_Smoke() { queryHeadBucketResponse, err := s.Client.HeadBucket(ctx, &queryHeadBucketRequest) s.Require().NoError(err) - queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ Timestamp: queryHeadBucketResponse.BucketInfo.CreateAt, }) s.T().Logf("queryGetSpStoragePriceByTimeResp %s, err: %v", queryGetSpStoragePriceByTimeResp, err) s.Require().NoError(err) - readPrice := queryGetSpStoragePriceByTimeResp.SpStoragePrice.ReadPrice + readPrice := queryGetSpStoragePriceByTimeResp.GlobalSpStorePrice.ReadPrice readChargeRate := readPrice.MulInt(sdk.NewIntFromUint64(queryHeadBucketResponse.BucketInfo.ChargedReadQuota)).TruncateInt() s.T().Logf("readPrice: %s, readChargeRate: %s", readPrice, readChargeRate) userTaxRate := params.VersionedParams.ValidatorTaxRate.MulInt(readChargeRate).TruncateInt() @@ -192,13 +191,13 @@ func (s *PaymentTestSuite) TestStorageBill_Smoke() { s.T().Logf("queryHeadObjectResponse %s, err: %v", queryHeadObjectResponse, err) s.Require().NoError(err) - queryGetSecondarySpStorePriceByTime, err := s.Client.QueryGetSecondarySpStorePriceByTime(ctx, &sptypes.QueryGetSecondarySpStorePriceByTimeRequest{ + queryGlobalSpStorePriceByTime, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ Timestamp: queryHeadBucketResponse.BucketInfo.CreateAt, }) - s.T().Logf("queryGetSecondarySpStorePriceByTime %s, err: %v", queryGetSecondarySpStorePriceByTime, err) + s.T().Logf("queryGlobalSpStorePriceByTime %s, err: %v", queryGlobalSpStorePriceByTime, err) s.Require().NoError(err) - primaryStorePrice := queryGetSpStoragePriceByTimeResp.SpStoragePrice.StorePrice - secondaryStorePrice := queryGetSecondarySpStorePriceByTime.SecondarySpStorePrice.StorePrice + primaryStorePrice := queryGlobalSpStorePriceByTime.GlobalSpStorePrice.PrimaryStorePrice + secondaryStorePrice := queryGlobalSpStorePriceByTime.GlobalSpStorePrice.SecondaryStorePrice chargeSize := s.getChargeSize(queryHeadObjectResponse.ObjectInfo.PayloadSize) expectedChargeRate := primaryStorePrice.Add(secondaryStorePrice.MulInt64(6)).MulInt(sdk.NewIntFromUint64(chargeSize)).TruncateInt() expectedChargeRate = params.VersionedParams.ValidatorTaxRate.MulInt(expectedChargeRate).TruncateInt().Add(expectedChargeRate) @@ -442,9 +441,8 @@ func (s *PaymentTestSuite) TestStorageBill_DeleteObjectBucket_WithPriceChange() s.Require().NoError(err) // sp price changes - priceRes, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - Timestamp: 0, + priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorKey.GetAddr().String(), }) s.Require().NoError(err) s.T().Log("price", priceRes.SpStoragePrice) @@ -557,9 +555,8 @@ func (s *PaymentTestSuite) TestStorageBill_DeleteObjectBucket_WithPriceChangeRes s.Require().NoError(err) // sp price changes - priceRes, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - Timestamp: 0, + priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorKey.GetAddr().String(), }) s.Require().NoError(err) s.T().Log("price", priceRes.SpStoragePrice) @@ -799,14 +796,13 @@ func (s *PaymentTestSuite) TestStorageBill_CreateBucket_WithZeroNoneZeroReadQuot s.Require().NoError(err) // check price and rate calculation - queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + queryGlobalSpStoragePriceByTimeResp, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ Timestamp: queryHeadBucketResponse.BucketInfo.CreateAt, }) - s.T().Logf("queryGetSpStoragePriceByTimeResp %s, err: %v", queryGetSpStoragePriceByTimeResp, err) + s.T().Logf("queryGlobalSpStoragePriceByTimeResp %s, err: %v", queryGlobalSpStoragePriceByTimeResp, err) s.Require().NoError(err) - readPrice := queryGetSpStoragePriceByTimeResp.SpStoragePrice.ReadPrice + readPrice := queryGlobalSpStoragePriceByTimeResp.GlobalSpStorePrice.ReadPrice readChargeRate := readPrice.MulInt(sdk.NewIntFromUint64(queryHeadBucketResponse.BucketInfo.ChargedReadQuota)).TruncateInt() s.T().Logf("readPrice: %s, readChargeRate: %s", readPrice, readChargeRate) taxRate := params.VersionedParams.ValidatorTaxRate.MulInt(readChargeRate).TruncateInt() @@ -1073,9 +1069,8 @@ func (s *PaymentTestSuite) TestStorageBill_SealObject_WithPriceChange() { // case: seal object with read price change and storage price change _, _, objectName, objectId, checksums, payloadSize := s.createObject(user, bucketName, false) - priceRes, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - Timestamp: 0, + priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorKey.GetAddr().String(), }) s.Require().NoError(err) // update new price @@ -1134,9 +1129,8 @@ func (s *PaymentTestSuite) TestStorageBill_SealObject_WithPriceChangeValidatorTa // case: seal object with read price change and storage price change _, _, objectName, objectId, checksums, payloadSize := s.createObject(user, bucketName, false) - priceRes, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - Timestamp: 0, + priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorKey.GetAddr().String(), }) s.Require().NoError(err) // update new price @@ -1227,9 +1221,8 @@ func (s *PaymentTestSuite) TestStorageBill_RejectSealObject_WithPriceChange() { // case: seal object with read price change and storage price change _, _, objectName, _, _, _ := s.createObject(user, bucketName, false) - priceRes, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - Timestamp: 0, + priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorKey.GetAddr().String(), }) s.Require().NoError(err) // update new price @@ -1283,9 +1276,8 @@ func (s *PaymentTestSuite) TestStorageBill_FullLifecycle() { user := s.GenAndChargeAccounts(1, 1000000)[0] // query storage price - priceRes, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - Timestamp: 0, + priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorKey.GetAddr().String(), }) s.Require().NoError(err) s.T().Log("price", priceRes.SpStoragePrice) @@ -1520,9 +1512,8 @@ func (s *PaymentTestSuite) TestStorageBill_CopyObject_WithPriceChange() { s.Require().Equal(streamRecordsAfter.GVG.NetflowRate.Sub(streamRecordsBefore.GVG.NetflowRate), gvgRate) s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate), taxRate) - priceRes, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - Timestamp: 0, + priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorKey.GetAddr().String(), }) s.Require().NoError(err) // update new price @@ -1602,14 +1593,13 @@ func (s *PaymentTestSuite) TestStorageBill_UpdateBucketQuota() { s.Require().NoError(err) // check price and rate calculation - queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - Timestamp: time.Now().Unix(), + priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorKey.GetAddr().String(), }) - s.T().Logf("queryGetSpStoragePriceByTimeResp %s, err: %v", queryGetSpStoragePriceByTimeResp, err) + s.T().Logf("priceRes %s, err: %v", priceRes, err) s.Require().NoError(err) - readPrice := queryGetSpStoragePriceByTimeResp.SpStoragePrice.ReadPrice + readPrice := priceRes.SpStoragePrice.ReadPrice readChargeRate := readPrice.MulInt(sdk.NewIntFromUint64(bucketInfo.ChargedReadQuota)).TruncateInt() s.T().Logf("readPrice: %s, readChargeRate: %s", readPrice, readChargeRate) taxRate := paymentParams.Params.VersionedParams.ValidatorTaxRate.MulInt(readChargeRate).TruncateInt() @@ -1638,9 +1628,9 @@ func (s *PaymentTestSuite) TestStorageBill_UpdateBucketQuota() { // update new price msgUpdatePrice := &sptypes.MsgUpdateSpStoragePrice{ SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: queryGetSpStoragePriceByTimeResp.SpStoragePrice.ReadPrice.MulInt64(100), - FreeReadQuota: queryGetSpStoragePriceByTimeResp.SpStoragePrice.FreeReadQuota, - StorePrice: queryGetSpStoragePriceByTimeResp.SpStoragePrice.StorePrice, + ReadPrice: priceRes.SpStoragePrice.ReadPrice.MulInt64(100), + FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, + StorePrice: priceRes.SpStoragePrice.StorePrice, } s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) @@ -1649,14 +1639,13 @@ func (s *PaymentTestSuite) TestStorageBill_UpdateBucketQuota() { s.Require().NoError(err) // check price and rate calculation - queryGetSpStoragePriceByTimeResp, err = s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - Timestamp: time.Now().Unix(), + priceRes, err = s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorKey.GetAddr().String(), }) - s.T().Logf("queryGetSpStoragePriceByTimeResp %s, err: %v", queryGetSpStoragePriceByTimeResp, err) + s.T().Logf("priceRes %s, err: %v", priceRes, err) s.Require().NoError(err) - readPrice = queryGetSpStoragePriceByTimeResp.SpStoragePrice.ReadPrice + readPrice = priceRes.SpStoragePrice.ReadPrice readChargeRate = readPrice.MulInt(sdk.NewIntFromUint64(bucketInfo.ChargedReadQuota)).TruncateInt() s.T().Logf("readPrice: %s, readChargeRate: %s", readPrice, readChargeRate) taxRate = paymentParams.Params.VersionedParams.ValidatorTaxRate.MulInt(readChargeRate).TruncateInt() @@ -1685,9 +1674,9 @@ func (s *PaymentTestSuite) TestStorageBill_UpdateBucketQuota() { // set big read price msgUpdatePrice = &sptypes.MsgUpdateSpStoragePrice{ SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: queryGetSpStoragePriceByTimeResp.SpStoragePrice.ReadPrice.MulInt64(1024 * 1024 * 1024), - FreeReadQuota: queryGetSpStoragePriceByTimeResp.SpStoragePrice.FreeReadQuota, - StorePrice: queryGetSpStoragePriceByTimeResp.SpStoragePrice.StorePrice, + ReadPrice: priceRes.SpStoragePrice.ReadPrice.MulInt64(1024 * 1024 * 1024), + FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, + StorePrice: priceRes.SpStoragePrice.StorePrice, } s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) @@ -1751,14 +1740,13 @@ func (s *PaymentTestSuite) TestStorageBill_UpdatePaymentAddress() { s.Require().NoError(err) // check price and rate calculation - queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - Timestamp: time.Now().Unix(), + priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorKey.GetAddr().String(), }) - s.T().Logf("queryGetSpStoragePriceByTimeResp %s, err: %v", queryGetSpStoragePriceByTimeResp, err) + s.T().Logf("priceRes %s, err: %v", priceRes, err) s.Require().NoError(err) - readPrice := queryGetSpStoragePriceByTimeResp.SpStoragePrice.ReadPrice + readPrice := priceRes.SpStoragePrice.ReadPrice readChargeRate := readPrice.MulInt(sdk.NewIntFromUint64(bucketInfo.ChargedReadQuota)).TruncateInt() s.T().Logf("readPrice: %s, readChargeRate: %s", readPrice, readChargeRate) taxRate := paymentParams.Params.VersionedParams.ValidatorTaxRate.MulInt(readChargeRate).TruncateInt() @@ -1787,9 +1775,9 @@ func (s *PaymentTestSuite) TestStorageBill_UpdatePaymentAddress() { // update new price msgUpdatePrice := &sptypes.MsgUpdateSpStoragePrice{ SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: queryGetSpStoragePriceByTimeResp.SpStoragePrice.ReadPrice.MulInt64(100), - FreeReadQuota: queryGetSpStoragePriceByTimeResp.SpStoragePrice.FreeReadQuota, - StorePrice: queryGetSpStoragePriceByTimeResp.SpStoragePrice.StorePrice, + ReadPrice: priceRes.SpStoragePrice.ReadPrice.MulInt64(100), + FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, + StorePrice: priceRes.SpStoragePrice.StorePrice, } s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) @@ -1798,14 +1786,13 @@ func (s *PaymentTestSuite) TestStorageBill_UpdatePaymentAddress() { s.Require().NoError(err) // check price and rate calculation - queryGetSpStoragePriceByTimeResp, err = s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - Timestamp: time.Now().Unix(), + priceRes, err = s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorKey.GetAddr().String(), }) - s.T().Logf("queryGetSpStoragePriceByTimeResp %s, err: %v", queryGetSpStoragePriceByTimeResp, err) + s.T().Logf("priceRes %s, err: %v", priceRes, err) s.Require().NoError(err) - readPrice = queryGetSpStoragePriceByTimeResp.SpStoragePrice.ReadPrice + readPrice = priceRes.SpStoragePrice.ReadPrice readChargeRate = readPrice.MulInt(sdk.NewIntFromUint64(bucketInfo.ChargedReadQuota)).TruncateInt() s.T().Logf("readPrice: %s, readChargeRate: %s", readPrice, readChargeRate) taxRate = paymentParams.Params.VersionedParams.ValidatorTaxRate.MulInt(readChargeRate).TruncateInt() @@ -1836,9 +1823,9 @@ func (s *PaymentTestSuite) TestStorageBill_UpdatePaymentAddress() { // set big read price msgUpdatePrice = &sptypes.MsgUpdateSpStoragePrice{ SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: queryGetSpStoragePriceByTimeResp.SpStoragePrice.ReadPrice.MulInt64(1024 * 1024 * 1024), - FreeReadQuota: queryGetSpStoragePriceByTimeResp.SpStoragePrice.FreeReadQuota, - StorePrice: queryGetSpStoragePriceByTimeResp.SpStoragePrice.StorePrice, + ReadPrice: priceRes.SpStoragePrice.ReadPrice.MulInt64(1024 * 1024 * 1024), + FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, + StorePrice: priceRes.SpStoragePrice.StorePrice, } s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) @@ -1853,7 +1840,6 @@ func (s *PaymentTestSuite) TestStorageBill_UpdatePaymentAddress() { user.GetAddr(), bucketName, &readQuota, paymentAcc, storagetypes.VISIBILITY_TYPE_PRIVATE) s.SendTxBlockWithExpectErrorString(msgUpdateBucketInfo, user, "apply user flows list failed") - } func (s *PaymentTestSuite) TestStorageBill_MigrationBucket() { @@ -2068,14 +2054,13 @@ func (s *PaymentTestSuite) NewMigrateBucket(srcSP, dstSP *core.StorageProvider, func (s *PaymentTestSuite) SetSPPrice(sp *core.StorageProvider, readPrice, storePrice string) { ctx := context.Background() - queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - Timestamp: time.Now().Unix(), + priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorKey.GetAddr().String(), }) s.Require().NoError(err) ReadPrice, err := sdk.NewDecFromStr(readPrice) s.Require().NoError(err) - StorePrice := queryGetSpStoragePriceByTimeResp.SpStoragePrice.StorePrice + StorePrice := priceRes.SpStoragePrice.StorePrice if storePrice != "0" { StorePrice, err = sdk.NewDecFromStr(storePrice) s.Require().NoError(err) @@ -2084,18 +2069,16 @@ func (s *PaymentTestSuite) SetSPPrice(sp *core.StorageProvider, readPrice, store msgUpdatePrice := &sptypes.MsgUpdateSpStoragePrice{ SpAddress: sp.OperatorKey.GetAddr().String(), ReadPrice: ReadPrice, - FreeReadQuota: queryGetSpStoragePriceByTimeResp.SpStoragePrice.FreeReadQuota, + FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, StorePrice: StorePrice, } s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) - queryGetSpStoragePriceByTimeResp, err = s.Client.QueryGetSpStoragePriceByTime(ctx, &sptypes.QueryGetSpStoragePriceByTimeRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - Timestamp: time.Now().Unix(), + priceRes, err = s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorKey.GetAddr().String(), }) s.Require().NoError(err) - s.T().Logf("queryGetSpStoragePriceByTimeResp read price: %s, store price: %v", - queryGetSpStoragePriceByTimeResp.SpStoragePrice.ReadPrice, queryGetSpStoragePriceByTimeResp.SpStoragePrice.StorePrice) - + s.T().Logf("priceRes read price: %s, store price: %v", + priceRes.SpStoragePrice.ReadPrice, priceRes.SpStoragePrice.StorePrice) } // CreatePaymentAccount create new payment account and return latest payment account diff --git a/proto/greenfield/sp/events.proto b/proto/greenfield/sp/events.proto index 4a2784f08..caf54d817 100644 --- a/proto/greenfield/sp/events.proto +++ b/proto/greenfield/sp/events.proto @@ -89,11 +89,23 @@ message EventSpStoragePriceUpdate { ]; } -message EventSecondarySpStorePriceUpdate { +message EventGlobalSpStorePriceUpdate { // update time, in unix timestamp int64 update_time_sec = 1; - // store price, in bnb wei per charge byte - string store_price = 2 [ + // read price, in bnb wei per charge byte + string read_price = 2 [ + (cosmos_proto.scalar) = "cosmos.Dec", + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; + // primary store price, in bnb wei per charge byte + string primary_store_price = 3 [ + (cosmos_proto.scalar) = "cosmos.Dec", + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; + // secondary store price, in bnb wei per charge byte + string secondary_store_price = 4 [ (cosmos_proto.scalar) = "cosmos.Dec", (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false diff --git a/proto/greenfield/sp/query.proto b/proto/greenfield/sp/query.proto index 0663c5c75..e9d4b331f 100644 --- a/proto/greenfield/sp/query.proto +++ b/proto/greenfield/sp/query.proto @@ -26,14 +26,14 @@ service Query { option (google.api.http).get = "/greenfield/storage_providers"; } - // get storage price of specific sp and time - rpc QueryGetSpStoragePriceByTime(QueryGetSpStoragePriceByTimeRequest) returns (QueryGetSpStoragePriceByTimeResponse) { - option (google.api.http).get = "/greenfield/sp/get_sp_storage_price_by_time/{sp_addr}/{timestamp}"; + // get the latest storage price of specific sp + rpc QuerySpStoragePrice(QuerySpStoragePriceRequest) returns (QuerySpStoragePriceResponse) { + option (google.api.http).get = "/greenfield/sp/sp_storage_price/{sp_addr}"; } - // get secondary store price by time - rpc QueryGetSecondarySpStorePriceByTime(QueryGetSecondarySpStorePriceByTimeRequest) returns (QueryGetSecondarySpStorePriceByTimeResponse) { - option (google.api.http).get = "/greenfield/sp/get_secondary_sp_store_price_by_time/{timestamp}"; + // get global store price by time + rpc QueryGlobalSpStorePriceByTime(QueryGlobalSpStorePriceByTimeRequest) returns (QueryGlobalSpStorePriceByTimeResponse) { + option (google.api.http).get = "/greenfield/sp/global_sp_store_price_by_time/{timestamp}"; } // Queries a storage provider with specify id @@ -74,24 +74,22 @@ message QueryStorageProvidersResponse { cosmos.base.query.v1beta1.PageResponse pagination = 2; } -message QueryGetSpStoragePriceByTimeRequest { +message QuerySpStoragePriceRequest { // operator address of sp string sp_addr = 1; - // unix timestamp in seconds. If it's 0, it will return the latest price. - int64 timestamp = 2; } -message QueryGetSpStoragePriceByTimeResponse { +message QuerySpStoragePriceResponse { SpStoragePrice sp_storage_price = 1 [(gogoproto.nullable) = false]; } -message QueryGetSecondarySpStorePriceByTimeRequest { +message QueryGlobalSpStorePriceByTimeRequest { // unix timestamp in seconds. If it's 0, it will return the latest price. int64 timestamp = 1; } -message QueryGetSecondarySpStorePriceByTimeResponse { - SecondarySpStorePrice secondary_sp_store_price = 1 [(gogoproto.nullable) = false]; +message QueryGlobalSpStorePriceByTimeResponse { + GlobalSpStorePrice global_sp_store_price = 1 [(gogoproto.nullable) = false]; } message QueryStorageProviderRequest { diff --git a/proto/greenfield/sp/types.proto b/proto/greenfield/sp/types.proto index 9715e2ca6..3d83286b6 100644 --- a/proto/greenfield/sp/types.proto +++ b/proto/greenfield/sp/types.proto @@ -90,12 +90,24 @@ message SpStoragePrice { ]; } -// global secondary sp store price, the price for all secondary sps -message SecondarySpStorePrice { +// global sp store price, the price for all sps +message GlobalSpStorePrice { // update time, unix timestamp in seconds int64 update_time_sec = 1; - // store price, in bnb wei per charge byte - string store_price = 2 [ + // read price, in bnb wei per charge byte + string read_price = 2 [ + (cosmos_proto.scalar) = "cosmos.Dec", + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; + // primary store price, in bnb wei per charge byte + string primary_store_price = 3 [ + (cosmos_proto.scalar) = "cosmos.Dec", + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; + // secondary store price, in bnb wei per charge byte + string secondary_store_price = 4 [ (cosmos_proto.scalar) = "cosmos.Dec", (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false diff --git a/x/payment/keeper/keeper.go b/x/payment/keeper/keeper.go index 78f12acbd..9e4c62af2 100644 --- a/x/payment/keeper/keeper.go +++ b/x/payment/keeper/keeper.go @@ -20,7 +20,6 @@ type ( bankKeeper types.BankKeeper accountKeeper types.AccountKeeper - spKeeper types.SpKeeper authority string } ) @@ -30,7 +29,6 @@ func NewKeeper( storeKey storetypes.StoreKey, bankKeeper types.BankKeeper, accountKeeper types.AccountKeeper, - spKeeper types.SpKeeper, authority string, ) *Keeper { return &Keeper{ @@ -38,7 +36,6 @@ func NewKeeper( storeKey: storeKey, bankKeeper: bankKeeper, accountKeeper: accountKeeper, - spKeeper: spKeeper, authority: authority, } } diff --git a/x/payment/keeper/keeper_test.go b/x/payment/keeper/keeper_test.go index 0d815fac5..534b8e414 100644 --- a/x/payment/keeper/keeper_test.go +++ b/x/payment/keeper/keeper_test.go @@ -18,7 +18,6 @@ import ( type DepKeepers struct { BankKeeper *types.MockBankKeeper AccountKeeper *types.MockAccountKeeper - SpKeeper *types.MockSpKeeper } func makePaymentKeeper(t *testing.T) (*keeper.Keeper, sdk.Context, DepKeepers) { @@ -29,13 +28,11 @@ func makePaymentKeeper(t *testing.T) (*keeper.Keeper, sdk.Context, DepKeepers) { ctrl := gomock.NewController(t) bankKeeper := types.NewMockBankKeeper(ctrl) accountKeeper := types.NewMockAccountKeeper(ctrl) - spKeeper := types.NewMockSpKeeper(ctrl) k := keeper.NewKeeper( encCfg.Codec, key, bankKeeper, accountKeeper, - spKeeper, authtypes.NewModuleAddress(types.ModuleName).String(), ) err := k.SetParams(testCtx.Ctx, types.DefaultParams()) @@ -46,7 +43,6 @@ func makePaymentKeeper(t *testing.T) (*keeper.Keeper, sdk.Context, DepKeepers) { depKeepers := DepKeepers{ BankKeeper: bankKeeper, AccountKeeper: accountKeeper, - SpKeeper: spKeeper, } return k, testCtx.Ctx, depKeepers diff --git a/x/payment/keeper/msg_server_test.go b/x/payment/keeper/msg_server_test.go index c7c3f735f..8aa3fae6a 100644 --- a/x/payment/keeper/msg_server_test.go +++ b/x/payment/keeper/msg_server_test.go @@ -29,7 +29,6 @@ type TestSuite struct { bankKeeper *types.MockBankKeeper accountKeeper *types.MockAccountKeeper - spKeeper *types.MockSpKeeper ctx sdk.Context queryClient types.QueryClient @@ -46,21 +45,18 @@ func (s *TestSuite) SetupTest() { bankKeeper := types.NewMockBankKeeper(ctrl) accountKeeper := types.NewMockAccountKeeper(ctrl) - spKeeper := types.NewMockSpKeeper(ctrl) s.paymentKeeper = keeper.NewKeeper( encCfg.Codec, key, bankKeeper, accountKeeper, - spKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) s.cdc = encCfg.Codec s.bankKeeper = bankKeeper s.accountKeeper = accountKeeper - s.spKeeper = spKeeper err := s.paymentKeeper.SetParams(s.ctx, types.DefaultParams()) s.Require().NoError(err) diff --git a/x/payment/keeper/price.go b/x/payment/keeper/price.go deleted file mode 100644 index 294525b83..000000000 --- a/x/payment/keeper/price.go +++ /dev/null @@ -1,26 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/bnb-chain/greenfield/x/payment/types" -) - -func (k Keeper) GetStoragePrice(ctx sdk.Context, params types.StoragePriceParams) (price types.StoragePrice, err error) { - primarySpPrice, err := k.spKeeper.GetSpStoragePriceByTime(ctx, params.PrimarySp, params.PriceTime) - if err != nil { - return types.StoragePrice{}, fmt.Errorf("get sp %d storage price @%d failed: %w", params.PrimarySp, params.PriceTime, err) - } - secondarySpStorePrice, err := k.spKeeper.GetSecondarySpStorePriceByTime(ctx, params.PriceTime) - if err != nil { - return types.StoragePrice{}, fmt.Errorf("get secondary sp store price failed: %w, price time: %d", err, params.PriceTime) - } - storePrice := types.StoragePrice{ - PrimaryStorePrice: primarySpPrice.StorePrice, - SecondaryStorePrice: secondarySpStorePrice.StorePrice, - ReadPrice: primarySpPrice.ReadPrice, - } - return storePrice, nil -} diff --git a/x/payment/keeper/price_test.go b/x/payment/keeper/price_test.go deleted file mode 100644 index 15f2ba89d..000000000 --- a/x/payment/keeper/price_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/golang/mock/gomock" - "github.com/stretchr/testify/require" - - "github.com/bnb-chain/greenfield/x/payment/types" - sp "github.com/bnb-chain/greenfield/x/sp/types" -) - -func TestGetStoragePrice(t *testing.T) { - keeper, ctx, depKeepers := makePaymentKeeper(t) - - primaryPrice := sp.SpStoragePrice{ - ReadPrice: sdk.NewDecWithPrec(2, 2), - FreeReadQuota: 0, - StorePrice: sdk.NewDecWithPrec(5, 1), - } - depKeepers.SpKeeper.EXPECT().GetSpStoragePriceByTime(gomock.Any(), gomock.Any(), gomock.Any()). - Return(primaryPrice, nil).AnyTimes() - - secondaryPrice := sp.SecondarySpStorePrice{ - StorePrice: sdk.NewDecWithPrec(2, 1), - } - depKeepers.SpKeeper.EXPECT().GetSecondarySpStorePriceByTime(gomock.Any(), gomock.Any()). - Return(secondaryPrice, nil).AnyTimes() - - resp, err := keeper.GetStoragePrice(ctx, types.StoragePriceParams{ - PrimarySp: 1, - PriceTime: 1, - }) - require.NoError(t, err) - require.True(t, resp.ReadPrice.Equal(primaryPrice.ReadPrice)) - require.True(t, resp.PrimaryStorePrice.Equal(primaryPrice.StorePrice)) - require.True(t, resp.SecondaryStorePrice.Equal(secondaryPrice.StorePrice)) -} diff --git a/x/payment/types/expected_keepers.go b/x/payment/types/expected_keepers.go index 943596b10..85e29402a 100644 --- a/x/payment/types/expected_keepers.go +++ b/x/payment/types/expected_keepers.go @@ -3,8 +3,6 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - - sptypes "github.com/bnb-chain/greenfield/x/sp/types" ) // AccountKeeper defines the expected account keeper used for simulations (noalias) @@ -24,9 +22,3 @@ type BankKeeper interface { 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 } - -// SpKeeper defines the expected interface needed to retrieve storage provider. -type SpKeeper interface { - GetSpStoragePriceByTime(ctx sdk.Context, spId uint32, time int64) (val sptypes.SpStoragePrice, err error) - GetSecondarySpStorePriceByTime(ctx sdk.Context, time int64) (val sptypes.SecondarySpStorePrice, err error) -} diff --git a/x/payment/types/expected_keepers_mocks.go b/x/payment/types/expected_keepers_mocks.go index fd96f7ab0..9450c3ce7 100644 --- a/x/payment/types/expected_keepers_mocks.go +++ b/x/payment/types/expected_keepers_mocks.go @@ -7,9 +7,8 @@ package types import ( reflect "reflect" - types "github.com/bnb-chain/greenfield/x/sp/types" - types0 "github.com/cosmos/cosmos-sdk/types" - types1 "github.com/cosmos/cosmos-sdk/x/auth/types" + types "github.com/cosmos/cosmos-sdk/types" + types0 "github.com/cosmos/cosmos-sdk/x/auth/types" gomock "github.com/golang/mock/gomock" ) @@ -37,10 +36,10 @@ func (m *MockAccountKeeper) EXPECT() *MockAccountKeeperMockRecorder { } // GetAccount mocks base method. -func (m *MockAccountKeeper) GetAccount(ctx types0.Context, addr types0.AccAddress) types1.AccountI { +func (m *MockAccountKeeper) GetAccount(ctx types.Context, addr types.AccAddress) types0.AccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAccount", ctx, addr) - ret0, _ := ret[0].(types1.AccountI) + ret0, _ := ret[0].(types0.AccountI) return ret0 } @@ -51,10 +50,10 @@ func (mr *MockAccountKeeperMockRecorder) GetAccount(ctx, addr interface{}) *gomo } // GetModuleAccount mocks base method. -func (m *MockAccountKeeper) GetModuleAccount(ctx types0.Context, moduleName string) types1.ModuleAccountI { +func (m *MockAccountKeeper) GetModuleAccount(ctx types.Context, moduleName string) types0.ModuleAccountI { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetModuleAccount", ctx, moduleName) - ret0, _ := ret[0].(types1.ModuleAccountI) + ret0, _ := ret[0].(types0.ModuleAccountI) return ret0 } @@ -65,10 +64,10 @@ func (mr *MockAccountKeeperMockRecorder) GetModuleAccount(ctx, moduleName interf } // GetModuleAddress mocks base method. -func (m *MockAccountKeeper) GetModuleAddress(name string) types0.AccAddress { +func (m *MockAccountKeeper) GetModuleAddress(name string) types.AccAddress { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetModuleAddress", name) - ret0, _ := ret[0].(types0.AccAddress) + ret0, _ := ret[0].(types.AccAddress) return ret0 } @@ -79,7 +78,7 @@ func (mr *MockAccountKeeperMockRecorder) GetModuleAddress(name interface{}) *gom } // HasAccount mocks base method. -func (m *MockAccountKeeper) HasAccount(ctx types0.Context, addr types0.AccAddress) bool { +func (m *MockAccountKeeper) HasAccount(ctx types.Context, addr types.AccAddress) bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "HasAccount", ctx, addr) ret0, _ := ret[0].(bool) @@ -93,7 +92,7 @@ func (mr *MockAccountKeeperMockRecorder) HasAccount(ctx, addr interface{}) *gomo } // SetModuleAccount mocks base method. -func (m *MockAccountKeeper) SetModuleAccount(arg0 types0.Context, arg1 types1.ModuleAccountI) { +func (m *MockAccountKeeper) SetModuleAccount(arg0 types.Context, arg1 types0.ModuleAccountI) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetModuleAccount", arg0, arg1) } @@ -128,10 +127,10 @@ func (m *MockBankKeeper) EXPECT() *MockBankKeeperMockRecorder { } // GetAllBalances mocks base method. -func (m *MockBankKeeper) GetAllBalances(ctx types0.Context, addr types0.AccAddress) types0.Coins { +func (m *MockBankKeeper) GetAllBalances(ctx types.Context, addr types.AccAddress) types.Coins { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAllBalances", ctx, addr) - ret0, _ := ret[0].(types0.Coins) + ret0, _ := ret[0].(types.Coins) return ret0 } @@ -142,10 +141,10 @@ func (mr *MockBankKeeperMockRecorder) GetAllBalances(ctx, addr interface{}) *gom } // GetBalance mocks base method. -func (m *MockBankKeeper) GetBalance(ctx types0.Context, addr types0.AccAddress, denom string) types0.Coin { +func (m *MockBankKeeper) GetBalance(ctx types.Context, addr types.AccAddress, denom string) types.Coin { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetBalance", ctx, addr, denom) - ret0, _ := ret[0].(types0.Coin) + ret0, _ := ret[0].(types.Coin) return ret0 } @@ -156,7 +155,7 @@ func (mr *MockBankKeeperMockRecorder) GetBalance(ctx, addr, denom interface{}) * } // SendCoinsFromAccountToModule mocks base method. -func (m *MockBankKeeper) SendCoinsFromAccountToModule(ctx types0.Context, senderAddr types0.AccAddress, recipientModule string, amt types0.Coins) error { +func (m *MockBankKeeper) SendCoinsFromAccountToModule(ctx types.Context, senderAddr types.AccAddress, recipientModule string, amt types.Coins) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SendCoinsFromAccountToModule", ctx, senderAddr, recipientModule, amt) ret0, _ := ret[0].(error) @@ -170,7 +169,7 @@ func (mr *MockBankKeeperMockRecorder) SendCoinsFromAccountToModule(ctx, senderAd } // SendCoinsFromModuleToAccount mocks base method. -func (m *MockBankKeeper) SendCoinsFromModuleToAccount(ctx types0.Context, senderModule string, recipientAddr types0.AccAddress, amt types0.Coins) error { +func (m *MockBankKeeper) SendCoinsFromModuleToAccount(ctx types.Context, senderModule string, recipientAddr types.AccAddress, amt types.Coins) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SendCoinsFromModuleToAccount", ctx, senderModule, recipientAddr, amt) ret0, _ := ret[0].(error) @@ -184,10 +183,10 @@ func (mr *MockBankKeeperMockRecorder) SendCoinsFromModuleToAccount(ctx, senderMo } // SpendableCoins mocks base method. -func (m *MockBankKeeper) SpendableCoins(ctx types0.Context, addr types0.AccAddress) types0.Coins { +func (m *MockBankKeeper) SpendableCoins(ctx types.Context, addr types.AccAddress) types.Coins { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SpendableCoins", ctx, addr) - ret0, _ := ret[0].(types0.Coins) + ret0, _ := ret[0].(types.Coins) return ret0 } @@ -196,56 +195,3 @@ func (mr *MockBankKeeperMockRecorder) SpendableCoins(ctx, addr interface{}) *gom mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SpendableCoins", reflect.TypeOf((*MockBankKeeper)(nil).SpendableCoins), ctx, addr) } - -// MockSpKeeper is a mock of SpKeeper interface. -type MockSpKeeper struct { - ctrl *gomock.Controller - recorder *MockSpKeeperMockRecorder -} - -// MockSpKeeperMockRecorder is the mock recorder for MockSpKeeper. -type MockSpKeeperMockRecorder struct { - mock *MockSpKeeper -} - -// NewMockSpKeeper creates a new mock instance. -func NewMockSpKeeper(ctrl *gomock.Controller) *MockSpKeeper { - mock := &MockSpKeeper{ctrl: ctrl} - mock.recorder = &MockSpKeeperMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockSpKeeper) EXPECT() *MockSpKeeperMockRecorder { - return m.recorder -} - -// GetSecondarySpStorePriceByTime mocks base method. -func (m *MockSpKeeper) GetSecondarySpStorePriceByTime(ctx types0.Context, time int64) (types.SecondarySpStorePrice, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSecondarySpStorePriceByTime", ctx, time) - ret0, _ := ret[0].(types.SecondarySpStorePrice) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSecondarySpStorePriceByTime indicates an expected call of GetSecondarySpStorePriceByTime. -func (mr *MockSpKeeperMockRecorder) GetSecondarySpStorePriceByTime(ctx, time interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSecondarySpStorePriceByTime", reflect.TypeOf((*MockSpKeeper)(nil).GetSecondarySpStorePriceByTime), ctx, time) -} - -// GetSpStoragePriceByTime mocks base method. -func (m *MockSpKeeper) GetSpStoragePriceByTime(ctx types0.Context, spId uint32, time int64) (types.SpStoragePrice, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSpStoragePriceByTime", ctx, spId, time) - ret0, _ := ret[0].(types.SpStoragePrice) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSpStoragePriceByTime indicates an expected call of GetSpStoragePriceByTime. -func (mr *MockSpKeeperMockRecorder) GetSpStoragePriceByTime(ctx, spId, time interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSpStoragePriceByTime", reflect.TypeOf((*MockSpKeeper)(nil).GetSpStoragePriceByTime), ctx, spId, time) -} diff --git a/x/payment/types/price.go b/x/payment/types/price.go index 6b67c292b..fe2d3b9a2 100644 --- a/x/payment/types/price.go +++ b/x/payment/types/price.go @@ -43,17 +43,6 @@ func (change *StreamRecordChange) WithFrozenRateChange(frozenRateChange sdkmath. return change } -type StoragePriceParams struct { - PrimarySp uint32 - PriceTime int64 -} - -type StoragePrice struct { - ReadPrice sdk.Dec - PrimaryStorePrice sdk.Dec - SecondaryStorePrice sdk.Dec -} - type UserFlows struct { From sdk.AccAddress Flows []OutFlow diff --git a/x/sp/keeper/grpc_query.go b/x/sp/keeper/grpc_query.go index 413db357b..1fe961ee1 100644 --- a/x/sp/keeper/grpc_query.go +++ b/x/sp/keeper/grpc_query.go @@ -34,17 +34,11 @@ func (k Keeper) StorageProviders(goCtx context.Context, req *types.QueryStorageP return &types.QueryStorageProvidersResponse{Sps: sps, Pagination: pageRes}, nil } -func (k Keeper) QueryGetSpStoragePriceByTime(goCtx context.Context, req *types.QueryGetSpStoragePriceByTimeRequest) (*types.QueryGetSpStoragePriceByTimeResponse, error) { +func (k Keeper) QuerySpStoragePrice(goCtx context.Context, req *types.QuerySpStoragePriceRequest) (*types.QuerySpStoragePriceResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") } - if req.Timestamp < 0 { - return nil, status.Error(codes.InvalidArgument, "invalid timestamp") - } - if req.Timestamp == 0 { - req.Timestamp = ctx.BlockTime().Unix() + 1 - } spAddr, err := sdk.AccAddressFromHexUnsafe(req.SpAddr) if err != nil { return nil, status.Error(codes.InvalidArgument, "invalid sp address") @@ -53,14 +47,14 @@ func (k Keeper) QueryGetSpStoragePriceByTime(goCtx context.Context, req *types.Q if !found { return nil, status.Error(codes.InvalidArgument, "unknown sp with the operator address") } - spStoragePrice, err := k.GetSpStoragePriceByTime(ctx, sp.Id, req.Timestamp) - if err != nil { + spStoragePrice, found := k.GetSpStoragePrice(ctx, sp.Id) + if !found { return nil, status.Errorf(codes.NotFound, "not found, err: %s", err) } - return &types.QueryGetSpStoragePriceByTimeResponse{SpStoragePrice: spStoragePrice}, nil + return &types.QuerySpStoragePriceResponse{SpStoragePrice: spStoragePrice}, nil } -func (k Keeper) QueryGetSecondarySpStorePriceByTime(goCtx context.Context, req *types.QueryGetSecondarySpStorePriceByTimeRequest) (*types.QueryGetSecondarySpStorePriceByTimeResponse, error) { +func (k Keeper) QueryGlobalSpStorePriceByTime(goCtx context.Context, req *types.QueryGlobalSpStorePriceByTimeRequest) (*types.QueryGlobalSpStorePriceByTimeResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) if req == nil { return nil, status.Error(codes.InvalidArgument, "invalid request") @@ -72,11 +66,11 @@ func (k Keeper) QueryGetSecondarySpStorePriceByTime(goCtx context.Context, req * req.Timestamp = ctx.BlockTime().Unix() + 1 } - price, err := k.GetSecondarySpStorePriceByTime(ctx, req.Timestamp) + price, err := k.GetGlobalSpStorePriceByTime(ctx, req.Timestamp) if err != nil { return nil, status.Errorf(codes.Internal, "err: %s", err) } - return &types.QueryGetSecondarySpStorePriceByTimeResponse{SecondarySpStorePrice: price}, nil + return &types.QueryGlobalSpStorePriceByTimeResponse{GlobalSpStorePrice: price}, nil } func (k Keeper) StorageProvider(goCtx context.Context, req *types.QueryStorageProviderRequest) (*types.QueryStorageProviderResponse, error) { diff --git a/x/sp/keeper/msg_server.go b/x/sp/keeper/msg_server.go index ad2199e54..ce6096ee1 100644 --- a/x/sp/keeper/msg_server.go +++ b/x/sp/keeper/msg_server.go @@ -152,7 +152,7 @@ func (k msgServer) CreateStorageProvider(goCtx context.Context, msg *types.MsgCr FreeReadQuota: msg.FreeReadQuota, } k.SetSpStoragePrice(ctx, spStoragePrice) - err = k.UpdateSecondarySpStorePrice(ctx) + err = k.UpdateGlobalSpStorePrice(ctx) if err != nil { return nil, err } @@ -327,7 +327,7 @@ func (k msgServer) UpdateSpStoragePrice(goCtx context.Context, msg *types.MsgUpd FreeReadQuota: msg.FreeReadQuota, } k.SetSpStoragePrice(ctx, spStorePrice) - err := k.UpdateSecondarySpStorePrice(ctx) + err := k.UpdateGlobalSpStorePrice(ctx) if err != nil { return nil, errors.Wrapf(err, "update secondary sp store price failed") } diff --git a/x/sp/keeper/sp_storage_price.go b/x/sp/keeper/sp_storage_price.go index 22f1242e9..c9f0ac3f9 100644 --- a/x/sp/keeper/sp_storage_price.go +++ b/x/sp/keeper/sp_storage_price.go @@ -21,11 +21,7 @@ func (k Keeper) SetSpStoragePrice(ctx sdk.Context, spStoragePrice types.SpStorag FreeReadQuota: spStoragePrice.FreeReadQuota, } store := prefix.NewStore(ctx.KVStore(k.storeKey), types.SpStoragePriceKeyPrefix) - key := types.SpStoragePriceKey( - spStoragePrice.SpId, - spStoragePrice.UpdateTimeSec, - ) - spStoragePrice.UpdateTimeSec = 0 + key := types.SpStoragePriceKey(spStoragePrice.SpId) spStoragePrice.SpId = 0 b := k.cdc.MustMarshal(&spStoragePrice) store.Set(key, b) @@ -36,21 +32,16 @@ func (k Keeper) SetSpStoragePrice(ctx sdk.Context, spStoragePrice types.SpStorag func (k Keeper) GetSpStoragePrice( ctx sdk.Context, spId uint32, - timestamp int64, ) (val types.SpStoragePrice, found bool) { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.SpStoragePriceKeyPrefix) - b := store.Get(types.SpStoragePriceKey( - spId, - timestamp, - )) + b := store.Get(types.SpStoragePriceKey(spId)) if b == nil { return val, false } k.cdc.MustUnmarshal(b, &val) val.SpId = spId - val.UpdateTimeSec = timestamp return val, true } @@ -64,99 +55,83 @@ func (k Keeper) GetAllSpStoragePrice(ctx sdk.Context) (list []types.SpStoragePri for ; iterator.Valid(); iterator.Next() { var val types.SpStoragePrice k.cdc.MustUnmarshal(iterator.Value(), &val) - spId, timestamp := types.ParseSpStoragePriceKey(iterator.Key()) + spId := types.ParseSpStoragePriceKey(iterator.Key()) val.SpId = spId - val.UpdateTimeSec = timestamp list = append(list, val) } return } -// GetSpStoragePriceByTime find the latest price before the given time -func (k Keeper) GetSpStoragePriceByTime( - ctx sdk.Context, - spId uint32, - timestamp int64, -) (val types.SpStoragePrice, err error) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.SpStoragePriceKeyPrefix) - - startKey := types.SpStoragePriceKey( - spId, - timestamp, - ) - iterator := store.ReverseIterator(nil, startKey) - defer iterator.Close() - if !iterator.Valid() { - return val, fmt.Errorf("no price found") +func (k Keeper) SetGlobalSpStorePrice(ctx sdk.Context, globalSpStorePrice types.GlobalSpStorePrice) { + event := &types.EventGlobalSpStorePriceUpdate{ + UpdateTimeSec: globalSpStorePrice.UpdateTimeSec, + PrimaryStorePrice: globalSpStorePrice.PrimaryStorePrice, + SecondaryStorePrice: globalSpStorePrice.SecondaryStorePrice, + ReadPrice: globalSpStorePrice.ReadPrice, } - - resSpId, resTimestamp := types.ParseSpStoragePriceKey(iterator.Key()) - if resSpId != spId { - return val, fmt.Errorf("no price found") - } - k.cdc.MustUnmarshal(iterator.Value(), &val) - val.SpId = spId - val.UpdateTimeSec = resTimestamp - - return val, nil -} - -func (k Keeper) SetSecondarySpStorePrice(ctx sdk.Context, secondarySpStorePrice types.SecondarySpStorePrice) { - event := &types.EventSecondarySpStorePriceUpdate{ - UpdateTimeSec: secondarySpStorePrice.UpdateTimeSec, - StorePrice: secondarySpStorePrice.StorePrice, - } - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.SecondarySpStorePriceKeyPrefix) - key := types.SecondarySpStorePriceKey( - secondarySpStorePrice.UpdateTimeSec, + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.GlobalSpStorePriceKeyPrefix) + key := types.GlobalSpStorePriceKey( + globalSpStorePrice.UpdateTimeSec, ) - secondarySpStorePrice.UpdateTimeSec = 0 - b := k.cdc.MustMarshal(&secondarySpStorePrice) + globalSpStorePrice.UpdateTimeSec = 0 + b := k.cdc.MustMarshal(&globalSpStorePrice) store.Set(key, b) _ = ctx.EventManager().EmitTypedEvents(event) } -// UpdateSecondarySpStorePrice calculate the price of secondary store by the average price of all sp store price -func (k Keeper) UpdateSecondarySpStorePrice(ctx sdk.Context) error { +// UpdateGlobalSpStorePrice calculate the global prices by the median price of all sp store price +func (k Keeper) UpdateGlobalSpStorePrice(ctx sdk.Context) error { sps := k.GetAllStorageProviders(ctx) current := ctx.BlockTime().Unix() - prices := make([]sdk.Dec, 0) + storePrices := make([]sdk.Dec, 0) + readPrices := make([]sdk.Dec, 0) for _, sp := range sps { if sp.Status != types.STATUS_IN_SERVICE { continue } - price, err := k.GetSpStoragePriceByTime(ctx, sp.Id, current+1) - if err != nil { - return err + price, found := k.GetSpStoragePrice(ctx, sp.Id) + if !found { + return fmt.Errorf("cannot find secondaryStorePrice for storage provider %d", sp.Id) } - prices = append(prices, price.StorePrice) + storePrices = append(storePrices, price.StorePrice) + readPrices = append(readPrices, price.ReadPrice) } - l := len(prices) + l := len(storePrices) if l == 0 { return nil } + primaryStorePrice := k.calculateMedian(storePrices) + secondaryStorePrice := k.SecondarySpStorePriceRatio(ctx).Mul(primaryStorePrice) + readPrice := k.calculateMedian(readPrices) + + globalSpStorePrice := types.GlobalSpStorePrice{ + PrimaryStorePrice: primaryStorePrice, + SecondaryStorePrice: secondaryStorePrice, + ReadPrice: readPrice, + UpdateTimeSec: current, + } + k.SetGlobalSpStorePrice(ctx, globalSpStorePrice) + return nil +} + +func (k Keeper) calculateMedian(prices []sdk.Dec) sdk.Dec { + l := len(prices) sort.Slice(prices, func(i, j int) bool { return prices[i].LT(prices[j]) }) - var median sdk.Dec + var storeMedian sdk.Dec if l%2 == 0 { - median = prices[l/2-1].Add(prices[l/2]).QuoInt64(2) + storeMedian = prices[l/2-1].Add(prices[l/2]).QuoInt64(2) } else { - median = prices[l/2] - } - price := k.SecondarySpStorePriceRatio(ctx).Mul(median) - secondarySpStorePrice := types.SecondarySpStorePrice{ - StorePrice: price, - UpdateTimeSec: current, + storeMedian = prices[l/2] } - k.SetSecondarySpStorePrice(ctx, secondarySpStorePrice) - return nil + return storeMedian } -func (k Keeper) GetSecondarySpStorePriceByTime(ctx sdk.Context, time int64) (val types.SecondarySpStorePrice, err error) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.SecondarySpStorePriceKeyPrefix) +func (k Keeper) GetGlobalSpStorePriceByTime(ctx sdk.Context, time int64) (val types.GlobalSpStorePrice, err error) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.GlobalSpStorePriceKeyPrefix) - startKey := types.SecondarySpStorePriceKey( + startKey := types.GlobalSpStorePriceKey( time, ) iterator := store.ReverseIterator(nil, startKey) @@ -166,7 +141,7 @@ func (k Keeper) GetSecondarySpStorePriceByTime(ctx sdk.Context, time int64) (val } k.cdc.MustUnmarshal(iterator.Value(), &val) - updateTimeSec := types.ParseSecondarySpStorePriceKey(iterator.Key()) + updateTimeSec := types.ParseGlobalSpStorePriceKey(iterator.Key()) val.UpdateTimeSec = updateTimeSec return val, nil } diff --git a/x/sp/keeper/sp_storage_price_test.go b/x/sp/keeper/sp_storage_price_test.go index 5a548b8bb..5fb304816 100644 --- a/x/sp/keeper/sp_storage_price_test.go +++ b/x/sp/keeper/sp_storage_price_test.go @@ -13,6 +13,10 @@ import ( func (s *KeeperTestSuite) TestGetSpStoragePriceByTime() { ctx := s.ctx.WithBlockTime(time.Unix(100, 0)) spId := uint32(10) + + _, found := s.spKeeper.GetSpStoragePrice(ctx, spId) + s.Require().True(!found) + spStoragePrice := types.SpStoragePrice{ SpId: spId, UpdateTimeSec: 1, @@ -20,6 +24,11 @@ func (s *KeeperTestSuite) TestGetSpStoragePriceByTime() { StorePrice: sdk.NewDec(100), } s.spKeeper.SetSpStoragePrice(ctx, spStoragePrice) + + price, found := s.spKeeper.GetSpStoragePrice(ctx, spId) + s.Require().True(found) + s.Require().True(reflect.DeepEqual(price, spStoragePrice)) + spStoragePrice2 := types.SpStoragePrice{ SpId: spId, UpdateTimeSec: 100, @@ -27,67 +36,47 @@ func (s *KeeperTestSuite) TestGetSpStoragePriceByTime() { StorePrice: sdk.NewDec(200), } s.spKeeper.SetSpStoragePrice(ctx, spStoragePrice2) - type args struct { - time int64 - } - tests := []struct { - name string - args args - wantVal types.SpStoragePrice - wantErr bool - }{ - {"test 0", args{time: 0}, types.SpStoragePrice{}, true}, - {"test 1", args{time: 1}, types.SpStoragePrice{}, true}, - {"test 2", args{time: 2}, spStoragePrice, false}, - {"test 100", args{time: 100}, spStoragePrice, false}, - {"test 101", args{time: 101}, spStoragePrice2, false}, - } - for _, tt := range tests { - s.T().Run(tt.name, func(t *testing.T) { - gotVal, err := s.spKeeper.GetSpStoragePriceByTime(ctx, spId, tt.args.time) - if (err != nil) != tt.wantErr { - t.Errorf("GetSpStoragePriceByTime() error = %v, wantErr %v", err, tt.wantErr) - return - } - if !reflect.DeepEqual(gotVal, tt.wantVal) { - t.Errorf("GetSpStoragePriceByTime() gotVal = %v, want %v", gotVal, tt.wantVal) - } - }) - } + price, found = s.spKeeper.GetSpStoragePrice(ctx, spId) + s.Require().True(found) + s.Require().True(reflect.DeepEqual(price, spStoragePrice2)) } -func (s *KeeperTestSuite) TestGetSecondarySpStorePriceByTime() { +func (s *KeeperTestSuite) TestGetGlobalSpStorePriceByTime() { keeper := s.spKeeper ctx := s.ctx - secondarySpStorePrice := types.SecondarySpStorePrice{ - UpdateTimeSec: 1, - StorePrice: sdk.NewDec(100), + secondarySpStorePrice := types.GlobalSpStorePrice{ + UpdateTimeSec: 1, + PrimaryStorePrice: sdk.NewDec(100), + SecondaryStorePrice: sdk.NewDec(40), + ReadPrice: sdk.NewDec(80), } - keeper.SetSecondarySpStorePrice(ctx, secondarySpStorePrice) - secondarySpStorePrice2 := types.SecondarySpStorePrice{ - UpdateTimeSec: 100, - StorePrice: sdk.NewDec(200), + keeper.SetGlobalSpStorePrice(ctx, secondarySpStorePrice) + secondarySpStorePrice2 := types.GlobalSpStorePrice{ + UpdateTimeSec: 100, + PrimaryStorePrice: sdk.NewDec(200), + SecondaryStorePrice: sdk.NewDec(70), + ReadPrice: sdk.NewDec(90), } - keeper.SetSecondarySpStorePrice(ctx, secondarySpStorePrice2) + keeper.SetGlobalSpStorePrice(ctx, secondarySpStorePrice2) type args struct { time int64 } tests := []struct { name string args args - wantVal types.SecondarySpStorePrice + wantVal types.GlobalSpStorePrice wantErr bool }{ - {"test 0", args{time: 0}, types.SecondarySpStorePrice{}, true}, - {"test 1", args{time: 1}, types.SecondarySpStorePrice{}, true}, + {"test 0", args{time: 0}, types.GlobalSpStorePrice{}, true}, + {"test 1", args{time: 1}, types.GlobalSpStorePrice{}, true}, {"test 2", args{time: 2}, secondarySpStorePrice, false}, {"test 100", args{time: 100}, secondarySpStorePrice, false}, {"test 101", args{time: 101}, secondarySpStorePrice2, false}, } for _, tt := range tests { s.T().Run(tt.name, func(t *testing.T) { - gotVal, err := keeper.GetSecondarySpStorePriceByTime(ctx, tt.args.time) + gotVal, err := keeper.GetGlobalSpStorePriceByTime(ctx, tt.args.time) if (err != nil) != tt.wantErr { t.Errorf("GetSpStoragePriceByTime() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/x/sp/types/events.pb.go b/x/sp/types/events.pb.go index ddded03fd..bd4ad58e4 100644 --- a/x/sp/types/events.pb.go +++ b/x/sp/types/events.pb.go @@ -420,25 +420,29 @@ func (m *EventSpStoragePriceUpdate) GetFreeReadQuota() uint64 { return 0 } -type EventSecondarySpStorePriceUpdate struct { +type EventGlobalSpStorePriceUpdate struct { // update time, in unix timestamp UpdateTimeSec int64 `protobuf:"varint,1,opt,name=update_time_sec,json=updateTimeSec,proto3" json:"update_time_sec,omitempty"` - // store price, in bnb wei per charge byte - StorePrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=store_price,json=storePrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"store_price"` + // read price, in bnb wei per charge byte + ReadPrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=read_price,json=readPrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"read_price"` + // primary store price, in bnb wei per charge byte + PrimaryStorePrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=primary_store_price,json=primaryStorePrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"primary_store_price"` + // secondary store price, in bnb wei per charge byte + SecondaryStorePrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=secondary_store_price,json=secondaryStorePrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"secondary_store_price"` } -func (m *EventSecondarySpStorePriceUpdate) Reset() { *m = EventSecondarySpStorePriceUpdate{} } -func (m *EventSecondarySpStorePriceUpdate) String() string { return proto.CompactTextString(m) } -func (*EventSecondarySpStorePriceUpdate) ProtoMessage() {} -func (*EventSecondarySpStorePriceUpdate) Descriptor() ([]byte, []int) { +func (m *EventGlobalSpStorePriceUpdate) Reset() { *m = EventGlobalSpStorePriceUpdate{} } +func (m *EventGlobalSpStorePriceUpdate) String() string { return proto.CompactTextString(m) } +func (*EventGlobalSpStorePriceUpdate) ProtoMessage() {} +func (*EventGlobalSpStorePriceUpdate) Descriptor() ([]byte, []int) { return fileDescriptor_685cbfa50fdf0841, []int{4} } -func (m *EventSecondarySpStorePriceUpdate) XXX_Unmarshal(b []byte) error { +func (m *EventGlobalSpStorePriceUpdate) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } -func (m *EventSecondarySpStorePriceUpdate) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { +func (m *EventGlobalSpStorePriceUpdate) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { - return xxx_messageInfo_EventSecondarySpStorePriceUpdate.Marshal(b, m, deterministic) + return xxx_messageInfo_EventGlobalSpStorePriceUpdate.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) @@ -448,19 +452,19 @@ func (m *EventSecondarySpStorePriceUpdate) XXX_Marshal(b []byte, deterministic b return b[:n], nil } } -func (m *EventSecondarySpStorePriceUpdate) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventSecondarySpStorePriceUpdate.Merge(m, src) +func (m *EventGlobalSpStorePriceUpdate) XXX_Merge(src proto.Message) { + xxx_messageInfo_EventGlobalSpStorePriceUpdate.Merge(m, src) } -func (m *EventSecondarySpStorePriceUpdate) XXX_Size() int { +func (m *EventGlobalSpStorePriceUpdate) XXX_Size() int { return m.Size() } -func (m *EventSecondarySpStorePriceUpdate) XXX_DiscardUnknown() { - xxx_messageInfo_EventSecondarySpStorePriceUpdate.DiscardUnknown(m) +func (m *EventGlobalSpStorePriceUpdate) XXX_DiscardUnknown() { + xxx_messageInfo_EventGlobalSpStorePriceUpdate.DiscardUnknown(m) } -var xxx_messageInfo_EventSecondarySpStorePriceUpdate proto.InternalMessageInfo +var xxx_messageInfo_EventGlobalSpStorePriceUpdate proto.InternalMessageInfo -func (m *EventSecondarySpStorePriceUpdate) GetUpdateTimeSec() int64 { +func (m *EventGlobalSpStorePriceUpdate) GetUpdateTimeSec() int64 { if m != nil { return m.UpdateTimeSec } @@ -545,63 +549,66 @@ func init() { proto.RegisterType((*EventEditStorageProvider)(nil), "greenfield.sp.EventEditStorageProvider") proto.RegisterType((*EventDeposit)(nil), "greenfield.sp.EventDeposit") proto.RegisterType((*EventSpStoragePriceUpdate)(nil), "greenfield.sp.EventSpStoragePriceUpdate") - proto.RegisterType((*EventSecondarySpStorePriceUpdate)(nil), "greenfield.sp.EventSecondarySpStorePriceUpdate") + proto.RegisterType((*EventGlobalSpStorePriceUpdate)(nil), "greenfield.sp.EventGlobalSpStorePriceUpdate") proto.RegisterType((*EventUpdateStorageProviderStatus)(nil), "greenfield.sp.EventUpdateStorageProviderStatus") } func init() { proto.RegisterFile("greenfield/sp/events.proto", fileDescriptor_685cbfa50fdf0841) } var fileDescriptor_685cbfa50fdf0841 = []byte{ - // 781 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x56, 0x41, 0x8f, 0x1b, 0x35, - 0x14, 0xde, 0xd9, 0x4d, 0xb2, 0x9b, 0x97, 0xa4, 0x8b, 0xa6, 0x45, 0xcc, 0x46, 0x6a, 0x1a, 0x05, - 0xa9, 0x8a, 0x90, 0x32, 0x51, 0xcb, 0xa1, 0x07, 0x10, 0x52, 0xb3, 0xe9, 0xa1, 0xe2, 0x02, 0x13, - 0xb8, 0x80, 0xd0, 0xc8, 0x33, 0x7e, 0x3b, 0xb5, 0x9a, 0xd8, 0xc6, 0x76, 0x52, 0xf2, 0x2f, 0x7a, - 0xe7, 0x17, 0x70, 0xe1, 0xd4, 0x23, 0x3f, 0xa0, 0xc7, 0xaa, 0x27, 0xc4, 0xa1, 0x42, 0xbb, 0x07, - 0xfe, 0x06, 0x1a, 0x8f, 0x27, 0x4d, 0xa2, 0x48, 0x11, 0xdd, 0xe5, 0x94, 0xd8, 0xef, 0x7d, 0xdf, - 0xfb, 0xfc, 0xfc, 0xcd, 0x93, 0xa1, 0x9d, 0x29, 0x44, 0x7e, 0xc1, 0x70, 0x4a, 0x87, 0x5a, 0x0e, - 0x71, 0x81, 0xdc, 0xe8, 0x50, 0x2a, 0x61, 0x84, 0xdf, 0x7a, 0x1f, 0x0b, 0xb5, 0x6c, 0x77, 0x52, - 0xa1, 0x67, 0x42, 0x0f, 0x13, 0xa2, 0x71, 0xb8, 0x78, 0x90, 0xa0, 0x21, 0x0f, 0x86, 0xa9, 0x60, - 0xbc, 0x48, 0x6f, 0x9f, 0x15, 0xf1, 0xd8, 0xae, 0x86, 0xc5, 0xc2, 0x85, 0xee, 0x64, 0x22, 0x13, - 0xc5, 0x7e, 0xfe, 0xaf, 0x04, 0x6c, 0xd6, 0x36, 0x4b, 0x89, 0x0e, 0xd0, 0xfb, 0xb5, 0x0a, 0xed, - 0x27, 0xb9, 0x96, 0x73, 0x85, 0xc4, 0xe0, 0xc4, 0x08, 0x45, 0x32, 0xfc, 0x46, 0x89, 0x05, 0xa3, - 0xa8, 0xfc, 0xdb, 0x50, 0xd5, 0x32, 0x66, 0x34, 0xf0, 0xba, 0x5e, 0xbf, 0x15, 0x55, 0xb4, 0x7c, - 0x4a, 0xfd, 0x47, 0x00, 0x5a, 0xc6, 0x84, 0x52, 0x85, 0x5a, 0x07, 0x87, 0x5d, 0xaf, 0x5f, 0x1f, - 0x05, 0x6f, 0x5f, 0x0d, 0xee, 0x38, 0x29, 0x8f, 0x8b, 0xc8, 0xc4, 0x28, 0xc6, 0xb3, 0xa8, 0xae, - 0xa5, 0xdb, 0xf0, 0x1f, 0xc3, 0xe9, 0xc5, 0x9c, 0x53, 0xc6, 0xb3, 0x15, 0xfa, 0x68, 0x0f, 0xfa, - 0x96, 0x03, 0x94, 0x14, 0x5f, 0x40, 0x53, 0x23, 0x99, 0xae, 0xf0, 0x95, 0x3d, 0xf8, 0x46, 0x9e, - 0x5d, 0x82, 0xcf, 0xe1, 0x23, 0x22, 0xa5, 0x12, 0x8b, 0x35, 0x82, 0xea, 0x1e, 0x82, 0xd3, 0x12, - 0x51, 0x92, 0x3c, 0x02, 0xc8, 0xd2, 0x15, 0xbc, 0xb6, 0xef, 0xf4, 0x59, 0x5a, 0x02, 0x9f, 0xc2, - 0xed, 0x19, 0x61, 0xdc, 0x20, 0x27, 0x3c, 0xc5, 0x15, 0xc3, 0xf1, 0x1e, 0x06, 0x7f, 0x0d, 0x54, - 0x52, 0xb5, 0xe1, 0x04, 0x39, 0x95, 0x82, 0x71, 0x13, 0x9c, 0xe4, 0xf8, 0x68, 0xb5, 0xf6, 0xbf, - 0x82, 0x96, 0x11, 0x86, 0x4c, 0x63, 0x8a, 0x52, 0x68, 0x66, 0x82, 0x7a, 0xd7, 0xeb, 0x37, 0x1e, - 0x9e, 0x85, 0x8e, 0x3d, 0x77, 0x55, 0xe8, 0x5c, 0x15, 0x9e, 0x0b, 0xc6, 0xa3, 0xa6, 0xcd, 0x1f, - 0x17, 0xe9, 0xfe, 0x00, 0x6a, 0xda, 0x10, 0x33, 0xd7, 0x01, 0x74, 0xbd, 0xfe, 0xad, 0x87, 0x1f, - 0x87, 0x1b, 0xee, 0x0c, 0x27, 0x36, 0x18, 0xb9, 0x24, 0x7f, 0x04, 0x0d, 0x8a, 0x3a, 0x55, 0x4c, - 0x1a, 0x26, 0x78, 0xd0, 0xb0, 0xc5, 0xda, 0x5b, 0x98, 0xf1, 0xfb, 0x8c, 0x51, 0xe5, 0xf5, 0xbb, - 0x7b, 0x07, 0xd1, 0x3a, 0xc8, 0xff, 0x04, 0x8e, 0x93, 0xa9, 0x8e, 0x9f, 0xe3, 0x32, 0x68, 0xda, - 0xd3, 0xd4, 0x92, 0xa9, 0xfe, 0x1a, 0x97, 0xbd, 0x7f, 0x8e, 0x20, 0xb0, 0xee, 0x7c, 0x42, 0x99, - 0xf9, 0x7f, 0xbd, 0xb9, 0xde, 0xd2, 0xa3, 0xad, 0x96, 0x6e, 0x9d, 0xb1, 0xf2, 0x21, 0x67, 0xdc, - 0x36, 0x6e, 0xf5, 0xba, 0xc6, 0xad, 0x5d, 0xcf, 0xb8, 0xc7, 0xd7, 0x36, 0xee, 0xc9, 0x07, 0x18, - 0x77, 0xed, 0xa6, 0xeb, 0x1b, 0x37, 0xfd, 0xd2, 0x83, 0xa6, 0xbd, 0xe9, 0xd2, 0x86, 0x3b, 0x66, - 0x85, 0xf7, 0x1f, 0x67, 0x45, 0x00, 0xc7, 0xe5, 0x37, 0x60, 0x8d, 0x10, 0x95, 0x4b, 0xff, 0xd3, - 0xed, 0x6f, 0xa4, 0xb8, 0xf1, 0x8d, 0x0f, 0xa1, 0xf7, 0xc7, 0x21, 0x9c, 0x59, 0x49, 0x13, 0xb9, - 0xb2, 0x1e, 0x4b, 0xf1, 0x7b, 0x49, 0x89, 0xc1, 0xdd, 0xee, 0xbb, 0x0f, 0xa7, 0x73, 0x1b, 0x8e, - 0x0d, 0x9b, 0x61, 0xac, 0x31, 0xb5, 0x95, 0x8f, 0xa2, 0x56, 0xb1, 0xfd, 0x1d, 0x9b, 0xe1, 0x04, - 0x53, 0xff, 0x47, 0x00, 0x85, 0x84, 0xc6, 0x32, 0x27, 0x74, 0x33, 0xf0, 0xcb, 0xdc, 0x33, 0x7f, - 0xbd, 0xbb, 0x77, 0x3f, 0x63, 0xe6, 0xd9, 0x3c, 0x09, 0x53, 0x31, 0x73, 0xb3, 0xdd, 0xfd, 0x0c, - 0x34, 0x7d, 0xee, 0x66, 0xf7, 0x18, 0xd3, 0xb7, 0xaf, 0x06, 0xe0, 0xba, 0x30, 0xc6, 0x34, 0xaa, - 0xe7, 0x7c, 0x56, 0x5f, 0x2e, 0xe2, 0x42, 0x21, 0xc6, 0xb6, 0xc2, 0xcf, 0x73, 0x61, 0x88, 0x75, - 0x6c, 0x25, 0x6a, 0xe5, 0xdb, 0x11, 0x12, 0xfa, 0x6d, 0xbe, 0xe9, 0xff, 0x04, 0x0d, 0x6d, 0x84, - 0x42, 0xa7, 0xa2, 0x7a, 0x03, 0x2a, 0xc0, 0x12, 0x5a, 0x19, 0xbd, 0xdf, 0x3c, 0xe8, 0x16, 0xed, - 0xc3, 0x54, 0x70, 0x4a, 0xd4, 0xb2, 0xe8, 0xe3, 0x46, 0x17, 0x77, 0x34, 0xcc, 0xdb, 0xd5, 0xb0, - 0x2d, 0xad, 0x87, 0x37, 0xac, 0xf5, 0xf7, 0x52, 0x6b, 0x21, 0x6b, 0x6b, 0xd2, 0x14, 0x13, 0xef, - 0x86, 0xe7, 0xcd, 0x5d, 0x00, 0xa9, 0x30, 0x76, 0xa3, 0xb6, 0xf0, 0x5f, 0x5d, 0x2a, 0x74, 0xc5, - 0xee, 0x02, 0x70, 0x7c, 0x51, 0x86, 0x2b, 0x45, 0x98, 0xe3, 0x8b, 0x22, 0x3c, 0x1a, 0xbf, 0xbe, - 0xec, 0x78, 0x6f, 0x2e, 0x3b, 0xde, 0xdf, 0x97, 0x1d, 0xef, 0xe5, 0x55, 0xe7, 0xe0, 0xcd, 0x55, - 0xe7, 0xe0, 0xcf, 0xab, 0xce, 0xc1, 0x0f, 0x9f, 0xad, 0x35, 0x23, 0xe1, 0xc9, 0x20, 0x7d, 0x46, - 0x18, 0x1f, 0xae, 0x3d, 0x00, 0x7e, 0x59, 0x3d, 0x01, 0x92, 0x9a, 0x7d, 0x03, 0x7c, 0xfe, 0x6f, - 0x00, 0x00, 0x00, 0xff, 0xff, 0xfc, 0xe5, 0x66, 0xee, 0x9c, 0x08, 0x00, 0x00, + // 819 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x56, 0xcd, 0x6e, 0x1b, 0x37, + 0x10, 0xf6, 0x5a, 0x3f, 0xb6, 0x46, 0x56, 0xdc, 0xae, 0x13, 0x74, 0x2d, 0xc0, 0x8a, 0xa0, 0x02, + 0x81, 0x51, 0x40, 0x12, 0x92, 0x1e, 0x72, 0x68, 0x51, 0x20, 0xb6, 0x82, 0x22, 0xe8, 0xa5, 0x5d, + 0xb5, 0x97, 0x16, 0xc5, 0x82, 0xbb, 0x1c, 0x6f, 0x88, 0x48, 0x24, 0x4b, 0x52, 0x4e, 0x7d, 0xef, + 0x03, 0xe4, 0xde, 0x77, 0xe8, 0x29, 0xc7, 0x3e, 0x40, 0x8e, 0x41, 0x4e, 0x45, 0x0f, 0x41, 0x61, + 0x1f, 0xfa, 0x1a, 0xc5, 0x72, 0xb9, 0xd2, 0x4a, 0x30, 0x20, 0xd4, 0x56, 0x4e, 0x36, 0x39, 0xfc, + 0xbe, 0x19, 0x7e, 0xf3, 0x71, 0xb4, 0xd0, 0x4e, 0x15, 0x22, 0x3f, 0x63, 0x38, 0xa1, 0x43, 0x2d, + 0x87, 0x78, 0x8e, 0xdc, 0xe8, 0x81, 0x54, 0xc2, 0x08, 0xbf, 0xb5, 0x88, 0x0d, 0xb4, 0x6c, 0x77, + 0x12, 0xa1, 0xa7, 0x42, 0x0f, 0x63, 0xa2, 0x71, 0x78, 0xfe, 0x30, 0x46, 0x43, 0x1e, 0x0e, 0x13, + 0xc1, 0x78, 0x7e, 0xbc, 0x7d, 0x98, 0xc7, 0x23, 0xbb, 0x1a, 0xe6, 0x0b, 0x17, 0xba, 0x9b, 0x8a, + 0x54, 0xe4, 0xfb, 0xd9, 0x7f, 0x05, 0x60, 0x39, 0xb7, 0xb9, 0x90, 0xe8, 0x00, 0xbd, 0xdf, 0x6b, + 0xd0, 0x7e, 0x9a, 0xd5, 0x72, 0xaa, 0x90, 0x18, 0x1c, 0x1b, 0xa1, 0x48, 0x8a, 0xdf, 0x2a, 0x71, + 0xce, 0x28, 0x2a, 0xff, 0x00, 0x6a, 0x5a, 0x46, 0x8c, 0x06, 0x5e, 0xd7, 0x3b, 0x6e, 0x85, 0x55, + 0x2d, 0x9f, 0x51, 0xff, 0x31, 0x80, 0x96, 0x11, 0xa1, 0x54, 0xa1, 0xd6, 0xc1, 0x76, 0xd7, 0x3b, + 0x6e, 0x9c, 0x04, 0xef, 0x5e, 0xf7, 0xef, 0xba, 0x52, 0x9e, 0xe4, 0x91, 0xb1, 0x51, 0x8c, 0xa7, + 0x61, 0x43, 0x4b, 0xb7, 0xe1, 0x3f, 0x81, 0xfd, 0xb3, 0x19, 0xa7, 0x8c, 0xa7, 0x73, 0x74, 0x65, + 0x0d, 0xfa, 0x8e, 0x03, 0x14, 0x14, 0x5f, 0xc0, 0x9e, 0x46, 0x32, 0x99, 0xe3, 0xab, 0x6b, 0xf0, + 0xcd, 0xec, 0x74, 0x01, 0x3e, 0x85, 0x8f, 0x88, 0x94, 0x4a, 0x9c, 0x97, 0x08, 0x6a, 0x6b, 0x08, + 0xf6, 0x0b, 0x44, 0x41, 0xf2, 0x18, 0x20, 0x4d, 0xe6, 0xf0, 0xfa, 0xba, 0xdb, 0xa7, 0x49, 0x01, + 0x7c, 0x06, 0x07, 0x53, 0xc2, 0xb8, 0x41, 0x4e, 0x78, 0x82, 0x73, 0x86, 0x9d, 0x35, 0x0c, 0x7e, + 0x09, 0x54, 0x50, 0xb5, 0x61, 0x17, 0x39, 0x95, 0x82, 0x71, 0x13, 0xec, 0x66, 0xf8, 0x70, 0xbe, + 0xf6, 0xbf, 0x82, 0x96, 0x11, 0x86, 0x4c, 0x22, 0x8a, 0x52, 0x68, 0x66, 0x82, 0x46, 0xd7, 0x3b, + 0x6e, 0x3e, 0x3a, 0x1c, 0x38, 0xf6, 0xcc, 0x55, 0x03, 0xe7, 0xaa, 0xc1, 0xa9, 0x60, 0x3c, 0xdc, + 0xb3, 0xe7, 0x47, 0xf9, 0x71, 0xbf, 0x0f, 0x75, 0x6d, 0x88, 0x99, 0xe9, 0x00, 0xba, 0xde, 0xf1, + 0x9d, 0x47, 0xf7, 0x06, 0x4b, 0xee, 0x1c, 0x8c, 0x6d, 0x30, 0x74, 0x87, 0xfc, 0x13, 0x68, 0x52, + 0xd4, 0x89, 0x62, 0xd2, 0x30, 0xc1, 0x83, 0xa6, 0x4d, 0xd6, 0x5e, 0xc1, 0x8c, 0x16, 0x27, 0x4e, + 0xaa, 0x6f, 0xde, 0xdf, 0xdf, 0x0a, 0xcb, 0x20, 0xff, 0x13, 0xd8, 0x89, 0x27, 0x3a, 0x7a, 0x81, + 0x17, 0xc1, 0x9e, 0xbd, 0x4d, 0x3d, 0x9e, 0xe8, 0x6f, 0xf0, 0xa2, 0xf7, 0x6f, 0x05, 0x02, 0xeb, + 0xce, 0xa7, 0x94, 0x99, 0x0f, 0xeb, 0xcd, 0xb2, 0xa4, 0x95, 0x15, 0x49, 0x57, 0xee, 0x58, 0xbd, + 0xc9, 0x1d, 0x57, 0x8d, 0x5b, 0xbb, 0xad, 0x71, 0xeb, 0xb7, 0x33, 0xee, 0xce, 0xad, 0x8d, 0xbb, + 0x7b, 0x03, 0xe3, 0x96, 0x3a, 0xdd, 0x58, 0xea, 0xf4, 0x2b, 0x0f, 0xf6, 0x6c, 0xa7, 0x0b, 0x1b, + 0x5e, 0x33, 0x2b, 0xbc, 0xff, 0x39, 0x2b, 0x02, 0xd8, 0x29, 0xde, 0x80, 0x35, 0x42, 0x58, 0x2c, + 0xfd, 0x4f, 0x57, 0xdf, 0x48, 0xde, 0xf1, 0xa5, 0x87, 0xd0, 0xfb, 0x73, 0x1b, 0x0e, 0x6d, 0x49, + 0x63, 0x39, 0xb7, 0x1e, 0x4b, 0xf0, 0x07, 0x49, 0x89, 0xc1, 0xeb, 0xdd, 0xf7, 0x00, 0xf6, 0x67, + 0x36, 0x1c, 0x19, 0x36, 0xc5, 0x48, 0x63, 0x62, 0x33, 0x57, 0xc2, 0x56, 0xbe, 0xfd, 0x3d, 0x9b, + 0xe2, 0x18, 0x13, 0xff, 0x27, 0x00, 0x85, 0x84, 0x46, 0x32, 0x23, 0x74, 0x33, 0xf0, 0xcb, 0xcc, + 0x33, 0x7f, 0xbf, 0xbf, 0xff, 0x20, 0x65, 0xe6, 0xf9, 0x2c, 0x1e, 0x24, 0x62, 0xea, 0x66, 0xbb, + 0xfb, 0xd3, 0xd7, 0xf4, 0x85, 0x9b, 0xdd, 0x23, 0x4c, 0xde, 0xbd, 0xee, 0x83, 0x53, 0x61, 0x84, + 0x49, 0xd8, 0xc8, 0xf8, 0x6c, 0x7d, 0x59, 0x11, 0x67, 0x0a, 0x31, 0xb2, 0x19, 0x7e, 0x99, 0x09, + 0x43, 0xac, 0x63, 0xab, 0x61, 0x2b, 0xdb, 0x0e, 0x91, 0xd0, 0xef, 0xb2, 0x4d, 0xff, 0x67, 0x68, + 0x6a, 0x23, 0x14, 0xba, 0x2a, 0x6a, 0x1b, 0xa8, 0x02, 0x2c, 0xa1, 0x2d, 0xa3, 0xf7, 0x5b, 0x05, + 0x8e, 0xac, 0x7c, 0x5f, 0x4f, 0x44, 0x4c, 0x26, 0xb9, 0x88, 0x4b, 0x12, 0x5e, 0xa3, 0x96, 0xb7, + 0x5e, 0xad, 0xed, 0xcd, 0xaa, 0x35, 0x81, 0x03, 0xa9, 0xd8, 0x94, 0xa8, 0x8b, 0xa8, 0xac, 0xc6, + 0x26, 0x7a, 0xf2, 0xb1, 0x23, 0x5e, 0x5c, 0xdc, 0x97, 0x70, 0x4f, 0x63, 0x22, 0x38, 0x5d, 0xcd, + 0x57, 0xdd, 0x40, 0xbe, 0x83, 0x39, 0xf5, 0x22, 0x63, 0xef, 0x0f, 0x0f, 0xba, 0xb6, 0x0d, 0xb9, + 0xe8, 0x2b, 0x43, 0x34, 0x1f, 0xe6, 0x1b, 0x1e, 0xa5, 0x47, 0x00, 0x52, 0x61, 0xe4, 0x7e, 0x45, + 0xf2, 0xa7, 0xd5, 0x90, 0x0a, 0x5d, 0xb2, 0x23, 0x00, 0x8e, 0x2f, 0x8b, 0x70, 0x35, 0x0f, 0x73, + 0x7c, 0x99, 0x87, 0x4f, 0x46, 0x6f, 0x2e, 0x3b, 0xde, 0xdb, 0xcb, 0x8e, 0xf7, 0xcf, 0x65, 0xc7, + 0x7b, 0x75, 0xd5, 0xd9, 0x7a, 0x7b, 0xd5, 0xd9, 0xfa, 0xeb, 0xaa, 0xb3, 0xf5, 0xe3, 0x67, 0x25, + 0x55, 0x62, 0x1e, 0xf7, 0x93, 0xe7, 0x84, 0xf1, 0x61, 0xe9, 0xdb, 0xe6, 0xd7, 0xf9, 0xd7, 0x4d, + 0x5c, 0xb7, 0x9f, 0x37, 0x9f, 0xff, 0x17, 0x00, 0x00, 0xff, 0xff, 0xdb, 0x8d, 0xb2, 0x3d, 0x77, + 0x09, 0x00, 0x00, } func (m *EventCreateStorageProvider) Marshal() (dAtA []byte, err error) { @@ -904,7 +911,7 @@ func (m *EventSpStoragePriceUpdate) MarshalToSizedBuffer(dAtA []byte) (int, erro return len(dAtA) - i, nil } -func (m *EventSecondarySpStorePriceUpdate) Marshal() (dAtA []byte, err error) { +func (m *EventGlobalSpStorePriceUpdate) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -914,20 +921,40 @@ func (m *EventSecondarySpStorePriceUpdate) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *EventSecondarySpStorePriceUpdate) MarshalTo(dAtA []byte) (int, error) { +func (m *EventGlobalSpStorePriceUpdate) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *EventSecondarySpStorePriceUpdate) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *EventGlobalSpStorePriceUpdate) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l { - size := m.StorePrice.Size() + size := m.SecondaryStorePrice.Size() i -= size - if _, err := m.StorePrice.MarshalTo(dAtA[i:]); err != nil { + if _, err := m.SecondaryStorePrice.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintEvents(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + { + size := m.PrimaryStorePrice.Size() + i -= size + if _, err := m.PrimaryStorePrice.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintEvents(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + { + size := m.ReadPrice.Size() + i -= size + if _, err := m.ReadPrice.MarshalTo(dAtA[i:]); err != nil { return 0, err } i = encodeVarintEvents(dAtA, i, uint64(size)) @@ -1140,7 +1167,7 @@ func (m *EventSpStoragePriceUpdate) Size() (n int) { return n } -func (m *EventSecondarySpStorePriceUpdate) Size() (n int) { +func (m *EventGlobalSpStorePriceUpdate) Size() (n int) { if m == nil { return 0 } @@ -1149,7 +1176,11 @@ func (m *EventSecondarySpStorePriceUpdate) Size() (n int) { if m.UpdateTimeSec != 0 { n += 1 + sovEvents(uint64(m.UpdateTimeSec)) } - l = m.StorePrice.Size() + l = m.ReadPrice.Size() + n += 1 + l + sovEvents(uint64(l)) + l = m.PrimaryStorePrice.Size() + n += 1 + l + sovEvents(uint64(l)) + l = m.SecondaryStorePrice.Size() n += 1 + l + sovEvents(uint64(l)) return n } @@ -2244,7 +2275,7 @@ func (m *EventSpStoragePriceUpdate) Unmarshal(dAtA []byte) error { } return nil } -func (m *EventSecondarySpStorePriceUpdate) Unmarshal(dAtA []byte) error { +func (m *EventGlobalSpStorePriceUpdate) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2267,10 +2298,10 @@ func (m *EventSecondarySpStorePriceUpdate) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: EventSecondarySpStorePriceUpdate: wiretype end group for non-group") + return fmt.Errorf("proto: EventGlobalSpStorePriceUpdate: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: EventSecondarySpStorePriceUpdate: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: EventGlobalSpStorePriceUpdate: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -2294,7 +2325,7 @@ func (m *EventSecondarySpStorePriceUpdate) Unmarshal(dAtA []byte) error { } case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field StorePrice", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ReadPrice", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -2322,7 +2353,75 @@ func (m *EventSecondarySpStorePriceUpdate) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.StorePrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.ReadPrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PrimaryStorePrice", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvents + } + 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 ErrInvalidLengthEvents + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthEvents + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.PrimaryStorePrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SecondaryStorePrice", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvents + } + 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 ErrInvalidLengthEvents + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthEvents + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.SecondaryStorePrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex diff --git a/x/sp/types/keys.go b/x/sp/types/keys.go index 82d705f66..e9ca69c2e 100644 --- a/x/sp/types/keys.go +++ b/x/sp/types/keys.go @@ -31,7 +31,7 @@ var ( StorageProviderByApprovalAddrKey = []byte{0x26} // prefix for each key to a storage provider index, by approval address StorageProviderByGcAddrKey = []byte{0x27} // prefix for each key to a storage provider index, by gc address SpStoragePriceKeyPrefix = []byte{0x28} - SecondarySpStorePriceKeyPrefix = []byte{0x29} + GlobalSpStorePriceKeyPrefix = []byte{0x29} StorageProviderByBlsPubKeyKey = []byte{0x30} // prefix for each key to a storage provider index, by bls pub key StorageProviderSequenceKey = []byte{0x31} @@ -98,30 +98,18 @@ func MustMarshalStorageProvider(cdc codec.BinaryCodec, sp *StorageProvider) []by return cdc.MustMarshal(sp) } -func SpStoragePriceKey( - spId uint32, - timestamp int64, -) []byte { +func SpStoragePriceKey(spId uint32) []byte { idBytes := make([]byte, 4) binary.BigEndian.PutUint32(idBytes, spId) - - timeBytes := make([]byte, 8) - binary.BigEndian.PutUint64(timeBytes, uint64(timestamp)) - - var key []byte - key = append(key, idBytes...) - key = append(key, timeBytes...) - - return key + return idBytes } -func ParseSpStoragePriceKey(key []byte) (spId uint32, timestamp int64) { +func ParseSpStoragePriceKey(key []byte) (spId uint32) { spId = binary.BigEndian.Uint32(key[0:4]) - timestamp = int64(binary.BigEndian.Uint64(key[4:])) return } -func SecondarySpStorePriceKey( +func GlobalSpStorePriceKey( timestamp int64, ) []byte { timeBytes := make([]byte, 8) @@ -129,7 +117,7 @@ func SecondarySpStorePriceKey( return timeBytes } -func ParseSecondarySpStorePriceKey(key []byte) (timestamp int64) { +func ParseGlobalSpStorePriceKey(key []byte) (timestamp int64) { timestamp = int64(binary.BigEndian.Uint64(key)) return } diff --git a/x/sp/types/query.pb.go b/x/sp/types/query.pb.go index 5f078b2d7..f471c1987 100644 --- a/x/sp/types/query.pb.go +++ b/x/sp/types/query.pb.go @@ -213,25 +213,23 @@ func (m *QueryStorageProvidersResponse) GetPagination() *query.PageResponse { return nil } -type QueryGetSpStoragePriceByTimeRequest struct { +type QuerySpStoragePriceRequest struct { // operator address of sp SpAddr string `protobuf:"bytes,1,opt,name=sp_addr,json=spAddr,proto3" json:"sp_addr,omitempty"` - // unix timestamp in seconds. If it's 0, it will return the latest price. - Timestamp int64 `protobuf:"varint,2,opt,name=timestamp,proto3" json:"timestamp,omitempty"` } -func (m *QueryGetSpStoragePriceByTimeRequest) Reset() { *m = QueryGetSpStoragePriceByTimeRequest{} } -func (m *QueryGetSpStoragePriceByTimeRequest) String() string { return proto.CompactTextString(m) } -func (*QueryGetSpStoragePriceByTimeRequest) ProtoMessage() {} -func (*QueryGetSpStoragePriceByTimeRequest) Descriptor() ([]byte, []int) { +func (m *QuerySpStoragePriceRequest) Reset() { *m = QuerySpStoragePriceRequest{} } +func (m *QuerySpStoragePriceRequest) String() string { return proto.CompactTextString(m) } +func (*QuerySpStoragePriceRequest) ProtoMessage() {} +func (*QuerySpStoragePriceRequest) Descriptor() ([]byte, []int) { return fileDescriptor_48dd9c8aad3b7a6d, []int{4} } -func (m *QueryGetSpStoragePriceByTimeRequest) XXX_Unmarshal(b []byte) error { +func (m *QuerySpStoragePriceRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } -func (m *QueryGetSpStoragePriceByTimeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { +func (m *QuerySpStoragePriceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { - return xxx_messageInfo_QueryGetSpStoragePriceByTimeRequest.Marshal(b, m, deterministic) + return xxx_messageInfo_QuerySpStoragePriceRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) @@ -241,48 +239,41 @@ func (m *QueryGetSpStoragePriceByTimeRequest) XXX_Marshal(b []byte, deterministi return b[:n], nil } } -func (m *QueryGetSpStoragePriceByTimeRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryGetSpStoragePriceByTimeRequest.Merge(m, src) +func (m *QuerySpStoragePriceRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QuerySpStoragePriceRequest.Merge(m, src) } -func (m *QueryGetSpStoragePriceByTimeRequest) XXX_Size() int { +func (m *QuerySpStoragePriceRequest) XXX_Size() int { return m.Size() } -func (m *QueryGetSpStoragePriceByTimeRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryGetSpStoragePriceByTimeRequest.DiscardUnknown(m) +func (m *QuerySpStoragePriceRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QuerySpStoragePriceRequest.DiscardUnknown(m) } -var xxx_messageInfo_QueryGetSpStoragePriceByTimeRequest proto.InternalMessageInfo +var xxx_messageInfo_QuerySpStoragePriceRequest proto.InternalMessageInfo -func (m *QueryGetSpStoragePriceByTimeRequest) GetSpAddr() string { +func (m *QuerySpStoragePriceRequest) GetSpAddr() string { if m != nil { return m.SpAddr } return "" } -func (m *QueryGetSpStoragePriceByTimeRequest) GetTimestamp() int64 { - if m != nil { - return m.Timestamp - } - return 0 -} - -type QueryGetSpStoragePriceByTimeResponse struct { +type QuerySpStoragePriceResponse struct { SpStoragePrice SpStoragePrice `protobuf:"bytes,1,opt,name=sp_storage_price,json=spStoragePrice,proto3" json:"sp_storage_price"` } -func (m *QueryGetSpStoragePriceByTimeResponse) Reset() { *m = QueryGetSpStoragePriceByTimeResponse{} } -func (m *QueryGetSpStoragePriceByTimeResponse) String() string { return proto.CompactTextString(m) } -func (*QueryGetSpStoragePriceByTimeResponse) ProtoMessage() {} -func (*QueryGetSpStoragePriceByTimeResponse) Descriptor() ([]byte, []int) { +func (m *QuerySpStoragePriceResponse) Reset() { *m = QuerySpStoragePriceResponse{} } +func (m *QuerySpStoragePriceResponse) String() string { return proto.CompactTextString(m) } +func (*QuerySpStoragePriceResponse) ProtoMessage() {} +func (*QuerySpStoragePriceResponse) Descriptor() ([]byte, []int) { return fileDescriptor_48dd9c8aad3b7a6d, []int{5} } -func (m *QueryGetSpStoragePriceByTimeResponse) XXX_Unmarshal(b []byte) error { +func (m *QuerySpStoragePriceResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } -func (m *QueryGetSpStoragePriceByTimeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { +func (m *QuerySpStoragePriceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { - return xxx_messageInfo_QueryGetSpStoragePriceByTimeResponse.Marshal(b, m, deterministic) + return xxx_messageInfo_QuerySpStoragePriceResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) @@ -292,46 +283,42 @@ func (m *QueryGetSpStoragePriceByTimeResponse) XXX_Marshal(b []byte, determinist return b[:n], nil } } -func (m *QueryGetSpStoragePriceByTimeResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryGetSpStoragePriceByTimeResponse.Merge(m, src) +func (m *QuerySpStoragePriceResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QuerySpStoragePriceResponse.Merge(m, src) } -func (m *QueryGetSpStoragePriceByTimeResponse) XXX_Size() int { +func (m *QuerySpStoragePriceResponse) XXX_Size() int { return m.Size() } -func (m *QueryGetSpStoragePriceByTimeResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryGetSpStoragePriceByTimeResponse.DiscardUnknown(m) +func (m *QuerySpStoragePriceResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QuerySpStoragePriceResponse.DiscardUnknown(m) } -var xxx_messageInfo_QueryGetSpStoragePriceByTimeResponse proto.InternalMessageInfo +var xxx_messageInfo_QuerySpStoragePriceResponse proto.InternalMessageInfo -func (m *QueryGetSpStoragePriceByTimeResponse) GetSpStoragePrice() SpStoragePrice { +func (m *QuerySpStoragePriceResponse) GetSpStoragePrice() SpStoragePrice { if m != nil { return m.SpStoragePrice } return SpStoragePrice{} } -type QueryGetSecondarySpStorePriceByTimeRequest struct { +type QueryGlobalSpStorePriceByTimeRequest struct { // unix timestamp in seconds. If it's 0, it will return the latest price. Timestamp int64 `protobuf:"varint,1,opt,name=timestamp,proto3" json:"timestamp,omitempty"` } -func (m *QueryGetSecondarySpStorePriceByTimeRequest) Reset() { - *m = QueryGetSecondarySpStorePriceByTimeRequest{} -} -func (m *QueryGetSecondarySpStorePriceByTimeRequest) String() string { - return proto.CompactTextString(m) -} -func (*QueryGetSecondarySpStorePriceByTimeRequest) ProtoMessage() {} -func (*QueryGetSecondarySpStorePriceByTimeRequest) Descriptor() ([]byte, []int) { +func (m *QueryGlobalSpStorePriceByTimeRequest) Reset() { *m = QueryGlobalSpStorePriceByTimeRequest{} } +func (m *QueryGlobalSpStorePriceByTimeRequest) String() string { return proto.CompactTextString(m) } +func (*QueryGlobalSpStorePriceByTimeRequest) ProtoMessage() {} +func (*QueryGlobalSpStorePriceByTimeRequest) Descriptor() ([]byte, []int) { return fileDescriptor_48dd9c8aad3b7a6d, []int{6} } -func (m *QueryGetSecondarySpStorePriceByTimeRequest) XXX_Unmarshal(b []byte) error { +func (m *QueryGlobalSpStorePriceByTimeRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } -func (m *QueryGetSecondarySpStorePriceByTimeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { +func (m *QueryGlobalSpStorePriceByTimeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { - return xxx_messageInfo_QueryGetSecondarySpStorePriceByTimeRequest.Marshal(b, m, deterministic) + return xxx_messageInfo_QueryGlobalSpStorePriceByTimeRequest.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) @@ -341,45 +328,41 @@ func (m *QueryGetSecondarySpStorePriceByTimeRequest) XXX_Marshal(b []byte, deter return b[:n], nil } } -func (m *QueryGetSecondarySpStorePriceByTimeRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryGetSecondarySpStorePriceByTimeRequest.Merge(m, src) +func (m *QueryGlobalSpStorePriceByTimeRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryGlobalSpStorePriceByTimeRequest.Merge(m, src) } -func (m *QueryGetSecondarySpStorePriceByTimeRequest) XXX_Size() int { +func (m *QueryGlobalSpStorePriceByTimeRequest) XXX_Size() int { return m.Size() } -func (m *QueryGetSecondarySpStorePriceByTimeRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryGetSecondarySpStorePriceByTimeRequest.DiscardUnknown(m) +func (m *QueryGlobalSpStorePriceByTimeRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryGlobalSpStorePriceByTimeRequest.DiscardUnknown(m) } -var xxx_messageInfo_QueryGetSecondarySpStorePriceByTimeRequest proto.InternalMessageInfo +var xxx_messageInfo_QueryGlobalSpStorePriceByTimeRequest proto.InternalMessageInfo -func (m *QueryGetSecondarySpStorePriceByTimeRequest) GetTimestamp() int64 { +func (m *QueryGlobalSpStorePriceByTimeRequest) GetTimestamp() int64 { if m != nil { return m.Timestamp } return 0 } -type QueryGetSecondarySpStorePriceByTimeResponse struct { - SecondarySpStorePrice SecondarySpStorePrice `protobuf:"bytes,1,opt,name=secondary_sp_store_price,json=secondarySpStorePrice,proto3" json:"secondary_sp_store_price"` +type QueryGlobalSpStorePriceByTimeResponse struct { + GlobalSpStorePrice GlobalSpStorePrice `protobuf:"bytes,1,opt,name=global_sp_store_price,json=globalSpStorePrice,proto3" json:"global_sp_store_price"` } -func (m *QueryGetSecondarySpStorePriceByTimeResponse) Reset() { - *m = QueryGetSecondarySpStorePriceByTimeResponse{} -} -func (m *QueryGetSecondarySpStorePriceByTimeResponse) String() string { - return proto.CompactTextString(m) -} -func (*QueryGetSecondarySpStorePriceByTimeResponse) ProtoMessage() {} -func (*QueryGetSecondarySpStorePriceByTimeResponse) Descriptor() ([]byte, []int) { +func (m *QueryGlobalSpStorePriceByTimeResponse) Reset() { *m = QueryGlobalSpStorePriceByTimeResponse{} } +func (m *QueryGlobalSpStorePriceByTimeResponse) String() string { return proto.CompactTextString(m) } +func (*QueryGlobalSpStorePriceByTimeResponse) ProtoMessage() {} +func (*QueryGlobalSpStorePriceByTimeResponse) Descriptor() ([]byte, []int) { return fileDescriptor_48dd9c8aad3b7a6d, []int{7} } -func (m *QueryGetSecondarySpStorePriceByTimeResponse) XXX_Unmarshal(b []byte) error { +func (m *QueryGlobalSpStorePriceByTimeResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } -func (m *QueryGetSecondarySpStorePriceByTimeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { +func (m *QueryGlobalSpStorePriceByTimeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { - return xxx_messageInfo_QueryGetSecondarySpStorePriceByTimeResponse.Marshal(b, m, deterministic) + return xxx_messageInfo_QueryGlobalSpStorePriceByTimeResponse.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) @@ -389,23 +372,23 @@ func (m *QueryGetSecondarySpStorePriceByTimeResponse) XXX_Marshal(b []byte, dete return b[:n], nil } } -func (m *QueryGetSecondarySpStorePriceByTimeResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryGetSecondarySpStorePriceByTimeResponse.Merge(m, src) +func (m *QueryGlobalSpStorePriceByTimeResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryGlobalSpStorePriceByTimeResponse.Merge(m, src) } -func (m *QueryGetSecondarySpStorePriceByTimeResponse) XXX_Size() int { +func (m *QueryGlobalSpStorePriceByTimeResponse) XXX_Size() int { return m.Size() } -func (m *QueryGetSecondarySpStorePriceByTimeResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryGetSecondarySpStorePriceByTimeResponse.DiscardUnknown(m) +func (m *QueryGlobalSpStorePriceByTimeResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryGlobalSpStorePriceByTimeResponse.DiscardUnknown(m) } -var xxx_messageInfo_QueryGetSecondarySpStorePriceByTimeResponse proto.InternalMessageInfo +var xxx_messageInfo_QueryGlobalSpStorePriceByTimeResponse proto.InternalMessageInfo -func (m *QueryGetSecondarySpStorePriceByTimeResponse) GetSecondarySpStorePrice() SecondarySpStorePrice { +func (m *QueryGlobalSpStorePriceByTimeResponse) GetGlobalSpStorePrice() GlobalSpStorePrice { if m != nil { - return m.SecondarySpStorePrice + return m.GlobalSpStorePrice } - return SecondarySpStorePrice{} + return GlobalSpStorePrice{} } type QueryStorageProviderRequest struct { @@ -693,10 +676,10 @@ func init() { proto.RegisterType((*QueryParamsResponse)(nil), "greenfield.sp.QueryParamsResponse") proto.RegisterType((*QueryStorageProvidersRequest)(nil), "greenfield.sp.QueryStorageProvidersRequest") proto.RegisterType((*QueryStorageProvidersResponse)(nil), "greenfield.sp.QueryStorageProvidersResponse") - proto.RegisterType((*QueryGetSpStoragePriceByTimeRequest)(nil), "greenfield.sp.QueryGetSpStoragePriceByTimeRequest") - proto.RegisterType((*QueryGetSpStoragePriceByTimeResponse)(nil), "greenfield.sp.QueryGetSpStoragePriceByTimeResponse") - proto.RegisterType((*QueryGetSecondarySpStorePriceByTimeRequest)(nil), "greenfield.sp.QueryGetSecondarySpStorePriceByTimeRequest") - proto.RegisterType((*QueryGetSecondarySpStorePriceByTimeResponse)(nil), "greenfield.sp.QueryGetSecondarySpStorePriceByTimeResponse") + proto.RegisterType((*QuerySpStoragePriceRequest)(nil), "greenfield.sp.QuerySpStoragePriceRequest") + proto.RegisterType((*QuerySpStoragePriceResponse)(nil), "greenfield.sp.QuerySpStoragePriceResponse") + proto.RegisterType((*QueryGlobalSpStorePriceByTimeRequest)(nil), "greenfield.sp.QueryGlobalSpStorePriceByTimeRequest") + proto.RegisterType((*QueryGlobalSpStorePriceByTimeResponse)(nil), "greenfield.sp.QueryGlobalSpStorePriceByTimeResponse") proto.RegisterType((*QueryStorageProviderRequest)(nil), "greenfield.sp.QueryStorageProviderRequest") proto.RegisterType((*QueryStorageProviderResponse)(nil), "greenfield.sp.QueryStorageProviderResponse") proto.RegisterType((*QueryStorageProviderByOperatorAddressRequest)(nil), "greenfield.sp.QueryStorageProviderByOperatorAddressRequest") @@ -708,63 +691,62 @@ func init() { func init() { proto.RegisterFile("greenfield/sp/query.proto", fileDescriptor_48dd9c8aad3b7a6d) } var fileDescriptor_48dd9c8aad3b7a6d = []byte{ - // 896 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x96, 0x4d, 0x6f, 0xdc, 0x44, - 0x18, 0xc7, 0xe3, 0x0d, 0xa4, 0xea, 0x53, 0xb5, 0x89, 0x86, 0x46, 0x6d, 0x4d, 0xb2, 0x4d, 0xdd, - 0x02, 0xed, 0xa6, 0xb1, 0xe9, 0xae, 0x38, 0xd0, 0x82, 0x50, 0x16, 0xc4, 0xd2, 0x4a, 0x55, 0x83, - 0xcb, 0x85, 0x0a, 0xc9, 0x9a, 0xb5, 0xa7, 0x8e, 0xa5, 0xac, 0x67, 0xea, 0xf1, 0x56, 0xac, 0xa2, - 0x5c, 0xfa, 0x09, 0x10, 0x2f, 0x17, 0xbe, 0x0f, 0x52, 0x8f, 0x11, 0x5c, 0x10, 0x07, 0x84, 0x12, - 0xf8, 0x1e, 0xc8, 0x33, 0xe3, 0xdd, 0xf5, 0xc4, 0xde, 0x35, 0x2b, 0x6e, 0xbb, 0x33, 0xcf, 0xcb, - 0xff, 0xf7, 0xf8, 0xf1, 0x5f, 0x86, 0x6b, 0x61, 0x42, 0x48, 0xfc, 0x3c, 0x22, 0x07, 0x81, 0xc3, - 0x99, 0xf3, 0x62, 0x48, 0x92, 0x91, 0xcd, 0x12, 0x9a, 0x52, 0x74, 0x71, 0x72, 0x65, 0x73, 0x66, - 0xb6, 0x7c, 0xca, 0x07, 0x94, 0x3b, 0x7d, 0xcc, 0x89, 0x8c, 0x73, 0x5e, 0xde, 0xeb, 0x93, 0x14, - 0xdf, 0x73, 0x18, 0x0e, 0xa3, 0x18, 0xa7, 0x11, 0x8d, 0x65, 0xaa, 0x79, 0x4d, 0xc6, 0x7a, 0xe2, - 0x9f, 0x23, 0xff, 0xa8, 0xab, 0xcb, 0x21, 0x0d, 0xa9, 0x3c, 0xcf, 0x7e, 0xa9, 0xd3, 0x8d, 0x90, - 0xd2, 0xf0, 0x80, 0x38, 0x98, 0x45, 0x0e, 0x8e, 0x63, 0x9a, 0x8a, 0x6a, 0x79, 0x8e, 0x59, 0x14, - 0xc9, 0x70, 0x82, 0x07, 0xf9, 0x9d, 0x06, 0x90, 0x8e, 0x18, 0x51, 0x57, 0xd6, 0x65, 0x40, 0x5f, - 0x66, 0x3a, 0xf7, 0x44, 0xbc, 0x4b, 0x5e, 0x0c, 0x09, 0x4f, 0xad, 0x47, 0xf0, 0x56, 0xe1, 0x94, - 0x33, 0x1a, 0x73, 0x82, 0x3a, 0xb0, 0x22, 0xeb, 0x5e, 0x35, 0xb6, 0x8c, 0xdb, 0x17, 0xda, 0xeb, - 0x76, 0x01, 0xdf, 0x96, 0xe1, 0xdd, 0x37, 0x5e, 0xff, 0x79, 0x7d, 0xc9, 0x55, 0xa1, 0xd6, 0x73, - 0xd8, 0x10, 0xb5, 0x9e, 0xa6, 0x34, 0xc1, 0x21, 0xd9, 0x4b, 0xe8, 0xcb, 0x28, 0x20, 0x49, 0xde, - 0x0b, 0x7d, 0x0e, 0x30, 0x99, 0x8d, 0x2a, 0xfc, 0xae, 0xad, 0xe6, 0x91, 0x0d, 0xd2, 0x96, 0x03, - 0x57, 0x83, 0xb4, 0xf7, 0x70, 0x48, 0x54, 0xae, 0x3b, 0x95, 0x69, 0xfd, 0x6c, 0xc0, 0x66, 0x45, - 0x23, 0x25, 0xff, 0x7d, 0x58, 0xe6, 0x2c, 0xd3, 0xbe, 0x7c, 0xfb, 0x42, 0xbb, 0xa9, 0x69, 0xd7, - 0xb2, 0xdc, 0x2c, 0x14, 0xf5, 0x0a, 0xda, 0x1a, 0x42, 0xdb, 0x7b, 0x73, 0xb5, 0xc9, 0x76, 0x05, - 0x71, 0xdf, 0xc0, 0x4d, 0xa1, 0xad, 0x47, 0xd2, 0xa7, 0x6c, 0xdc, 0x2a, 0xf2, 0x49, 0x77, 0xf4, - 0x55, 0x34, 0xc8, 0x79, 0xd0, 0x15, 0x38, 0xc7, 0x99, 0x87, 0x83, 0x20, 0x11, 0x83, 0x38, 0xef, - 0xae, 0x70, 0xb6, 0x1b, 0x04, 0x09, 0xda, 0x80, 0xf3, 0x69, 0x34, 0x20, 0x3c, 0xc5, 0x03, 0x26, - 0x74, 0x2c, 0xbb, 0x93, 0x03, 0x6b, 0x08, 0xb7, 0x66, 0x57, 0x57, 0x03, 0x78, 0x0c, 0x6b, 0x9c, - 0x79, 0x5c, 0x06, 0x78, 0x2c, 0x8b, 0x50, 0x03, 0xdf, 0xd4, 0xa7, 0x51, 0x2c, 0x23, 0x9f, 0xe8, - 0x25, 0x5e, 0x38, 0xb5, 0x1e, 0x41, 0x6b, 0xdc, 0x96, 0xf8, 0x34, 0x0e, 0x70, 0x32, 0x92, 0x89, - 0x65, 0x6c, 0x05, 0x04, 0x43, 0x47, 0xf8, 0xde, 0x80, 0xed, 0x5a, 0xc5, 0x14, 0x8a, 0x0f, 0x57, - 0x79, 0x1e, 0xe6, 0x29, 0xa8, 0x22, 0xd2, 0x2d, 0x1d, 0xa9, 0xb4, 0xaa, 0x24, 0x5b, 0xe7, 0x65, - 0x97, 0xd6, 0x0e, 0xbc, 0x5d, 0xb6, 0x51, 0x39, 0xd1, 0x25, 0x68, 0x44, 0x81, 0xe8, 0x76, 0xd1, - 0x6d, 0x44, 0x81, 0xb5, 0x5f, 0xbe, 0xe9, 0x63, 0xcd, 0x5f, 0xc0, 0x2a, 0x2f, 0x5e, 0x29, 0xa9, - 0xf3, 0x76, 0x51, 0x4f, 0xb3, 0xbe, 0x86, 0xbb, 0x65, 0x9d, 0xba, 0xa3, 0x27, 0x8c, 0x24, 0x38, - 0xa5, 0x49, 0xb6, 0x34, 0x84, 0x8f, 0xdf, 0xb1, 0x3b, 0xb0, 0x46, 0xd5, 0x8d, 0xd8, 0x2e, 0xc2, - 0xb9, 0x5a, 0xb0, 0x55, 0x5a, 0xcc, 0xb0, 0x46, 0xb0, 0x53, 0xb3, 0xf4, 0xff, 0x4e, 0xf5, 0xac, - 0xbc, 0xf5, 0x63, 0x1c, 0xc5, 0x29, 0x89, 0x71, 0xec, 0x13, 0x97, 0xf8, 0x34, 0x09, 0x16, 0xc1, - 0x3a, 0x00, 0xbb, 0x6e, 0x6d, 0xc5, 0x75, 0x1f, 0xce, 0x25, 0xf2, 0x48, 0x39, 0xc6, 0x96, 0xc6, - 0x73, 0x26, 0xd7, 0xcd, 0x13, 0xda, 0xbf, 0x00, 0xbc, 0x29, 0xda, 0xa1, 0x18, 0x56, 0xa4, 0x2b, - 0xa2, 0x1b, 0x5a, 0xfa, 0x59, 0xdb, 0x35, 0xad, 0x59, 0x21, 0x52, 0x96, 0xb5, 0xf9, 0xea, 0xb7, - 0xbf, 0x7f, 0x68, 0x5c, 0x41, 0xeb, 0x4e, 0x99, 0xe1, 0xa3, 0x1f, 0x0d, 0x58, 0xd3, 0x0d, 0x10, - 0x6d, 0x97, 0xd5, 0xad, 0xf0, 0x63, 0xf3, 0x6e, 0xbd, 0x60, 0x25, 0xe7, 0x1d, 0x21, 0xe7, 0x3a, - 0xda, 0x2c, 0xc8, 0x19, 0x3b, 0x4c, 0xae, 0xe0, 0x57, 0x43, 0xbd, 0x1b, 0x15, 0x16, 0x85, 0xda, - 0x65, 0x5d, 0x67, 0xbb, 0xa5, 0xd9, 0xf9, 0x4f, 0x39, 0x4a, 0xf0, 0x43, 0x21, 0xf8, 0x53, 0xb4, - 0xab, 0xcd, 0x2f, 0x24, 0xa9, 0xa7, 0x9b, 0xa3, 0xd7, 0x1f, 0x79, 0x99, 0x45, 0x39, 0x87, 0xca, - 0x95, 0x8f, 0x9c, 0xc3, 0xb1, 0x65, 0x1d, 0xa1, 0x7f, 0x8c, 0x29, 0x57, 0xaf, 0xf6, 0x2c, 0xf4, - 0x61, 0x95, 0xce, 0xb9, 0xa6, 0x69, 0xde, 0x5f, 0x24, 0x55, 0x91, 0xf6, 0x04, 0xe9, 0x2e, 0xfa, - 0xa4, 0x8c, 0xb4, 0xc2, 0x3b, 0x27, 0xc4, 0x53, 0x9c, 0x3f, 0x19, 0xb0, 0xaa, 0x2d, 0x00, 0x6a, - 0xd5, 0xd8, 0x92, 0x1c, 0x62, 0xbb, 0x56, 0xac, 0x52, 0x7d, 0x47, 0xa8, 0xbe, 0x89, 0x6e, 0xcc, - 0x5a, 0x28, 0xe7, 0x30, 0x0a, 0x8e, 0xd0, 0x1f, 0x06, 0x6c, 0xcd, 0xb3, 0x29, 0xf4, 0xa0, 0x46, - 0xf3, 0x2a, 0xdf, 0x34, 0x3f, 0x5a, 0x2c, 0x59, 0xa1, 0x3c, 0x10, 0x28, 0x1f, 0xa0, 0x8e, 0xf6, - 0x00, 0x74, 0x9a, 0x6c, 0xe8, 0xba, 0x8f, 0xa1, 0x57, 0x0d, 0x68, 0xcf, 0x35, 0xab, 0xb3, 0xb8, - 0x75, 0x14, 0x57, 0x1a, 0xaa, 0xf9, 0xf1, 0x82, 0xd9, 0x0a, 0xf8, 0x89, 0x00, 0x7e, 0x88, 0x7a, - 0xf3, 0x80, 0x07, 0x93, 0x1a, 0x9e, 0xf2, 0xcc, 0xb2, 0x21, 0x74, 0x3f, 0x7b, 0x7d, 0xd2, 0x34, - 0x8e, 0x4f, 0x9a, 0xc6, 0x5f, 0x27, 0x4d, 0xe3, 0xbb, 0xd3, 0xe6, 0xd2, 0xf1, 0x69, 0x73, 0xe9, - 0xf7, 0xd3, 0xe6, 0xd2, 0xb3, 0x56, 0x18, 0xa5, 0xfb, 0xc3, 0xbe, 0xed, 0xd3, 0x81, 0xd3, 0x8f, - 0xfb, 0x3b, 0xfe, 0x3e, 0x8e, 0xe2, 0xe9, 0xb6, 0xdf, 0x8e, 0xbf, 0x74, 0xfb, 0x2b, 0xe2, 0x53, - 0xb7, 0xf3, 0x6f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x58, 0xf5, 0x0f, 0xbb, 0xc8, 0x0b, 0x00, 0x00, + // 874 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x56, 0x41, 0x4f, 0xf4, 0x44, + 0x18, 0xde, 0x2e, 0xba, 0x5f, 0x98, 0x2f, 0xdf, 0x07, 0x19, 0x21, 0x48, 0x65, 0x17, 0xa8, 0xa2, + 0xec, 0x02, 0xad, 0xec, 0x4a, 0x62, 0x40, 0x13, 0x25, 0x44, 0xd4, 0x84, 0x80, 0xd5, 0x8b, 0x5c, + 0x9a, 0xe9, 0x76, 0x28, 0x4d, 0x76, 0x3b, 0x43, 0xa7, 0x10, 0x37, 0x84, 0x0b, 0xfe, 0x01, 0x13, + 0xf5, 0xe2, 0xc5, 0xbf, 0xc3, 0xc1, 0x03, 0x89, 0x17, 0xe3, 0xc1, 0x18, 0xf0, 0x4f, 0x78, 0x33, + 0x9d, 0x99, 0xee, 0xd2, 0xd9, 0x2e, 0x5b, 0xc9, 0x77, 0xdb, 0xce, 0xfb, 0x3e, 0xef, 0xfb, 0x3c, + 0xef, 0xbc, 0x7d, 0xb6, 0x60, 0xde, 0x8f, 0x30, 0x0e, 0x4f, 0x02, 0xdc, 0xf1, 0x2c, 0x46, 0xad, + 0xb3, 0x73, 0x1c, 0xf5, 0x4c, 0x1a, 0x91, 0x98, 0xc0, 0x17, 0x83, 0x90, 0xc9, 0xa8, 0xde, 0x68, + 0x13, 0xd6, 0x25, 0xcc, 0x72, 0x11, 0xc3, 0x22, 0xcf, 0xba, 0xd8, 0x74, 0x71, 0x8c, 0x36, 0x2d, + 0x8a, 0xfc, 0x20, 0x44, 0x71, 0x40, 0x42, 0x01, 0xd5, 0xe7, 0x45, 0xae, 0xc3, 0x9f, 0x2c, 0xf1, + 0x20, 0x43, 0x33, 0x3e, 0xf1, 0x89, 0x38, 0x4f, 0x7e, 0xc9, 0xd3, 0x05, 0x9f, 0x10, 0xbf, 0x83, + 0x2d, 0x44, 0x03, 0x0b, 0x85, 0x21, 0x89, 0x79, 0xb5, 0x14, 0xa3, 0x67, 0x49, 0x52, 0x14, 0xa1, + 0x6e, 0x1a, 0x53, 0x04, 0xc4, 0x3d, 0x8a, 0x65, 0xc8, 0x98, 0x01, 0xf0, 0xab, 0x84, 0xe7, 0x11, + 0xcf, 0xb7, 0xf1, 0xd9, 0x39, 0x66, 0xb1, 0xf1, 0x25, 0x78, 0x23, 0x73, 0xca, 0x28, 0x09, 0x19, + 0x86, 0x2d, 0x50, 0x11, 0x75, 0xdf, 0xd4, 0x96, 0xb4, 0xd5, 0xe7, 0xcd, 0x59, 0x33, 0x23, 0xdf, + 0x14, 0xe9, 0xbb, 0xaf, 0xdd, 0xfc, 0xb5, 0x58, 0xb2, 0x65, 0xaa, 0x71, 0x02, 0x16, 0x78, 0xad, + 0xaf, 0x63, 0x12, 0x21, 0x1f, 0x1f, 0x45, 0xe4, 0x22, 0xf0, 0x70, 0x94, 0xf6, 0x82, 0x9f, 0x01, + 0x30, 0x98, 0x8d, 0x2c, 0xfc, 0xae, 0x29, 0xe7, 0x91, 0x0c, 0xd2, 0x14, 0x03, 0x97, 0x83, 0x34, + 0x8f, 0x90, 0x8f, 0x25, 0xd6, 0x7e, 0x80, 0x34, 0x7e, 0xd1, 0x40, 0x75, 0x44, 0x23, 0x49, 0xff, + 0x7d, 0x30, 0xc1, 0x68, 0xc2, 0x7d, 0x62, 0xf5, 0x79, 0xb3, 0xa6, 0x70, 0x57, 0x50, 0x76, 0x92, + 0x0a, 0xf7, 0x33, 0xdc, 0xca, 0x9c, 0xdb, 0x7b, 0x63, 0xb9, 0x89, 0x76, 0x19, 0x72, 0x5b, 0x40, + 0x17, 0xdc, 0x68, 0xbf, 0x4f, 0xd0, 0x4e, 0x65, 0xc0, 0x39, 0xf0, 0x8c, 0x51, 0x07, 0x79, 0x5e, + 0xc4, 0xf5, 0x4f, 0xda, 0x15, 0x46, 0x3f, 0xf5, 0xbc, 0xc8, 0xe8, 0x80, 0xb7, 0x72, 0x61, 0x52, + 0xd0, 0x01, 0x98, 0x66, 0xd4, 0x61, 0x22, 0xe4, 0xd0, 0x24, 0x26, 0x07, 0x58, 0x55, 0xd5, 0x65, + 0x0a, 0xc8, 0x1b, 0x7a, 0xc9, 0x32, 0xa7, 0xc6, 0x1e, 0x78, 0x87, 0x77, 0xdb, 0xef, 0x10, 0x17, + 0x75, 0x04, 0x44, 0x02, 0x7a, 0xdf, 0x04, 0xdd, 0x3e, 0xdd, 0x05, 0x30, 0x19, 0x07, 0x5d, 0xcc, + 0x62, 0xd4, 0xa5, 0xbc, 0xdf, 0x84, 0x3d, 0x38, 0x30, 0xbe, 0xd7, 0xc0, 0xca, 0x98, 0x32, 0x92, + 0xfe, 0x31, 0x98, 0xf5, 0x79, 0x8e, 0x23, 0x55, 0x64, 0x35, 0x2c, 0x2b, 0x1a, 0x72, 0xea, 0x09, + 0x1d, 0xd0, 0x1f, 0x8a, 0x18, 0x1b, 0xe9, 0xe4, 0x94, 0x6b, 0x95, 0x12, 0x5e, 0x82, 0x72, 0xe0, + 0xf1, 0x3e, 0x2f, 0xec, 0x72, 0xe0, 0x19, 0xa7, 0xf9, 0x4b, 0xda, 0xa7, 0xfa, 0x39, 0x98, 0x62, + 0xd9, 0x90, 0x24, 0x39, 0x6e, 0x8d, 0x54, 0x98, 0xf1, 0x2d, 0x58, 0xcf, 0xeb, 0xb4, 0xdb, 0x3b, + 0xa4, 0x38, 0x42, 0x31, 0x89, 0x92, 0x8b, 0xc7, 0xac, 0xff, 0x7a, 0xd4, 0xc1, 0x34, 0x91, 0x11, + 0xbe, 0x21, 0x98, 0x31, 0xb9, 0x24, 0x53, 0x24, 0x8b, 0x30, 0x7a, 0x60, 0xa3, 0x60, 0xe9, 0x57, + 0xae, 0xea, 0x38, 0xbf, 0xf5, 0x01, 0x0a, 0xc2, 0x18, 0x87, 0x28, 0x4c, 0x96, 0xb6, 0x4d, 0x22, + 0xef, 0x29, 0xb2, 0x3a, 0xc0, 0x2c, 0x5a, 0x5b, 0xea, 0xda, 0x06, 0xcf, 0x22, 0x71, 0x24, 0x5f, + 0xf6, 0x25, 0x45, 0xcf, 0x10, 0xd6, 0x4e, 0x01, 0xcd, 0x7f, 0x27, 0xc1, 0xeb, 0xbc, 0x1d, 0x0c, + 0x41, 0x45, 0x18, 0x1a, 0x54, 0x37, 0x71, 0xd8, 0x31, 0x75, 0xe3, 0xb1, 0x14, 0x41, 0xcb, 0xa8, + 0x5e, 0xff, 0xfe, 0xcf, 0x8f, 0xe5, 0x39, 0x38, 0x6b, 0xe5, 0x79, 0x35, 0xfc, 0x49, 0x03, 0xd3, + 0xaa, 0x77, 0xc1, 0xb5, 0xbc, 0xba, 0x23, 0xac, 0x54, 0x5f, 0x2f, 0x96, 0x2c, 0xe9, 0xac, 0x70, + 0x3a, 0x8b, 0xb0, 0x9a, 0xa1, 0xd3, 0x37, 0x93, 0x94, 0xc1, 0xaf, 0x9a, 0xfc, 0x33, 0xc8, 0x7a, + 0x08, 0xac, 0xe7, 0x36, 0xcb, 0xf3, 0x37, 0xbd, 0x51, 0x24, 0x55, 0xb2, 0xda, 0xe4, 0xac, 0xd6, + 0x60, 0x5d, 0x19, 0x92, 0x6a, 0x74, 0xd6, 0xa5, 0xb4, 0xcc, 0x2b, 0xf8, 0x5b, 0xea, 0xfc, 0xa3, + 0x1c, 0x07, 0xb6, 0xf2, 0x08, 0x8c, 0xb1, 0x39, 0xfd, 0x83, 0xff, 0x07, 0x92, 0xfc, 0x3f, 0xe1, + 0xfc, 0xb7, 0xe1, 0x87, 0x0a, 0xff, 0x5c, 0xa7, 0x73, 0xdc, 0x9e, 0x93, 0x38, 0xa7, 0x75, 0xd9, + 0xf7, 0xcf, 0x2b, 0xf8, 0xb3, 0x06, 0xa6, 0x94, 0x4b, 0x83, 0x8d, 0x02, 0x37, 0x9b, 0xf2, 0x5e, + 0x2b, 0x94, 0x2b, 0xe9, 0xd6, 0x39, 0xdd, 0xb7, 0xe1, 0xf2, 0x63, 0x4b, 0x60, 0x5d, 0x06, 0xde, + 0x15, 0xfc, 0x53, 0x03, 0x4b, 0xe3, 0xac, 0x05, 0xee, 0x14, 0x68, 0x3e, 0xca, 0xeb, 0xf4, 0x8f, + 0x9e, 0x06, 0x96, 0x52, 0x76, 0xb8, 0x94, 0x2d, 0xd8, 0x52, 0x37, 0x47, 0x51, 0x93, 0x0c, 0x5d, + 0xf5, 0x1e, 0x78, 0x5d, 0x06, 0xcd, 0xb1, 0x06, 0x33, 0x2c, 0xb7, 0x08, 0xe3, 0x91, 0x26, 0xa8, + 0x7f, 0xfc, 0x44, 0xb4, 0x14, 0x7c, 0xc8, 0x05, 0x7f, 0x01, 0xf7, 0xc7, 0x09, 0xee, 0x0e, 0x6a, + 0x38, 0xd2, 0xe7, 0xf2, 0x86, 0xb0, 0xbb, 0x77, 0x73, 0x57, 0xd3, 0x6e, 0xef, 0x6a, 0xda, 0xdf, + 0x77, 0x35, 0xed, 0x87, 0xfb, 0x5a, 0xe9, 0xf6, 0xbe, 0x56, 0xfa, 0xe3, 0xbe, 0x56, 0x3a, 0x6e, + 0xf8, 0x41, 0x7c, 0x7a, 0xee, 0x9a, 0x6d, 0xd2, 0xb5, 0xdc, 0xd0, 0xdd, 0x68, 0x9f, 0xa2, 0x20, + 0x7c, 0xd8, 0xf6, 0xbb, 0xfe, 0x87, 0xa5, 0x5b, 0xe1, 0x5f, 0x96, 0xad, 0xff, 0x02, 0x00, 0x00, + 0xff, 0xff, 0x57, 0x64, 0xa6, 0xac, 0x37, 0x0b, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -783,10 +765,10 @@ type QueryClient interface { Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) // Queries a list of GetStorageProviders items. StorageProviders(ctx context.Context, in *QueryStorageProvidersRequest, opts ...grpc.CallOption) (*QueryStorageProvidersResponse, error) - // get storage price of specific sp and time - QueryGetSpStoragePriceByTime(ctx context.Context, in *QueryGetSpStoragePriceByTimeRequest, opts ...grpc.CallOption) (*QueryGetSpStoragePriceByTimeResponse, error) - // get secondary store price by time - QueryGetSecondarySpStorePriceByTime(ctx context.Context, in *QueryGetSecondarySpStorePriceByTimeRequest, opts ...grpc.CallOption) (*QueryGetSecondarySpStorePriceByTimeResponse, error) + // get the latest storage price of specific sp + QuerySpStoragePrice(ctx context.Context, in *QuerySpStoragePriceRequest, opts ...grpc.CallOption) (*QuerySpStoragePriceResponse, error) + // get global store price by time + QueryGlobalSpStorePriceByTime(ctx context.Context, in *QueryGlobalSpStorePriceByTimeRequest, opts ...grpc.CallOption) (*QueryGlobalSpStorePriceByTimeResponse, error) // Queries a storage provider with specify id StorageProvider(ctx context.Context, in *QueryStorageProviderRequest, opts ...grpc.CallOption) (*QueryStorageProviderResponse, error) // Queries a StorageProvider by specify operator address. @@ -821,18 +803,18 @@ func (c *queryClient) StorageProviders(ctx context.Context, in *QueryStorageProv return out, nil } -func (c *queryClient) QueryGetSpStoragePriceByTime(ctx context.Context, in *QueryGetSpStoragePriceByTimeRequest, opts ...grpc.CallOption) (*QueryGetSpStoragePriceByTimeResponse, error) { - out := new(QueryGetSpStoragePriceByTimeResponse) - err := c.cc.Invoke(ctx, "/greenfield.sp.Query/QueryGetSpStoragePriceByTime", in, out, opts...) +func (c *queryClient) QuerySpStoragePrice(ctx context.Context, in *QuerySpStoragePriceRequest, opts ...grpc.CallOption) (*QuerySpStoragePriceResponse, error) { + out := new(QuerySpStoragePriceResponse) + err := c.cc.Invoke(ctx, "/greenfield.sp.Query/QuerySpStoragePrice", in, out, opts...) if err != nil { return nil, err } return out, nil } -func (c *queryClient) QueryGetSecondarySpStorePriceByTime(ctx context.Context, in *QueryGetSecondarySpStorePriceByTimeRequest, opts ...grpc.CallOption) (*QueryGetSecondarySpStorePriceByTimeResponse, error) { - out := new(QueryGetSecondarySpStorePriceByTimeResponse) - err := c.cc.Invoke(ctx, "/greenfield.sp.Query/QueryGetSecondarySpStorePriceByTime", in, out, opts...) +func (c *queryClient) QueryGlobalSpStorePriceByTime(ctx context.Context, in *QueryGlobalSpStorePriceByTimeRequest, opts ...grpc.CallOption) (*QueryGlobalSpStorePriceByTimeResponse, error) { + out := new(QueryGlobalSpStorePriceByTimeResponse) + err := c.cc.Invoke(ctx, "/greenfield.sp.Query/QueryGlobalSpStorePriceByTime", in, out, opts...) if err != nil { return nil, err } @@ -872,10 +854,10 @@ type QueryServer interface { Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) // Queries a list of GetStorageProviders items. StorageProviders(context.Context, *QueryStorageProvidersRequest) (*QueryStorageProvidersResponse, error) - // get storage price of specific sp and time - QueryGetSpStoragePriceByTime(context.Context, *QueryGetSpStoragePriceByTimeRequest) (*QueryGetSpStoragePriceByTimeResponse, error) - // get secondary store price by time - QueryGetSecondarySpStorePriceByTime(context.Context, *QueryGetSecondarySpStorePriceByTimeRequest) (*QueryGetSecondarySpStorePriceByTimeResponse, error) + // get the latest storage price of specific sp + QuerySpStoragePrice(context.Context, *QuerySpStoragePriceRequest) (*QuerySpStoragePriceResponse, error) + // get global store price by time + QueryGlobalSpStorePriceByTime(context.Context, *QueryGlobalSpStorePriceByTimeRequest) (*QueryGlobalSpStorePriceByTimeResponse, error) // Queries a storage provider with specify id StorageProvider(context.Context, *QueryStorageProviderRequest) (*QueryStorageProviderResponse, error) // Queries a StorageProvider by specify operator address. @@ -894,11 +876,11 @@ func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsReq func (*UnimplementedQueryServer) StorageProviders(ctx context.Context, req *QueryStorageProvidersRequest) (*QueryStorageProvidersResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method StorageProviders not implemented") } -func (*UnimplementedQueryServer) QueryGetSpStoragePriceByTime(ctx context.Context, req *QueryGetSpStoragePriceByTimeRequest) (*QueryGetSpStoragePriceByTimeResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method QueryGetSpStoragePriceByTime not implemented") +func (*UnimplementedQueryServer) QuerySpStoragePrice(ctx context.Context, req *QuerySpStoragePriceRequest) (*QuerySpStoragePriceResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method QuerySpStoragePrice not implemented") } -func (*UnimplementedQueryServer) QueryGetSecondarySpStorePriceByTime(ctx context.Context, req *QueryGetSecondarySpStorePriceByTimeRequest) (*QueryGetSecondarySpStorePriceByTimeResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method QueryGetSecondarySpStorePriceByTime not implemented") +func (*UnimplementedQueryServer) QueryGlobalSpStorePriceByTime(ctx context.Context, req *QueryGlobalSpStorePriceByTimeRequest) (*QueryGlobalSpStorePriceByTimeResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method QueryGlobalSpStorePriceByTime not implemented") } func (*UnimplementedQueryServer) StorageProvider(ctx context.Context, req *QueryStorageProviderRequest) (*QueryStorageProviderResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method StorageProvider not implemented") @@ -950,38 +932,38 @@ func _Query_StorageProviders_Handler(srv interface{}, ctx context.Context, dec f return interceptor(ctx, in, info, handler) } -func _Query_QueryGetSpStoragePriceByTime_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryGetSpStoragePriceByTimeRequest) +func _Query_QuerySpStoragePrice_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QuerySpStoragePriceRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return srv.(QueryServer).QueryGetSpStoragePriceByTime(ctx, in) + return srv.(QueryServer).QuerySpStoragePrice(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/greenfield.sp.Query/QueryGetSpStoragePriceByTime", + FullMethod: "/greenfield.sp.Query/QuerySpStoragePrice", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).QueryGetSpStoragePriceByTime(ctx, req.(*QueryGetSpStoragePriceByTimeRequest)) + return srv.(QueryServer).QuerySpStoragePrice(ctx, req.(*QuerySpStoragePriceRequest)) } return interceptor(ctx, in, info, handler) } -func _Query_QueryGetSecondarySpStorePriceByTime_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryGetSecondarySpStorePriceByTimeRequest) +func _Query_QueryGlobalSpStorePriceByTime_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryGlobalSpStorePriceByTimeRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { - return srv.(QueryServer).QueryGetSecondarySpStorePriceByTime(ctx, in) + return srv.(QueryServer).QueryGlobalSpStorePriceByTime(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/greenfield.sp.Query/QueryGetSecondarySpStorePriceByTime", + FullMethod: "/greenfield.sp.Query/QueryGlobalSpStorePriceByTime", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).QueryGetSecondarySpStorePriceByTime(ctx, req.(*QueryGetSecondarySpStorePriceByTimeRequest)) + return srv.(QueryServer).QueryGlobalSpStorePriceByTime(ctx, req.(*QueryGlobalSpStorePriceByTimeRequest)) } return interceptor(ctx, in, info, handler) } @@ -1053,12 +1035,12 @@ var _Query_serviceDesc = grpc.ServiceDesc{ Handler: _Query_StorageProviders_Handler, }, { - MethodName: "QueryGetSpStoragePriceByTime", - Handler: _Query_QueryGetSpStoragePriceByTime_Handler, + MethodName: "QuerySpStoragePrice", + Handler: _Query_QuerySpStoragePrice_Handler, }, { - MethodName: "QueryGetSecondarySpStorePriceByTime", - Handler: _Query_QueryGetSecondarySpStorePriceByTime_Handler, + MethodName: "QueryGlobalSpStorePriceByTime", + Handler: _Query_QueryGlobalSpStorePriceByTime_Handler, }, { MethodName: "StorageProvider", @@ -1217,7 +1199,7 @@ func (m *QueryStorageProvidersResponse) MarshalToSizedBuffer(dAtA []byte) (int, return len(dAtA) - i, nil } -func (m *QueryGetSpStoragePriceByTimeRequest) Marshal() (dAtA []byte, err error) { +func (m *QuerySpStoragePriceRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -1227,21 +1209,16 @@ func (m *QueryGetSpStoragePriceByTimeRequest) Marshal() (dAtA []byte, err error) return dAtA[:n], nil } -func (m *QueryGetSpStoragePriceByTimeRequest) MarshalTo(dAtA []byte) (int, error) { +func (m *QuerySpStoragePriceRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *QueryGetSpStoragePriceByTimeRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *QuerySpStoragePriceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - if m.Timestamp != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.Timestamp)) - i-- - dAtA[i] = 0x10 - } if len(m.SpAddr) > 0 { i -= len(m.SpAddr) copy(dAtA[i:], m.SpAddr) @@ -1252,7 +1229,7 @@ func (m *QueryGetSpStoragePriceByTimeRequest) MarshalToSizedBuffer(dAtA []byte) return len(dAtA) - i, nil } -func (m *QueryGetSpStoragePriceByTimeResponse) Marshal() (dAtA []byte, err error) { +func (m *QuerySpStoragePriceResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -1262,12 +1239,12 @@ func (m *QueryGetSpStoragePriceByTimeResponse) Marshal() (dAtA []byte, err error return dAtA[:n], nil } -func (m *QueryGetSpStoragePriceByTimeResponse) MarshalTo(dAtA []byte) (int, error) { +func (m *QuerySpStoragePriceResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *QueryGetSpStoragePriceByTimeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *QuerySpStoragePriceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int @@ -1285,7 +1262,7 @@ func (m *QueryGetSpStoragePriceByTimeResponse) MarshalToSizedBuffer(dAtA []byte) return len(dAtA) - i, nil } -func (m *QueryGetSecondarySpStorePriceByTimeRequest) Marshal() (dAtA []byte, err error) { +func (m *QueryGlobalSpStorePriceByTimeRequest) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -1295,12 +1272,12 @@ func (m *QueryGetSecondarySpStorePriceByTimeRequest) Marshal() (dAtA []byte, err return dAtA[:n], nil } -func (m *QueryGetSecondarySpStorePriceByTimeRequest) MarshalTo(dAtA []byte) (int, error) { +func (m *QueryGlobalSpStorePriceByTimeRequest) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *QueryGetSecondarySpStorePriceByTimeRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *QueryGlobalSpStorePriceByTimeRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int @@ -1313,7 +1290,7 @@ func (m *QueryGetSecondarySpStorePriceByTimeRequest) MarshalToSizedBuffer(dAtA [ return len(dAtA) - i, nil } -func (m *QueryGetSecondarySpStorePriceByTimeResponse) Marshal() (dAtA []byte, err error) { +func (m *QueryGlobalSpStorePriceByTimeResponse) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -1323,18 +1300,18 @@ func (m *QueryGetSecondarySpStorePriceByTimeResponse) Marshal() (dAtA []byte, er return dAtA[:n], nil } -func (m *QueryGetSecondarySpStorePriceByTimeResponse) MarshalTo(dAtA []byte) (int, error) { +func (m *QueryGlobalSpStorePriceByTimeResponse) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *QueryGetSecondarySpStorePriceByTimeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *QueryGlobalSpStorePriceByTimeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l { - size, err := m.SecondarySpStorePrice.MarshalToSizedBuffer(dAtA[:i]) + size, err := m.GlobalSpStorePrice.MarshalToSizedBuffer(dAtA[:i]) if err != nil { return 0, err } @@ -1604,7 +1581,7 @@ func (m *QueryStorageProvidersResponse) Size() (n int) { return n } -func (m *QueryGetSpStoragePriceByTimeRequest) Size() (n int) { +func (m *QuerySpStoragePriceRequest) Size() (n int) { if m == nil { return 0 } @@ -1614,13 +1591,10 @@ func (m *QueryGetSpStoragePriceByTimeRequest) Size() (n int) { if l > 0 { n += 1 + l + sovQuery(uint64(l)) } - if m.Timestamp != 0 { - n += 1 + sovQuery(uint64(m.Timestamp)) - } return n } -func (m *QueryGetSpStoragePriceByTimeResponse) Size() (n int) { +func (m *QuerySpStoragePriceResponse) Size() (n int) { if m == nil { return 0 } @@ -1631,7 +1605,7 @@ func (m *QueryGetSpStoragePriceByTimeResponse) Size() (n int) { return n } -func (m *QueryGetSecondarySpStorePriceByTimeRequest) Size() (n int) { +func (m *QueryGlobalSpStorePriceByTimeRequest) Size() (n int) { if m == nil { return 0 } @@ -1643,13 +1617,13 @@ func (m *QueryGetSecondarySpStorePriceByTimeRequest) Size() (n int) { return n } -func (m *QueryGetSecondarySpStorePriceByTimeResponse) Size() (n int) { +func (m *QueryGlobalSpStorePriceByTimeResponse) Size() (n int) { if m == nil { return 0 } var l int _ = l - l = m.SecondarySpStorePrice.Size() + l = m.GlobalSpStorePrice.Size() n += 1 + l + sovQuery(uint64(l)) return n } @@ -2078,7 +2052,7 @@ func (m *QueryStorageProvidersResponse) Unmarshal(dAtA []byte) error { } return nil } -func (m *QueryGetSpStoragePriceByTimeRequest) Unmarshal(dAtA []byte) error { +func (m *QuerySpStoragePriceRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2101,10 +2075,10 @@ func (m *QueryGetSpStoragePriceByTimeRequest) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryGetSpStoragePriceByTimeRequest: wiretype end group for non-group") + return fmt.Errorf("proto: QuerySpStoragePriceRequest: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryGetSpStoragePriceByTimeRequest: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QuerySpStoragePriceRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -2139,25 +2113,6 @@ func (m *QueryGetSpStoragePriceByTimeRequest) Unmarshal(dAtA []byte) error { } m.SpAddr = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) - } - m.Timestamp = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Timestamp |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } default: iNdEx = preIndex skippy, err := skipQuery(dAtA[iNdEx:]) @@ -2179,7 +2134,7 @@ func (m *QueryGetSpStoragePriceByTimeRequest) Unmarshal(dAtA []byte) error { } return nil } -func (m *QueryGetSpStoragePriceByTimeResponse) Unmarshal(dAtA []byte) error { +func (m *QuerySpStoragePriceResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2202,10 +2157,10 @@ func (m *QueryGetSpStoragePriceByTimeResponse) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryGetSpStoragePriceByTimeResponse: wiretype end group for non-group") + return fmt.Errorf("proto: QuerySpStoragePriceResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryGetSpStoragePriceByTimeResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QuerySpStoragePriceResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -2262,7 +2217,7 @@ func (m *QueryGetSpStoragePriceByTimeResponse) Unmarshal(dAtA []byte) error { } return nil } -func (m *QueryGetSecondarySpStorePriceByTimeRequest) Unmarshal(dAtA []byte) error { +func (m *QueryGlobalSpStorePriceByTimeRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2285,10 +2240,10 @@ func (m *QueryGetSecondarySpStorePriceByTimeRequest) Unmarshal(dAtA []byte) erro fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryGetSecondarySpStorePriceByTimeRequest: wiretype end group for non-group") + return fmt.Errorf("proto: QueryGlobalSpStorePriceByTimeRequest: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryGetSecondarySpStorePriceByTimeRequest: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QueryGlobalSpStorePriceByTimeRequest: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -2331,7 +2286,7 @@ func (m *QueryGetSecondarySpStorePriceByTimeRequest) Unmarshal(dAtA []byte) erro } return nil } -func (m *QueryGetSecondarySpStorePriceByTimeResponse) Unmarshal(dAtA []byte) error { +func (m *QueryGlobalSpStorePriceByTimeResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2354,15 +2309,15 @@ func (m *QueryGetSecondarySpStorePriceByTimeResponse) Unmarshal(dAtA []byte) err fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: QueryGetSecondarySpStorePriceByTimeResponse: wiretype end group for non-group") + return fmt.Errorf("proto: QueryGlobalSpStorePriceByTimeResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: QueryGetSecondarySpStorePriceByTimeResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: QueryGlobalSpStorePriceByTimeResponse: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SecondarySpStorePrice", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field GlobalSpStorePrice", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -2389,7 +2344,7 @@ func (m *QueryGetSecondarySpStorePriceByTimeResponse) Unmarshal(dAtA []byte) err if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.SecondarySpStorePrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.GlobalSpStorePrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex diff --git a/x/sp/types/query.pb.gw.go b/x/sp/types/query.pb.gw.go index c1f381017..20cf43e2a 100644 --- a/x/sp/types/query.pb.gw.go +++ b/x/sp/types/query.pb.gw.go @@ -87,8 +87,8 @@ func local_request_Query_StorageProviders_0(ctx context.Context, marshaler runti } -func request_Query_QueryGetSpStoragePriceByTime_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryGetSpStoragePriceByTimeRequest +func request_Query_QuerySpStoragePrice_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QuerySpStoragePriceRequest var metadata runtime.ServerMetadata var ( @@ -109,24 +109,13 @@ func request_Query_QueryGetSpStoragePriceByTime_0(ctx context.Context, marshaler return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "sp_addr", err) } - val, ok = pathParams["timestamp"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "timestamp") - } - - protoReq.Timestamp, err = runtime.Int64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "timestamp", err) - } - - msg, err := client.QueryGetSpStoragePriceByTime(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + msg, err := client.QuerySpStoragePrice(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } -func local_request_Query_QueryGetSpStoragePriceByTime_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryGetSpStoragePriceByTimeRequest +func local_request_Query_QuerySpStoragePrice_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QuerySpStoragePriceRequest var metadata runtime.ServerMetadata var ( @@ -147,24 +136,13 @@ func local_request_Query_QueryGetSpStoragePriceByTime_0(ctx context.Context, mar return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "sp_addr", err) } - val, ok = pathParams["timestamp"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "timestamp") - } - - protoReq.Timestamp, err = runtime.Int64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "timestamp", err) - } - - msg, err := server.QueryGetSpStoragePriceByTime(ctx, &protoReq) + msg, err := server.QuerySpStoragePrice(ctx, &protoReq) return msg, metadata, err } -func request_Query_QueryGetSecondarySpStorePriceByTime_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryGetSecondarySpStorePriceByTimeRequest +func request_Query_QueryGlobalSpStorePriceByTime_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryGlobalSpStorePriceByTimeRequest var metadata runtime.ServerMetadata var ( @@ -185,13 +163,13 @@ func request_Query_QueryGetSecondarySpStorePriceByTime_0(ctx context.Context, ma return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "timestamp", err) } - msg, err := client.QueryGetSecondarySpStorePriceByTime(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + msg, err := client.QueryGlobalSpStorePriceByTime(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err } -func local_request_Query_QueryGetSecondarySpStorePriceByTime_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryGetSecondarySpStorePriceByTimeRequest +func local_request_Query_QueryGlobalSpStorePriceByTime_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryGlobalSpStorePriceByTimeRequest var metadata runtime.ServerMetadata var ( @@ -212,7 +190,7 @@ func local_request_Query_QueryGetSecondarySpStorePriceByTime_0(ctx context.Conte return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "timestamp", err) } - msg, err := server.QueryGetSecondarySpStorePriceByTime(ctx, &protoReq) + msg, err := server.QueryGlobalSpStorePriceByTime(ctx, &protoReq) return msg, metadata, err } @@ -395,7 +373,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv }) - mux.Handle("GET", pattern_Query_QueryGetSpStoragePriceByTime_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QuerySpStoragePrice_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream @@ -406,7 +384,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := local_request_Query_QueryGetSpStoragePriceByTime_0(rctx, inboundMarshaler, server, req, pathParams) + resp, md, err := local_request_Query_QuerySpStoragePrice_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 { @@ -414,11 +392,11 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } - forward_Query_QueryGetSpStoragePriceByTime_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QuerySpStoragePrice_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryGetSecondarySpStorePriceByTime_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryGlobalSpStorePriceByTime_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream @@ -429,7 +407,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := local_request_Query_QueryGetSecondarySpStorePriceByTime_0(rctx, inboundMarshaler, server, req, pathParams) + resp, md, err := local_request_Query_QueryGlobalSpStorePriceByTime_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 { @@ -437,7 +415,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv return } - forward_Query_QueryGetSecondarySpStorePriceByTime_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryGlobalSpStorePriceByTime_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) @@ -591,7 +569,7 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie }) - mux.Handle("GET", pattern_Query_QueryGetSpStoragePriceByTime_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QuerySpStoragePrice_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) @@ -600,18 +578,18 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := request_Query_QueryGetSpStoragePriceByTime_0(rctx, inboundMarshaler, client, req, pathParams) + resp, md, err := request_Query_QuerySpStoragePrice_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_QueryGetSpStoragePriceByTime_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QuerySpStoragePrice_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) - mux.Handle("GET", pattern_Query_QueryGetSecondarySpStorePriceByTime_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle("GET", pattern_Query_QueryGlobalSpStorePriceByTime_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) @@ -620,14 +598,14 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return } - resp, md, err := request_Query_QueryGetSecondarySpStorePriceByTime_0(rctx, inboundMarshaler, client, req, pathParams) + resp, md, err := request_Query_QueryGlobalSpStorePriceByTime_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_QueryGetSecondarySpStorePriceByTime_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + forward_Query_QueryGlobalSpStorePriceByTime_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) }) @@ -699,9 +677,9 @@ var ( pattern_Query_StorageProviders_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"greenfield", "storage_providers"}, "", runtime.AssumeColonVerbOpt(false))) - pattern_Query_QueryGetSpStoragePriceByTime_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4}, []string{"greenfield", "sp", "get_sp_storage_price_by_time", "sp_addr", "timestamp"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_QuerySpStoragePrice_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"greenfield", "sp", "sp_storage_price", "sp_addr"}, "", runtime.AssumeColonVerbOpt(false))) - pattern_Query_QueryGetSecondarySpStorePriceByTime_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"greenfield", "sp", "get_secondary_sp_store_price_by_time", "timestamp"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_QueryGlobalSpStorePriceByTime_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"greenfield", "sp", "global_sp_store_price_by_time", "timestamp"}, "", runtime.AssumeColonVerbOpt(false))) pattern_Query_StorageProvider_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2}, []string{"greenfield", "storage_provider", "id"}, "", runtime.AssumeColonVerbOpt(false))) @@ -715,9 +693,9 @@ var ( forward_Query_StorageProviders_0 = runtime.ForwardResponseMessage - forward_Query_QueryGetSpStoragePriceByTime_0 = runtime.ForwardResponseMessage + forward_Query_QuerySpStoragePrice_0 = runtime.ForwardResponseMessage - forward_Query_QueryGetSecondarySpStorePriceByTime_0 = runtime.ForwardResponseMessage + forward_Query_QueryGlobalSpStorePriceByTime_0 = runtime.ForwardResponseMessage forward_Query_StorageProvider_0 = runtime.ForwardResponseMessage diff --git a/x/sp/types/types.pb.go b/x/sp/types/types.pb.go index 4c40068fd..36d19af42 100644 --- a/x/sp/types/types.pb.go +++ b/x/sp/types/types.pb.go @@ -398,26 +398,30 @@ func (m *SpStoragePrice) GetFreeReadQuota() uint64 { return 0 } -// global secondary sp store price, the price for all secondary sps -type SecondarySpStorePrice struct { +// global sp store price, the price for all sps +type GlobalSpStorePrice struct { // update time, unix timestamp in seconds UpdateTimeSec int64 `protobuf:"varint,1,opt,name=update_time_sec,json=updateTimeSec,proto3" json:"update_time_sec,omitempty"` - // store price, in bnb wei per charge byte - StorePrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=store_price,json=storePrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"store_price"` + // read price, in bnb wei per charge byte + ReadPrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=read_price,json=readPrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"read_price"` + // primary store price, in bnb wei per charge byte + PrimaryStorePrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=primary_store_price,json=primaryStorePrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"primary_store_price"` + // secondary store price, in bnb wei per charge byte + SecondaryStorePrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=secondary_store_price,json=secondaryStorePrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"secondary_store_price"` } -func (m *SecondarySpStorePrice) Reset() { *m = SecondarySpStorePrice{} } -func (m *SecondarySpStorePrice) String() string { return proto.CompactTextString(m) } -func (*SecondarySpStorePrice) ProtoMessage() {} -func (*SecondarySpStorePrice) Descriptor() ([]byte, []int) { +func (m *GlobalSpStorePrice) Reset() { *m = GlobalSpStorePrice{} } +func (m *GlobalSpStorePrice) String() string { return proto.CompactTextString(m) } +func (*GlobalSpStorePrice) ProtoMessage() {} +func (*GlobalSpStorePrice) Descriptor() ([]byte, []int) { return fileDescriptor_7a9af9b5be8c2eeb, []int{4} } -func (m *SecondarySpStorePrice) XXX_Unmarshal(b []byte) error { +func (m *GlobalSpStorePrice) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } -func (m *SecondarySpStorePrice) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { +func (m *GlobalSpStorePrice) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { - return xxx_messageInfo_SecondarySpStorePrice.Marshal(b, m, deterministic) + return xxx_messageInfo_GlobalSpStorePrice.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) @@ -427,19 +431,19 @@ func (m *SecondarySpStorePrice) XXX_Marshal(b []byte, deterministic bool) ([]byt return b[:n], nil } } -func (m *SecondarySpStorePrice) XXX_Merge(src proto.Message) { - xxx_messageInfo_SecondarySpStorePrice.Merge(m, src) +func (m *GlobalSpStorePrice) XXX_Merge(src proto.Message) { + xxx_messageInfo_GlobalSpStorePrice.Merge(m, src) } -func (m *SecondarySpStorePrice) XXX_Size() int { +func (m *GlobalSpStorePrice) XXX_Size() int { return m.Size() } -func (m *SecondarySpStorePrice) XXX_DiscardUnknown() { - xxx_messageInfo_SecondarySpStorePrice.DiscardUnknown(m) +func (m *GlobalSpStorePrice) XXX_DiscardUnknown() { + xxx_messageInfo_GlobalSpStorePrice.DiscardUnknown(m) } -var xxx_messageInfo_SecondarySpStorePrice proto.InternalMessageInfo +var xxx_messageInfo_GlobalSpStorePrice proto.InternalMessageInfo -func (m *SecondarySpStorePrice) GetUpdateTimeSec() int64 { +func (m *GlobalSpStorePrice) GetUpdateTimeSec() int64 { if m != nil { return m.UpdateTimeSec } @@ -569,7 +573,7 @@ func init() { proto.RegisterType((*StorageProvider)(nil), "greenfield.sp.StorageProvider") proto.RegisterType((*RewardInfo)(nil), "greenfield.sp.RewardInfo") proto.RegisterType((*SpStoragePrice)(nil), "greenfield.sp.SpStoragePrice") - proto.RegisterType((*SecondarySpStorePrice)(nil), "greenfield.sp.SecondarySpStorePrice") + proto.RegisterType((*GlobalSpStorePrice)(nil), "greenfield.sp.GlobalSpStorePrice") proto.RegisterType((*SpMaintenanceStats)(nil), "greenfield.sp.SpMaintenanceStats") proto.RegisterType((*MaintenanceRecord)(nil), "greenfield.sp.MaintenanceRecord") } @@ -577,68 +581,70 @@ func init() { func init() { proto.RegisterFile("greenfield/sp/types.proto", fileDescriptor_7a9af9b5be8c2eeb) } var fileDescriptor_7a9af9b5be8c2eeb = []byte{ - // 962 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x55, 0x41, 0x6f, 0x1b, 0x45, - 0x14, 0xf6, 0xda, 0x8e, 0xd3, 0x3c, 0x27, 0xb1, 0x3b, 0x4d, 0xe8, 0x26, 0x08, 0x37, 0xca, 0x21, - 0x84, 0x4a, 0xb1, 0xd5, 0x70, 0xa8, 0x04, 0x5c, 0x1c, 0xdb, 0x54, 0x0b, 0x6d, 0x54, 0xd6, 0x29, - 0x42, 0x20, 0xb4, 0x1a, 0xef, 0xbc, 0x38, 0xa3, 0xd8, 0x33, 0xdb, 0x99, 0x71, 0x8a, 0xff, 0x01, - 0x47, 0x7e, 0x01, 0x07, 0xf8, 0x05, 0x48, 0x3d, 0xf1, 0x0b, 0x7a, 0xac, 0x7a, 0x42, 0x1c, 0x2a, - 0x94, 0xfc, 0x11, 0xb4, 0x3b, 0xb3, 0x8e, 0x09, 0x48, 0x16, 0x52, 0x4f, 0xf6, 0xfb, 0xde, 0xfb, - 0xbe, 0x7d, 0x33, 0xf3, 0xbd, 0x19, 0xd8, 0x1a, 0x2a, 0x44, 0x71, 0xca, 0x71, 0xc4, 0x5a, 0x3a, - 0x69, 0x99, 0x69, 0x82, 0xba, 0x99, 0x28, 0x69, 0x24, 0x59, 0xbb, 0x4e, 0x35, 0x75, 0xb2, 0xdd, - 0x88, 0xa5, 0x1e, 0x4b, 0xdd, 0x1a, 0x50, 0x8d, 0xad, 0x8b, 0x07, 0x03, 0x34, 0xf4, 0x41, 0x2b, - 0x96, 0x5c, 0xd8, 0xf2, 0xed, 0x2d, 0x9b, 0x8f, 0xb2, 0xa8, 0x65, 0x03, 0x97, 0xda, 0x18, 0xca, - 0xa1, 0xb4, 0x78, 0xfa, 0xcf, 0xa2, 0xbb, 0xbf, 0x78, 0x50, 0xed, 0xa2, 0x8e, 0x15, 0x4f, 0x0c, - 0x97, 0x82, 0xf8, 0xb0, 0x3c, 0x96, 0x82, 0x9f, 0xa3, 0xf2, 0xbd, 0x1d, 0x6f, 0x7f, 0x25, 0xcc, - 0x43, 0xb2, 0x0d, 0xb7, 0x38, 0x43, 0x61, 0xb8, 0x99, 0xfa, 0xc5, 0x2c, 0x35, 0x8b, 0x53, 0xd6, - 0x0b, 0x1c, 0x68, 0x6e, 0xd0, 0x2f, 0x59, 0x96, 0x0b, 0xc9, 0x47, 0x50, 0xd7, 0x18, 0x4f, 0x14, - 0x37, 0xd3, 0x28, 0x96, 0xc2, 0xd0, 0xd8, 0xf8, 0xe5, 0xac, 0xa4, 0x96, 0xe3, 0x1d, 0x0b, 0xa7, - 0x22, 0x0c, 0x0d, 0xe5, 0x23, 0xed, 0x2f, 0x59, 0x11, 0x17, 0xee, 0xfe, 0xbe, 0x04, 0xb5, 0xbe, - 0x91, 0x8a, 0x0e, 0xf1, 0xa9, 0x92, 0x17, 0x9c, 0xa1, 0x22, 0xeb, 0x50, 0xe4, 0x2c, 0xeb, 0x71, - 0x2d, 0x2c, 0x72, 0x46, 0x3a, 0x50, 0x97, 0x09, 0x2a, 0x6a, 0xa4, 0x8a, 0x28, 0x63, 0x0a, 0xb5, - 0xb6, 0x6d, 0x1e, 0xf9, 0x6f, 0x5e, 0x1e, 0x6c, 0xb8, 0xad, 0x68, 0xdb, 0x4c, 0xdf, 0x28, 0x2e, - 0x86, 0x61, 0x2d, 0x67, 0x38, 0x98, 0xb4, 0xa1, 0x76, 0x3a, 0x11, 0x8c, 0x8b, 0xe1, 0x4c, 0xa3, - 0xb4, 0x40, 0x63, 0xdd, 0x11, 0x72, 0x89, 0x4f, 0x61, 0x55, 0x23, 0x1d, 0xcd, 0xf8, 0xe5, 0x05, - 0xfc, 0x6a, 0x5a, 0x9d, 0x93, 0x3b, 0x50, 0xa7, 0x49, 0xa2, 0xe4, 0xc5, 0x9c, 0xc0, 0xd2, 0xa2, - 0x45, 0xe4, 0x8c, 0x5c, 0xe4, 0x21, 0xc0, 0x30, 0x9e, 0xd1, 0x2b, 0x0b, 0xe8, 0x2b, 0xc3, 0x38, - 0x27, 0x06, 0x70, 0x67, 0x4c, 0xb9, 0x30, 0x28, 0xa8, 0x88, 0x71, 0xa6, 0xb0, 0xbc, 0x40, 0x81, - 0xcc, 0x91, 0x72, 0x29, 0x0a, 0x6b, 0x46, 0x1a, 0x3a, 0x8a, 0x18, 0x26, 0x52, 0x73, 0xe3, 0xdf, - 0xca, 0x44, 0x3e, 0x7b, 0xf5, 0xf6, 0x5e, 0xe1, 0xcf, 0xb7, 0xf7, 0xf6, 0x86, 0xdc, 0x9c, 0x4d, - 0x06, 0xcd, 0x58, 0x8e, 0x9d, 0x49, 0xdd, 0xcf, 0x81, 0x66, 0xe7, 0xce, 0xff, 0x81, 0x30, 0x6f, - 0x5e, 0x1e, 0x80, 0xfb, 0x64, 0x20, 0x4c, 0xb8, 0x9a, 0x49, 0x76, 0xad, 0x22, 0x39, 0x80, 0x8a, - 0x36, 0xd4, 0x4c, 0xb4, 0xbf, 0xb2, 0xe3, 0xed, 0xaf, 0x1f, 0x6e, 0x36, 0xff, 0x31, 0x2a, 0xcd, - 0x7e, 0x96, 0x0c, 0x5d, 0x51, 0x6a, 0x5f, 0x14, 0x2c, 0x91, 0x5c, 0x18, 0x1f, 0xac, 0x7d, 0xf3, - 0x98, 0x1c, 0x41, 0x95, 0x5d, 0xcf, 0x80, 0x5f, 0xdd, 0xf1, 0xf6, 0xab, 0x87, 0xdb, 0x37, 0xf4, - 0xe6, 0xa6, 0xe4, 0xa8, 0x9c, 0xae, 0x23, 0x9c, 0x27, 0x91, 0xbb, 0xb0, 0x3c, 0x18, 0xe9, 0xe8, - 0x1c, 0xa7, 0xfe, 0xea, 0x8e, 0xb7, 0xbf, 0x1a, 0x56, 0x06, 0x23, 0xfd, 0x25, 0x4e, 0x77, 0xa7, - 0x00, 0x21, 0xbe, 0xa0, 0x8a, 0x05, 0xe2, 0x54, 0x92, 0x43, 0x58, 0xce, 0xf7, 0xd5, 0x5b, 0xb0, - 0xaf, 0x79, 0x21, 0x79, 0x08, 0x15, 0x3a, 0x96, 0x13, 0x61, 0x32, 0x43, 0x57, 0x0f, 0xb7, 0x9a, - 0xae, 0x3e, 0xbd, 0x05, 0x9a, 0xee, 0x16, 0x68, 0x76, 0x24, 0xcf, 0x1b, 0x73, 0xe5, 0xbb, 0xbf, - 0x15, 0x61, 0xbd, 0x9f, 0xcc, 0x26, 0x87, 0xc7, 0x48, 0xee, 0xc0, 0x92, 0x4e, 0xa2, 0xd9, 0xe4, - 0x94, 0x75, 0x12, 0x30, 0xb2, 0x07, 0xb5, 0x49, 0xc2, 0xa8, 0xc1, 0xc8, 0xf0, 0x31, 0x46, 0x1a, - 0xe3, 0xec, 0x4b, 0xa5, 0x70, 0xcd, 0xc2, 0x27, 0x7c, 0x8c, 0x7d, 0x8c, 0xc9, 0x77, 0x00, 0x0a, - 0x29, 0x8b, 0x92, 0x54, 0xca, 0x4d, 0xc6, 0xff, 0x39, 0xd2, 0x2e, 0xc6, 0x73, 0x47, 0xda, 0xc5, - 0x38, 0x5c, 0x49, 0xf5, 0x6c, 0x67, 0x7b, 0x50, 0x3b, 0x55, 0x88, 0x51, 0xf6, 0x85, 0xe7, 0x13, - 0x69, 0x68, 0x36, 0x3b, 0xe5, 0x70, 0x2d, 0x85, 0x43, 0xa4, 0xec, 0xab, 0x14, 0x24, 0xdf, 0x43, - 0x55, 0x1b, 0xa9, 0xd0, 0x75, 0xb1, 0xf4, 0x0e, 0xba, 0x80, 0x4c, 0x30, 0x6b, 0x63, 0xf7, 0x67, - 0x0f, 0x36, 0xfb, 0x18, 0x4b, 0xc1, 0xa8, 0x9a, 0xda, 0xcd, 0xc3, 0x59, 0x83, 0x37, 0x77, 0xc9, - 0xfb, 0xaf, 0x5d, 0xba, 0xd1, 0x60, 0xf1, 0x1d, 0x37, 0xf8, 0x14, 0x48, 0x3f, 0x79, 0x72, 0x3d, - 0x72, 0xa9, 0xcf, 0x35, 0xf9, 0x04, 0x96, 0x15, 0xc6, 0x52, 0xb1, 0xd4, 0x57, 0xa5, 0xfd, 0xea, - 0xe1, 0xce, 0x0d, 0xfb, 0xce, 0x31, 0xc2, 0xac, 0x30, 0xcc, 0x09, 0xe9, 0x92, 0x6f, 0xff, 0x2b, - 0x4d, 0xde, 0x83, 0xca, 0x19, 0xf2, 0xe1, 0x99, 0x71, 0xab, 0x74, 0x51, 0x7a, 0xa3, 0x2b, 0x7c, - 0x3e, 0x41, 0x6d, 0x22, 0x36, 0x51, 0x34, 0x9b, 0x18, 0xeb, 0x96, 0x9a, 0xc3, 0xbb, 0x0e, 0x26, - 0x1f, 0x42, 0x8d, 0xc6, 0x66, 0x92, 0x5e, 0x03, 0x79, 0x65, 0x29, 0xab, 0x5c, 0xb7, 0xf0, 0xac, - 0xf0, 0x83, 0xd4, 0x58, 0x56, 0x93, 0xda, 0xf7, 0xa1, 0x94, 0x5a, 0x23, 0x43, 0xda, 0xe6, 0xbe, - 0x86, 0x8a, 0x9d, 0x66, 0xb2, 0x09, 0xb7, 0xfb, 0x27, 0xed, 0x93, 0x67, 0xfd, 0x28, 0x38, 0x8e, - 0xfa, 0xbd, 0xf0, 0xeb, 0xa0, 0xd3, 0xab, 0x17, 0xc8, 0x06, 0xd4, 0xaf, 0xe1, 0x2f, 0xda, 0xc1, - 0xe3, 0x5e, 0xb7, 0xee, 0x91, 0xf7, 0xe1, 0xae, 0x43, 0x1f, 0x85, 0xed, 0x4e, 0xef, 0xf3, 0x67, - 0x8f, 0xa3, 0xde, 0x37, 0xc1, 0x49, 0x70, 0xfc, 0xa8, 0x5e, 0x24, 0x5b, 0xb0, 0x79, 0x4d, 0x79, - 0xd2, 0x0e, 0x8e, 0x4f, 0x7a, 0xc7, 0xed, 0xe3, 0x4e, 0xaf, 0x5e, 0xda, 0x2e, 0xff, 0xf8, 0x6b, - 0xa3, 0x70, 0xd4, 0x7d, 0x75, 0xd9, 0xf0, 0x5e, 0x5f, 0x36, 0xbc, 0xbf, 0x2e, 0x1b, 0xde, 0x4f, - 0x57, 0x8d, 0xc2, 0xeb, 0xab, 0x46, 0xe1, 0x8f, 0xab, 0x46, 0xe1, 0xdb, 0xfb, 0x73, 0x67, 0x38, - 0x10, 0x83, 0x83, 0xf8, 0x8c, 0x72, 0xd1, 0x9a, 0x7b, 0xc3, 0x7f, 0x98, 0xbd, 0xe2, 0x83, 0x4a, - 0xf6, 0xcc, 0x7e, 0xfc, 0x77, 0x00, 0x00, 0x00, 0xff, 0xff, 0xb5, 0x3d, 0xbe, 0xfd, 0xe3, 0x07, - 0x00, 0x00, + // 999 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x56, 0xc1, 0x6e, 0x23, 0x45, + 0x10, 0xf5, 0xd8, 0x8e, 0xb3, 0x29, 0x27, 0xb1, 0xd3, 0x49, 0xd8, 0x49, 0x10, 0xde, 0xc8, 0x87, + 0x10, 0x56, 0x8a, 0xad, 0x0d, 0x87, 0x95, 0x80, 0x8b, 0x63, 0x9b, 0xc8, 0xb0, 0x1b, 0x2d, 0xe3, + 0x2c, 0x42, 0x20, 0x34, 0x6a, 0x4f, 0x57, 0x9c, 0x56, 0xec, 0xee, 0xd9, 0xee, 0x76, 0x16, 0xff, + 0x01, 0x47, 0xbe, 0x80, 0x03, 0x7c, 0x01, 0xd2, 0x9e, 0xf8, 0x82, 0x3d, 0xae, 0xf6, 0x84, 0x38, + 0xac, 0x50, 0xf2, 0x15, 0xdc, 0xd0, 0xcc, 0xf4, 0x8c, 0x4d, 0x38, 0x58, 0x48, 0x39, 0xd9, 0xf5, + 0xaa, 0xde, 0xeb, 0x9a, 0xea, 0xaa, 0x9a, 0x81, 0x9d, 0xa1, 0x42, 0x14, 0xe7, 0x1c, 0x47, 0xac, + 0xa9, 0xc3, 0xa6, 0x99, 0x86, 0xa8, 0x1b, 0xa1, 0x92, 0x46, 0x92, 0xb5, 0x99, 0xab, 0xa1, 0xc3, + 0xdd, 0x5a, 0x20, 0xf5, 0x58, 0xea, 0xe6, 0x80, 0x6a, 0x6c, 0x5e, 0x3d, 0x1a, 0xa0, 0xa1, 0x8f, + 0x9a, 0x81, 0xe4, 0x22, 0x09, 0xdf, 0xdd, 0x49, 0xfc, 0x7e, 0x6c, 0x35, 0x13, 0xc3, 0xba, 0xb6, + 0x86, 0x72, 0x28, 0x13, 0x3c, 0xfa, 0x97, 0xa0, 0xf5, 0x5f, 0x1c, 0x28, 0x77, 0x50, 0x07, 0x8a, + 0x87, 0x86, 0x4b, 0x41, 0x5c, 0x58, 0x1e, 0x4b, 0xc1, 0x2f, 0x51, 0xb9, 0xce, 0x9e, 0x73, 0xb0, + 0xe2, 0xa5, 0x26, 0xd9, 0x85, 0x7b, 0x9c, 0xa1, 0x30, 0xdc, 0x4c, 0xdd, 0x7c, 0xec, 0xca, 0xec, + 0x88, 0xf5, 0x12, 0x07, 0x9a, 0x1b, 0x74, 0x0b, 0x09, 0xcb, 0x9a, 0xe4, 0x23, 0xa8, 0x6a, 0x0c, + 0x26, 0x8a, 0x9b, 0xa9, 0x1f, 0x48, 0x61, 0x68, 0x60, 0xdc, 0x62, 0x1c, 0x52, 0x49, 0xf1, 0x76, + 0x02, 0x47, 0x22, 0x0c, 0x0d, 0xe5, 0x23, 0xed, 0x2e, 0x25, 0x22, 0xd6, 0xac, 0xff, 0xbe, 0x04, + 0x95, 0xbe, 0x91, 0x8a, 0x0e, 0xf1, 0x99, 0x92, 0x57, 0x9c, 0xa1, 0x22, 0xeb, 0x90, 0xe7, 0x2c, + 0xce, 0x71, 0xcd, 0xcb, 0x73, 0x46, 0xda, 0x50, 0x95, 0x21, 0x2a, 0x6a, 0xa4, 0xf2, 0x29, 0x63, + 0x0a, 0xb5, 0x4e, 0xd2, 0x3c, 0x76, 0xdf, 0xbe, 0x3a, 0xdc, 0xb2, 0xa5, 0x68, 0x25, 0x9e, 0xbe, + 0x51, 0x5c, 0x0c, 0xbd, 0x4a, 0xca, 0xb0, 0x30, 0x69, 0x41, 0xe5, 0x7c, 0x22, 0x18, 0x17, 0xc3, + 0x4c, 0xa3, 0xb0, 0x40, 0x63, 0xdd, 0x12, 0x52, 0x89, 0x4f, 0x61, 0x55, 0x23, 0x1d, 0x65, 0xfc, + 0xe2, 0x02, 0x7e, 0x39, 0x8a, 0x4e, 0xc9, 0x6d, 0xa8, 0xd2, 0x30, 0x54, 0xf2, 0x6a, 0x4e, 0x60, + 0x69, 0xd1, 0x43, 0xa4, 0x8c, 0x54, 0xe4, 0x31, 0xc0, 0x30, 0xc8, 0xe8, 0xa5, 0x05, 0xf4, 0x95, + 0x61, 0x90, 0x12, 0x7b, 0xb0, 0x39, 0xa6, 0x5c, 0x18, 0x14, 0x54, 0x04, 0x98, 0x29, 0x2c, 0x2f, + 0x50, 0x20, 0x73, 0xa4, 0x54, 0x8a, 0xc2, 0x9a, 0x91, 0x86, 0x8e, 0x7c, 0x86, 0xa1, 0xd4, 0xdc, + 0xb8, 0xf7, 0x62, 0x91, 0xcf, 0x5e, 0xbf, 0x7b, 0x90, 0xfb, 0xf3, 0xdd, 0x83, 0xfd, 0x21, 0x37, + 0x17, 0x93, 0x41, 0x23, 0x90, 0x63, 0xdb, 0xa4, 0xf6, 0xe7, 0x50, 0xb3, 0x4b, 0xdb, 0xff, 0x3d, + 0x61, 0xde, 0xbe, 0x3a, 0x04, 0x7b, 0x64, 0x4f, 0x18, 0x6f, 0x35, 0x96, 0xec, 0x24, 0x8a, 0xe4, + 0x10, 0x4a, 0xda, 0x50, 0x33, 0xd1, 0xee, 0xca, 0x9e, 0x73, 0xb0, 0x7e, 0xb4, 0xdd, 0xf8, 0xd7, + 0xa8, 0x34, 0xfa, 0xb1, 0xd3, 0xb3, 0x41, 0x51, 0xfb, 0xa2, 0x60, 0xa1, 0xe4, 0xc2, 0xb8, 0x90, + 0xb4, 0x6f, 0x6a, 0x93, 0x63, 0x28, 0xb3, 0xd9, 0x0c, 0xb8, 0xe5, 0x3d, 0xe7, 0xa0, 0x7c, 0xb4, + 0x7b, 0x4b, 0x6f, 0x6e, 0x4a, 0x8e, 0x8b, 0xd1, 0x73, 0x78, 0xf3, 0x24, 0x72, 0x1f, 0x96, 0x07, + 0x23, 0xed, 0x5f, 0xe2, 0xd4, 0x5d, 0xdd, 0x73, 0x0e, 0x56, 0xbd, 0xd2, 0x60, 0xa4, 0xbf, 0xc4, + 0x69, 0x7d, 0x0a, 0xe0, 0xe1, 0x4b, 0xaa, 0x58, 0x4f, 0x9c, 0x4b, 0x72, 0x04, 0xcb, 0x69, 0x5d, + 0x9d, 0x05, 0x75, 0x4d, 0x03, 0xc9, 0x63, 0x28, 0xd1, 0xb1, 0x9c, 0x08, 0x13, 0x37, 0x74, 0xf9, + 0x68, 0xa7, 0x61, 0xe3, 0xa3, 0x2d, 0xd0, 0xb0, 0x5b, 0xa0, 0xd1, 0x96, 0x3c, 0x4d, 0xcc, 0x86, + 0xd7, 0x7f, 0xcb, 0xc3, 0x7a, 0x3f, 0xcc, 0x26, 0x87, 0x07, 0x48, 0x36, 0x61, 0x49, 0x87, 0x7e, + 0x36, 0x39, 0x45, 0x1d, 0xf6, 0x18, 0xd9, 0x87, 0xca, 0x24, 0x64, 0xd4, 0xa0, 0x6f, 0xf8, 0x18, + 0x7d, 0x8d, 0x41, 0x7c, 0x52, 0xc1, 0x5b, 0x4b, 0xe0, 0x33, 0x3e, 0xc6, 0x3e, 0x06, 0xe4, 0x3b, + 0x00, 0x85, 0x94, 0xf9, 0x61, 0x24, 0x65, 0x27, 0xe3, 0xff, 0x5c, 0x69, 0x07, 0x83, 0xb9, 0x2b, + 0xed, 0x60, 0xe0, 0xad, 0x44, 0x7a, 0x49, 0x66, 0xfb, 0x50, 0x39, 0x57, 0x88, 0x7e, 0x7c, 0xc2, + 0x8b, 0x89, 0x34, 0x34, 0x9e, 0x9d, 0xa2, 0xb7, 0x16, 0xc1, 0x1e, 0x52, 0xf6, 0x55, 0x04, 0x92, + 0xef, 0xa1, 0xac, 0x8d, 0x54, 0x68, 0xb3, 0x58, 0xba, 0x83, 0x2c, 0x20, 0x16, 0x8c, 0xd3, 0xa8, + 0xff, 0x9d, 0x07, 0x72, 0x32, 0x92, 0x03, 0x3a, 0x4a, 0x2a, 0x87, 0x59, 0x76, 0xb7, 0x4b, 0xe4, + 0x2c, 0x2e, 0x51, 0xfe, 0x6e, 0x4b, 0x34, 0x82, 0xcd, 0x50, 0xf1, 0x31, 0x55, 0x53, 0x7f, 0xbe, + 0x04, 0x77, 0x71, 0x11, 0x1b, 0x56, 0x78, 0xee, 0x91, 0x43, 0xd8, 0xd6, 0x18, 0x48, 0xc1, 0x6e, + 0x9f, 0x57, 0xbc, 0x83, 0xf3, 0x36, 0x33, 0xe9, 0xd9, 0x89, 0xf5, 0x67, 0x40, 0xfa, 0xe1, 0xd3, + 0xd9, 0x36, 0x89, 0x46, 0x58, 0x93, 0x4f, 0x60, 0x59, 0x61, 0x20, 0x15, 0x8b, 0x46, 0xa6, 0x70, + 0x50, 0x3e, 0xda, 0xbb, 0x35, 0x99, 0x73, 0x0c, 0x2f, 0x0e, 0xf4, 0x52, 0x42, 0xfd, 0x67, 0x07, + 0x36, 0xfe, 0xe3, 0x26, 0xef, 0x41, 0xe9, 0x02, 0xf9, 0xf0, 0xc2, 0xd8, 0x3b, 0xb4, 0x56, 0xf4, + 0xb2, 0x52, 0xf8, 0x62, 0x82, 0xda, 0xf8, 0x6c, 0xa2, 0x68, 0xbc, 0x0c, 0x92, 0x41, 0xa8, 0x58, + 0xbc, 0x63, 0x61, 0xf2, 0x21, 0x54, 0x68, 0x60, 0x26, 0xd1, 0x86, 0x4b, 0x23, 0x0b, 0x71, 0xe4, + 0x7a, 0x02, 0x67, 0x81, 0x1f, 0x44, 0x0d, 0x91, 0x68, 0xd2, 0xe4, 0xd5, 0x57, 0x88, 0xae, 0x34, + 0x46, 0x5a, 0xe6, 0xa1, 0x86, 0x52, 0xb2, 0xa8, 0xc8, 0x36, 0x6c, 0xf4, 0xcf, 0x5a, 0x67, 0xcf, + 0xfb, 0x7e, 0xef, 0xd4, 0xef, 0x77, 0xbd, 0xaf, 0x7b, 0xed, 0x6e, 0x35, 0x47, 0xb6, 0xa0, 0x3a, + 0x83, 0xbf, 0x68, 0xf5, 0x9e, 0x74, 0x3b, 0x55, 0x87, 0xbc, 0x0f, 0xf7, 0x2d, 0x7a, 0xe2, 0xb5, + 0xda, 0xdd, 0xcf, 0x9f, 0x3f, 0xf1, 0xbb, 0xdf, 0xf4, 0xce, 0x7a, 0xa7, 0x27, 0xd5, 0x3c, 0xd9, + 0x81, 0xed, 0x19, 0xe5, 0x69, 0xab, 0x77, 0x7a, 0xd6, 0x3d, 0x6d, 0x9d, 0xb6, 0xbb, 0xd5, 0xc2, + 0x6e, 0xf1, 0xc7, 0x5f, 0x6b, 0xb9, 0xe3, 0xce, 0xeb, 0xeb, 0x9a, 0xf3, 0xe6, 0xba, 0xe6, 0xfc, + 0x75, 0x5d, 0x73, 0x7e, 0xba, 0xa9, 0xe5, 0xde, 0xdc, 0xd4, 0x72, 0x7f, 0xdc, 0xd4, 0x72, 0xdf, + 0x3e, 0x9c, 0xbb, 0xcc, 0x81, 0x18, 0x1c, 0x06, 0x17, 0x94, 0x8b, 0xe6, 0xdc, 0xe7, 0xc9, 0x0f, + 0xd9, 0x07, 0xca, 0xa0, 0x14, 0x7f, 0x41, 0x7c, 0xfc, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xc4, + 0xb8, 0x2c, 0x5d, 0xbe, 0x08, 0x00, 0x00, } func (m *Description) Marshal() (dAtA []byte, err error) { @@ -906,7 +912,7 @@ func (m *SpStoragePrice) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } -func (m *SecondarySpStorePrice) Marshal() (dAtA []byte, err error) { +func (m *GlobalSpStorePrice) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -916,20 +922,40 @@ func (m *SecondarySpStorePrice) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *SecondarySpStorePrice) MarshalTo(dAtA []byte) (int, error) { +func (m *GlobalSpStorePrice) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *SecondarySpStorePrice) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *GlobalSpStorePrice) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l { - size := m.StorePrice.Size() + size := m.SecondaryStorePrice.Size() i -= size - if _, err := m.StorePrice.MarshalTo(dAtA[i:]); err != nil { + if _, err := m.SecondaryStorePrice.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + { + size := m.PrimaryStorePrice.Size() + i -= size + if _, err := m.PrimaryStorePrice.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + { + size := m.ReadPrice.Size() + i -= size + if _, err := m.ReadPrice.MarshalTo(dAtA[i:]); err != nil { return 0, err } i = encodeVarintTypes(dAtA, i, uint64(size)) @@ -1152,7 +1178,7 @@ func (m *SpStoragePrice) Size() (n int) { return n } -func (m *SecondarySpStorePrice) Size() (n int) { +func (m *GlobalSpStorePrice) Size() (n int) { if m == nil { return 0 } @@ -1161,7 +1187,11 @@ func (m *SecondarySpStorePrice) Size() (n int) { if m.UpdateTimeSec != 0 { n += 1 + sovTypes(uint64(m.UpdateTimeSec)) } - l = m.StorePrice.Size() + l = m.ReadPrice.Size() + n += 1 + l + sovTypes(uint64(l)) + l = m.PrimaryStorePrice.Size() + n += 1 + l + sovTypes(uint64(l)) + l = m.SecondaryStorePrice.Size() n += 1 + l + sovTypes(uint64(l)) return n } @@ -2121,7 +2151,7 @@ func (m *SpStoragePrice) Unmarshal(dAtA []byte) error { } return nil } -func (m *SecondarySpStorePrice) Unmarshal(dAtA []byte) error { +func (m *GlobalSpStorePrice) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2144,10 +2174,10 @@ func (m *SecondarySpStorePrice) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: SecondarySpStorePrice: wiretype end group for non-group") + return fmt.Errorf("proto: GlobalSpStorePrice: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: SecondarySpStorePrice: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: GlobalSpStorePrice: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -2171,7 +2201,7 @@ func (m *SecondarySpStorePrice) Unmarshal(dAtA []byte) error { } case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field StorePrice", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field ReadPrice", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -2199,7 +2229,75 @@ func (m *SecondarySpStorePrice) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.StorePrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.ReadPrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PrimaryStorePrice", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + 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 ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.PrimaryStorePrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SecondaryStorePrice", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + 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 ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.SecondaryStorePrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex diff --git a/x/storage/keeper/keeper_object_test.go b/x/storage/keeper/keeper_object_test.go index ba79025ba..013711ef7 100644 --- a/x/storage/keeper/keeper_object_test.go +++ b/x/storage/keeper/keeper_object_test.go @@ -181,7 +181,7 @@ func (s *TestSuite) TestCreateObject() { BucketName: bucketInfo.BucketName, ObjectName: objectName, }) - s.paymentKeeper.EXPECT().GetStoragePrice(gomock.Any(), gomock.Any()).Return(types4.StoragePrice{ + s.spKeeper.EXPECT().GetGlobalSpStorePriceByTime(gomock.Any(), gomock.Any()).Return(types3.GlobalSpStorePrice{ ReadPrice: sdk.NewDec(1), PrimaryStorePrice: sdk.NewDec(2), SecondaryStorePrice: sdk.NewDec(1), diff --git a/x/storage/keeper/payment.go b/x/storage/keeper/payment.go index ff047bbc6..87d6953e4 100644 --- a/x/storage/keeper/payment.go +++ b/x/storage/keeper/payment.go @@ -3,6 +3,8 @@ package keeper import ( "fmt" + sptypes "github.com/bnb-chain/greenfield/x/sp/types" + "cosmossdk.io/errors" sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" @@ -63,10 +65,7 @@ func (k Keeper) GetBucketReadBill(ctx sdk.Context, bucketInfo *storagetypes.Buck return userFlows, fmt.Errorf("get GVG family failed: %d", bucketInfo.GlobalVirtualGroupFamilyId) } - price, err := k.paymentKeeper.GetStoragePrice(ctx, types.StoragePriceParams{ - PrimarySp: gvgFamily.PrimarySpId, - PriceTime: internalBucketInfo.PriceTime, - }) + price, err := k.spKeeper.GetGlobalSpStorePriceByTime(ctx, internalBucketInfo.PriceTime) if err != nil { return userFlows, fmt.Errorf("get storage price failed: %w", err) } @@ -161,18 +160,13 @@ func (k Keeper) UnlockAndChargeObjectStoreFee(ctx sdk.Context, primarySpId uint3 return k.ChargeObjectStoreFee(ctx, primarySpId, bucketInfo, internalBucketInfo, objectInfo) } -func (k Keeper) IsPriceChanged(ctx sdk.Context, primarySpId uint32, priceTime int64) (bool, *types.StoragePrice, sdk.Dec, *types.StoragePrice, sdk.Dec, error) { - prePrice, err := k.paymentKeeper.GetStoragePrice(ctx, types.StoragePriceParams{ - PrimarySp: primarySpId, - PriceTime: priceTime, - }) +func (k Keeper) IsPriceChanged(ctx sdk.Context, primarySpId uint32, priceTime int64) (bool, *sptypes.GlobalSpStorePrice, sdk.Dec, *sptypes.GlobalSpStorePrice, sdk.Dec, error) { + prePrice, err := k.spKeeper.GetGlobalSpStorePriceByTime(ctx, priceTime) if err != nil { return false, nil, sdk.ZeroDec(), nil, sdk.ZeroDec(), err } - currentPrice, err := k.paymentKeeper.GetStoragePrice(ctx, types.StoragePriceParams{ - PrimarySp: primarySpId, - PriceTime: ctx.BlockTime().Unix(), - }) + + currentPrice, err := k.spKeeper.GetGlobalSpStorePriceByTime(ctx, ctx.BlockTime().Unix()) if err != nil { return false, nil, sdk.ZeroDec(), nil, sdk.ZeroDec(), err } @@ -263,10 +257,7 @@ func (k Keeper) ChargeObjectStoreFeeForEarlyDeletion(ctx sdk.Context, bucketInfo } paymentAddr := sdk.MustAccAddressFromHex(bucketInfo.PaymentAddress) - price, err := k.paymentKeeper.GetStoragePrice(ctx, types.StoragePriceParams{ - PrimarySp: gvgFamily.PrimarySpId, - PriceTime: internalBucketInfo.PriceTime, - }) + price, err := k.spKeeper.GetGlobalSpStorePriceByTime(ctx, internalBucketInfo.PriceTime) if err != nil { return fmt.Errorf("get storage price failed: %w", err) } @@ -375,10 +366,7 @@ func (k Keeper) ChargeViaObjectChange(ctx sdk.Context, bucketInfo *storagetypes. return fmt.Errorf("get GVG family failed: %d", bucketInfo.GlobalVirtualGroupFamilyId) } - price, err := k.paymentKeeper.GetStoragePrice(ctx, types.StoragePriceParams{ - PrimarySp: gvgFamily.PrimarySpId, - PriceTime: internalBucketInfo.PriceTime, - }) + price, err := k.spKeeper.GetGlobalSpStorePriceByTime(ctx, internalBucketInfo.PriceTime) if err != nil { return fmt.Errorf("get storage price failed: %w", err) } @@ -424,7 +412,7 @@ func (k Keeper) ChargeViaObjectChange(ctx sdk.Context, bucketInfo *storagetypes. return nil } -func (k Keeper) calculateLVGStoreBill(ctx sdk.Context, price types.StoragePrice, params types.VersionedParams, +func (k Keeper) calculateLVGStoreBill(ctx sdk.Context, price sptypes.GlobalSpStorePrice, params types.VersionedParams, gvgFamily *vgtypes.GlobalVirtualGroupFamily, gvg *vgtypes.GlobalVirtualGroup, lvg *storagetypes.LocalVirtualGroup) []types.OutFlow { outFlows := make([]types.OutFlow, 0) @@ -473,10 +461,7 @@ func (k Keeper) GetBucketReadStoreBill(ctx sdk.Context, bucketInfo *storagetypes return userFlows, fmt.Errorf("get GVG family failed: %d", bucketInfo.GlobalVirtualGroupFamilyId) } - price, err := k.paymentKeeper.GetStoragePrice(ctx, types.StoragePriceParams{ - PrimarySp: gvgFamily.PrimarySpId, - PriceTime: internalBucketInfo.PriceTime, - }) + price, err := k.spKeeper.GetGlobalSpStorePriceByTime(ctx, internalBucketInfo.PriceTime) if err != nil { return userFlows, fmt.Errorf("get storage price failed: %w", err) } @@ -518,6 +503,7 @@ func (k Keeper) GetBucketReadStoreBill(ctx sdk.Context, bucketInfo *storagetypes func (k Keeper) UnChargeBucketReadStoreFee(ctx sdk.Context, bucketInfo *storagetypes.BucketInfo, internalBucketInfo *storagetypes.InternalBucketInfo) error { + ctx = ctx.WithValue(types.ForceUpdateStreamRecordKey, true) // used for bucket migration bill, err := k.GetBucketReadStoreBill(ctx, bucketInfo, internalBucketInfo) if err != nil { return fmt.Errorf("get bucket bill failed, bucket: %s, err: %s", bucketInfo.BucketName, err.Error()) @@ -532,6 +518,7 @@ func (k Keeper) UnChargeBucketReadStoreFee(ctx sdk.Context, bucketInfo *storaget func (k Keeper) ChargeBucketReadStoreFee(ctx sdk.Context, bucketInfo *storagetypes.BucketInfo, internalBucketInfo *storagetypes.InternalBucketInfo) error { + ctx = ctx.WithValue(types.ForceUpdateStreamRecordKey, true) // used for bucket migration internalBucketInfo.PriceTime = ctx.BlockTime().Unix() bill, err := k.GetBucketReadStoreBill(ctx, bucketInfo, internalBucketInfo) if err != nil { @@ -562,10 +549,7 @@ func getNegFlows(flows []types.OutFlow) (negFlows []types.OutFlow) { } func (k Keeper) GetObjectLockFee(ctx sdk.Context, primarySpId uint32, priceTime int64, payloadSize uint64) (amount sdkmath.Int, err error) { - price, err := k.paymentKeeper.GetStoragePrice(ctx, types.StoragePriceParams{ - PrimarySp: primarySpId, - PriceTime: priceTime, - }) + price, err := k.spKeeper.GetGlobalSpStorePriceByTime(ctx, priceTime) if err != nil { return amount, fmt.Errorf("get store price failed: %w", err) } diff --git a/x/storage/keeper/payment_test.go b/x/storage/keeper/payment_test.go index b58c2a8f7..1b8655534 100644 --- a/x/storage/keeper/payment_test.go +++ b/x/storage/keeper/payment_test.go @@ -104,12 +104,12 @@ func (s *TestSuite) TestGetObjectLockFee() { s.spKeeper.EXPECT().GetStorageProvider(gomock.Any(), gomock.Eq(primarySp.Id)). Return(primarySp, true).AnyTimes() - price := paymenttypes.StoragePrice{ + price := sptypes.GlobalSpStorePrice{ ReadPrice: sdk.NewDec(100), PrimaryStorePrice: sdk.NewDec(1000), SecondaryStorePrice: sdk.NewDec(500), } - s.paymentKeeper.EXPECT().GetStoragePrice(gomock.Any(), gomock.Any()). + s.spKeeper.EXPECT().GetGlobalSpStorePriceByTime(gomock.Any(), gomock.Any()). Return(price, nil).AnyTimes() params := paymenttypes.DefaultParams() s.paymentKeeper.EXPECT().GetVersionedParamsWithTs(gomock.Any(), gomock.Any()). @@ -143,12 +143,12 @@ func (s *TestSuite) TestGetBucketReadBill() { s.spKeeper.EXPECT().GetStorageProvider(gomock.Any(), gomock.Eq(primarySp.Id)). Return(primarySp, true).AnyTimes() - price := paymenttypes.StoragePrice{ + price := sptypes.GlobalSpStorePrice{ ReadPrice: sdk.NewDec(100), PrimaryStorePrice: sdk.NewDec(1000), SecondaryStorePrice: sdk.NewDec(500), } - s.paymentKeeper.EXPECT().GetStoragePrice(gomock.Any(), gomock.Any()). + s.spKeeper.EXPECT().GetGlobalSpStorePriceByTime(gomock.Any(), gomock.Any()). Return(price, nil).AnyTimes() params := paymenttypes.DefaultParams() s.paymentKeeper.EXPECT().GetVersionedParamsWithTs(gomock.Any(), gomock.Any()). @@ -205,12 +205,12 @@ func (s *TestSuite) TestGetBucketReadStoreBill() { s.spKeeper.EXPECT().GetStorageProvider(gomock.Any(), gomock.Eq(primarySp.Id)). Return(primarySp, true).AnyTimes() - price := paymenttypes.StoragePrice{ + price := sptypes.GlobalSpStorePrice{ ReadPrice: sdk.NewDec(100), PrimaryStorePrice: sdk.NewDec(1000), SecondaryStorePrice: sdk.NewDec(500), } - s.paymentKeeper.EXPECT().GetStoragePrice(gomock.Any(), gomock.Any()). + s.spKeeper.EXPECT().GetGlobalSpStorePriceByTime(gomock.Any(), gomock.Any()). Return(price, nil).AnyTimes() params := paymenttypes.DefaultParams() s.paymentKeeper.EXPECT().GetVersionedParamsWithTs(gomock.Any(), gomock.Any()). diff --git a/x/storage/types/expected_keepers.go b/x/storage/types/expected_keepers.go index 17bdf6812..90f2ac6d0 100644 --- a/x/storage/types/expected_keepers.go +++ b/x/storage/types/expected_keepers.go @@ -39,12 +39,12 @@ type SpKeeper interface { GetStorageProviderByOperatorAddr(ctx sdk.Context, addr sdk.AccAddress) (sp *sptypes.StorageProvider, found bool) GetStorageProviderBySealAddr(ctx sdk.Context, sealAddr sdk.AccAddress) (sp *sptypes.StorageProvider, found bool) GetStorageProviderByGcAddr(ctx sdk.Context, gcAddr sdk.AccAddress) (sp *sptypes.StorageProvider, found bool) + GetGlobalSpStorePriceByTime(ctx sdk.Context, time int64) (val sptypes.GlobalSpStorePrice, err error) } type PaymentKeeper interface { GetVersionedParamsWithTs(ctx sdk.Context, time int64) (paymenttypes.VersionedParams, error) IsPaymentAccountOwner(ctx sdk.Context, addr, owner sdk.AccAddress) bool - GetStoragePrice(ctx sdk.Context, params paymenttypes.StoragePriceParams) (price paymenttypes.StoragePrice, err error) ApplyUserFlowsList(ctx sdk.Context, userFlows []paymenttypes.UserFlows) (err error) UpdateStreamRecordByAddr(ctx sdk.Context, change *paymenttypes.StreamRecordChange) (ret *paymenttypes.StreamRecord, err error) } diff --git a/x/storage/types/expected_keepers_mocks.go b/x/storage/types/expected_keepers_mocks.go index 25abcc6a9..0232c9816 100644 --- a/x/storage/types/expected_keepers_mocks.go +++ b/x/storage/types/expected_keepers_mocks.go @@ -174,6 +174,21 @@ func (m *MockSpKeeper) EXPECT() *MockSpKeeperMockRecorder { return m.recorder } +// GetGlobalSpStorePriceByTime mocks base method. +func (m *MockSpKeeper) GetGlobalSpStorePriceByTime(ctx types3.Context, time int64) (types1.GlobalSpStorePrice, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetGlobalSpStorePriceByTime", ctx, time) + ret0, _ := ret[0].(types1.GlobalSpStorePrice) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetGlobalSpStorePriceByTime indicates an expected call of GetGlobalSpStorePriceByTime. +func (mr *MockSpKeeperMockRecorder) GetGlobalSpStorePriceByTime(ctx, time interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetGlobalSpStorePriceByTime", reflect.TypeOf((*MockSpKeeper)(nil).GetGlobalSpStorePriceByTime), ctx, time) +} + // GetStorageProvider mocks base method. func (m *MockSpKeeper) GetStorageProvider(ctx types3.Context, id uint32) (*types1.StorageProvider, bool) { m.ctrl.T.Helper() @@ -285,21 +300,6 @@ func (mr *MockPaymentKeeperMockRecorder) ApplyUserFlowsList(ctx, userFlows inter return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ApplyUserFlowsList", reflect.TypeOf((*MockPaymentKeeper)(nil).ApplyUserFlowsList), ctx, userFlows) } -// GetStoragePrice mocks base method. -func (m *MockPaymentKeeper) GetStoragePrice(ctx types3.Context, params types.StoragePriceParams) (types.StoragePrice, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetStoragePrice", ctx, params) - ret0, _ := ret[0].(types.StoragePrice) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetStoragePrice indicates an expected call of GetStoragePrice. -func (mr *MockPaymentKeeperMockRecorder) GetStoragePrice(ctx, params interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStoragePrice", reflect.TypeOf((*MockPaymentKeeper)(nil).GetStoragePrice), ctx, params) -} - // GetVersionedParamsWithTs mocks base method. func (m *MockPaymentKeeper) GetVersionedParamsWithTs(ctx types3.Context, time int64) (types.VersionedParams, error) { m.ctrl.T.Helper() From fd984afa80bcd2a96dd807ffc0849f69859b8ab4 Mon Sep 17 00:00:00 2001 From: forcodedancing Date: Tue, 8 Aug 2023 18:54:40 +0800 Subject: [PATCH 02/13] update sp module --- app/export_test.go | 5 +- deployment/localup/localup.sh | 2 + e2e/core/basesuite.go | 2 +- e2e/tests/payment_test.go | 3 +- e2e/tests/storage_bill_test.go | 375 ++++++++++++++++++++++-- e2e/tests/storage_test.go | 3 +- proto/greenfield/sp/params.proto | 4 + swagger/static/swagger.yaml | 256 +++++++++------- x/bridge/client/cli/tx_test.go | 4 +- x/challenge/client/cli/query_test.go | 2 +- x/payment/client/cli/query_test.go | 2 +- x/permission/client/cli/query_test.go | 2 +- x/sp/abci.go | 14 +- x/sp/client/cli/query_test.go | 2 +- x/sp/keeper/msg_server.go | 17 +- x/sp/keeper/sp_status.go | 3 +- x/sp/keeper/sp_storage_price.go | 33 +++ x/sp/types/errors.go | 1 + x/sp/types/keys.go | 25 +- x/sp/types/params.go | 46 ++- x/sp/types/params.pb.go | 146 +++++++-- x/storage/client/cli/query_test.go | 2 +- x/storage/keeper/keeper_test.go | 4 +- x/storage/keeper/payment.go | 3 +- x/virtualgroup/client/cli/query_test.go | 2 +- 25 files changed, 740 insertions(+), 218 deletions(-) diff --git a/app/export_test.go b/app/export_test.go index a9c3cd26a..6982c7fab 100644 --- a/app/export_test.go +++ b/app/export_test.go @@ -3,11 +3,12 @@ package app_test import ( "testing" - "github.com/bnb-chain/greenfield/sdk/client/test" - "github.com/bnb-chain/greenfield/testutil" dbm "github.com/cometbft/cometbft-db" "github.com/cometbft/cometbft/libs/log" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + + "github.com/bnb-chain/greenfield/sdk/client/test" + "github.com/bnb-chain/greenfield/testutil" ) func TestExportAppStateAndValidators(t *testing.T) { diff --git a/deployment/localup/localup.sh b/deployment/localup/localup.sh index bda54bdcf..88606177c 100644 --- a/deployment/localup/localup.sh +++ b/deployment/localup/localup.sh @@ -153,6 +153,8 @@ function generate_genesis() { sed -i -e "s/\"discontinue_confirm_period\": \"604800\"/\"discontinue_confirm_period\": \"5\"/g" ${workspace}/.local/validator${i}/config/genesis.json sed -i -e "s/\"discontinue_deletion_max\": \"100\"/\"discontinue_deletion_max\": \"2\"/g" ${workspace}/.local/validator${i}/config/genesis.json sed -i -e "s/\"voting_period\": \"30s\"/\"voting_period\": \"5s\"/g" ${workspace}/.local/validator${i}/config/genesis.json + sed -i -e "s/\"update_global_price_interval\": \"2592000\"/\"update_global_price_interval\": \"1\"/g" ${workspace}/.local/validator${i}/config/genesis.json + sed -i -e "s/\"max_update_price_times\": 3/\"max_update_price_times\": 1000000/g" ${workspace}/.local/validator${i}/config/genesis.json #sed -i -e "s/\"community_tax\": \"0.020000000000000000\"/\"community_tax\": \"0\"/g" ${workspace}/.local/validator${i}/config/genesis.json sed -i -e "s/log_level = \"info\"/\log_level= \"debug\"/g" ${workspace}/.local/validator${i}/config/config.toml done diff --git a/e2e/core/basesuite.go b/e2e/core/basesuite.go index 416c6cce8..107f6f677 100644 --- a/e2e/core/basesuite.go +++ b/e2e/core/basesuite.go @@ -127,7 +127,7 @@ func (s *BaseSuite) InitChain() { func (s *BaseSuite) SetupSuite() { s.Config = InitConfig() initValidatorOnce.Do(func() { - s.InitChain() + //s.InitChain() }) s.Client, _ = client.NewGreenfieldClient(s.Config.TendermintAddr, s.Config.ChainId) diff --git a/e2e/tests/payment_test.go b/e2e/tests/payment_test.go index 16b5774eb..a60c7727d 100644 --- a/e2e/tests/payment_test.go +++ b/e2e/tests/payment_test.go @@ -10,10 +10,9 @@ import ( "testing" "time" - "github.com/cosmos/cosmos-sdk/types/query" - sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/query" "github.com/cosmos/cosmos-sdk/types/tx" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" diff --git a/e2e/tests/storage_bill_test.go b/e2e/tests/storage_bill_test.go index 6d5d5fabc..ab8c9febb 100644 --- a/e2e/tests/storage_bill_test.go +++ b/e2e/tests/storage_bill_test.go @@ -1593,13 +1593,13 @@ func (s *PaymentTestSuite) TestStorageBill_UpdateBucketQuota() { s.Require().NoError(err) // check price and rate calculation - priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + priceRes, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: bucketInfo.CreateAt, }) s.T().Logf("priceRes %s, err: %v", priceRes, err) s.Require().NoError(err) - readPrice := priceRes.SpStoragePrice.ReadPrice + readPrice := priceRes.GlobalSpStorePrice.ReadPrice readChargeRate := readPrice.MulInt(sdk.NewIntFromUint64(bucketInfo.ChargedReadQuota)).TruncateInt() s.T().Logf("readPrice: %s, readChargeRate: %s", readPrice, readChargeRate) taxRate := paymentParams.Params.VersionedParams.ValidatorTaxRate.MulInt(readChargeRate).TruncateInt() @@ -1626,11 +1626,14 @@ func (s *PaymentTestSuite) TestStorageBill_UpdateBucketQuota() { }) s.Require().Equal(expectedOutFlows, userOutFlowsResponse.OutFlows) // update new price + spPriceRes, _ := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorKey.GetAddr().String(), + }) msgUpdatePrice := &sptypes.MsgUpdateSpStoragePrice{ SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice.MulInt64(100), - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice, + ReadPrice: spPriceRes.SpStoragePrice.ReadPrice.MulInt64(100), + FreeReadQuota: spPriceRes.SpStoragePrice.FreeReadQuota, + StorePrice: spPriceRes.SpStoragePrice.StorePrice, } s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) @@ -1639,13 +1642,13 @@ func (s *PaymentTestSuite) TestStorageBill_UpdateBucketQuota() { s.Require().NoError(err) // check price and rate calculation - priceRes, err = s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + priceRes, err = s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: bucketInfo.CreateAt, }) s.T().Logf("priceRes %s, err: %v", priceRes, err) s.Require().NoError(err) - readPrice = priceRes.SpStoragePrice.ReadPrice + readPrice = priceRes.GlobalSpStorePrice.ReadPrice readChargeRate = readPrice.MulInt(sdk.NewIntFromUint64(bucketInfo.ChargedReadQuota)).TruncateInt() s.T().Logf("readPrice: %s, readChargeRate: %s", readPrice, readChargeRate) taxRate = paymentParams.Params.VersionedParams.ValidatorTaxRate.MulInt(readChargeRate).TruncateInt() @@ -1674,9 +1677,9 @@ func (s *PaymentTestSuite) TestStorageBill_UpdateBucketQuota() { // set big read price msgUpdatePrice = &sptypes.MsgUpdateSpStoragePrice{ SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice.MulInt64(1024 * 1024 * 1024), - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice, + ReadPrice: spPriceRes.SpStoragePrice.ReadPrice.MulInt64(1024 * 1024 * 1024), + FreeReadQuota: spPriceRes.SpStoragePrice.FreeReadQuota, + StorePrice: spPriceRes.SpStoragePrice.StorePrice, } s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) @@ -1685,7 +1688,6 @@ func (s *PaymentTestSuite) TestStorageBill_UpdateBucketQuota() { user.GetAddr(), bucketName, &chargedReadQuota, user.GetAddr(), storagetypes.VISIBILITY_TYPE_PRIVATE) s.reduceBNBBalance(user, s.Validator, sdkmath.NewIntWithDecimal(1, 16)) s.SendTxBlockWithExpectErrorString(msgUpdateBucketInfo, user, "apply user flows list failed") - } // TestStorageBill_UpdatePaymentAddress @@ -1740,13 +1742,13 @@ func (s *PaymentTestSuite) TestStorageBill_UpdatePaymentAddress() { s.Require().NoError(err) // check price and rate calculation - priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + priceRes, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: bucketInfo.CreateAt, }) s.T().Logf("priceRes %s, err: %v", priceRes, err) s.Require().NoError(err) - readPrice := priceRes.SpStoragePrice.ReadPrice + readPrice := priceRes.GlobalSpStorePrice.ReadPrice readChargeRate := readPrice.MulInt(sdk.NewIntFromUint64(bucketInfo.ChargedReadQuota)).TruncateInt() s.T().Logf("readPrice: %s, readChargeRate: %s", readPrice, readChargeRate) taxRate := paymentParams.Params.VersionedParams.ValidatorTaxRate.MulInt(readChargeRate).TruncateInt() @@ -1756,7 +1758,7 @@ func (s *PaymentTestSuite) TestStorageBill_UpdatePaymentAddress() { streamRecordsAfter = s.getStreamRecords(streamAddresses) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) s.Require().Equal(streamRecordsAfter.User.NetflowRate.Sub(streamRecordsBefore.User.NetflowRate), userTotalRate.Neg()) - s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate), readChargeRate) + s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), readChargeRate.Int64()) s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate), taxRate) expectedOutFlows := []paymenttypes.OutFlow{ @@ -1773,11 +1775,14 @@ func (s *PaymentTestSuite) TestStorageBill_UpdatePaymentAddress() { }) s.Require().Equal(expectedOutFlows, userOutFlowsResponse.OutFlows) // update new price + spPriceRes, _ := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorKey.GetAddr().String(), + }) msgUpdatePrice := &sptypes.MsgUpdateSpStoragePrice{ SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice.MulInt64(100), - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice, + ReadPrice: spPriceRes.SpStoragePrice.ReadPrice.MulInt64(100), + FreeReadQuota: spPriceRes.SpStoragePrice.FreeReadQuota, + StorePrice: spPriceRes.SpStoragePrice.StorePrice, } s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) @@ -1786,13 +1791,13 @@ func (s *PaymentTestSuite) TestStorageBill_UpdatePaymentAddress() { s.Require().NoError(err) // check price and rate calculation - priceRes, err = s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + priceRes, err = s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: bucketInfo.CreateAt, }) s.T().Logf("priceRes %s, err: %v", priceRes, err) s.Require().NoError(err) - readPrice = priceRes.SpStoragePrice.ReadPrice + readPrice = priceRes.GlobalSpStorePrice.ReadPrice readChargeRate = readPrice.MulInt(sdk.NewIntFromUint64(bucketInfo.ChargedReadQuota)).TruncateInt() s.T().Logf("readPrice: %s, readChargeRate: %s", readPrice, readChargeRate) taxRate = paymentParams.Params.VersionedParams.ValidatorTaxRate.MulInt(readChargeRate).TruncateInt() @@ -1823,9 +1828,9 @@ func (s *PaymentTestSuite) TestStorageBill_UpdatePaymentAddress() { // set big read price msgUpdatePrice = &sptypes.MsgUpdateSpStoragePrice{ SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice.MulInt64(1024 * 1024 * 1024), - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice, + ReadPrice: spPriceRes.SpStoragePrice.ReadPrice.MulInt64(1024 * 1024 * 1024), + FreeReadQuota: spPriceRes.SpStoragePrice.FreeReadQuota, + StorePrice: spPriceRes.SpStoragePrice.StorePrice, } s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) @@ -1842,7 +1847,7 @@ func (s *PaymentTestSuite) TestStorageBill_UpdatePaymentAddress() { s.SendTxBlockWithExpectErrorString(msgUpdateBucketInfo, user, "apply user flows list failed") } -func (s *PaymentTestSuite) TestStorageBill_MigrationBucket() { +func (s *PaymentTestSuite) TestStorageBill_MigrateBucket() { var err error ctx := context.Background() primarySP := s.PickStorageProvider() @@ -1998,6 +2003,314 @@ func (s *PaymentTestSuite) TestStorageBill_MigrationBucket() { s.Require().Equal(streamRecordsAfter.User.NetflowRate.Neg(), userTotalRate.Abs()) } +func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_ThenDiscontinueBucket() { + var err error + ctx := context.Background() + primarySP := s.PickStorageProvider() + s.SetSPPrice(primarySP, "1", "1.15") + + gvg, found := primarySP.GetFirstGlobalVirtualGroup() + s.Require().True(found) + queryFamilyResponse, err := s.Client.GlobalVirtualGroupFamily(ctx, &virtualgrouptypes.QueryGlobalVirtualGroupFamilyRequest{ + FamilyId: gvg.FamilyId, + }) + s.Require().NoError(err) + family := queryFamilyResponse.GlobalVirtualGroupFamily + user := s.GenAndChargeAccounts(1, 10)[0] + + streamAddresses := []string{ + user.GetAddr().String(), + family.VirtualPaymentAddress, + gvg.VirtualPaymentAddress, + paymenttypes.ValidatorTaxPoolAddress.String(), + } + + paymentParams, err := s.Client.PaymentQueryClient.Params(ctx, &paymenttypes.QueryParamsRequest{}) + s.T().Logf("paymentParams %s, err: %v", paymentParams, err) + s.Require().NoError(err) + + bucketName := s.createBucket(primarySP, user, 0) + bucketInfo, err := s.Client.HeadBucket(context.Background(), &storagetypes.QueryHeadBucketRequest{ + BucketName: bucketName, + }) + s.Require().NoError(err) + + // create object with none zero payload size + streamRecordsBefore := s.getStreamRecords(streamAddresses) + _, _, objectName, objectId, checksums, payloadSize := s.createObject(user, bucketName, false) + + // assertions + streamRecordsAfter := s.getStreamRecords(streamAddresses) + s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) + lockFee := s.calculateLockFee(primarySP, bucketName, objectName, payloadSize) + s.Require().Equal(streamRecordsAfter.User.LockBalance.Sub(streamRecordsBefore.User.LockBalance), lockFee) + s.Require().Equal(streamRecordsAfter.User.NetflowRate.Sub(streamRecordsBefore.User.NetflowRate).Int64(), int64(0)) + s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), int64(0)) + s.Require().Equal(streamRecordsAfter.GVG.NetflowRate.Sub(streamRecordsBefore.GVG.NetflowRate).Int64(), int64(0)) + s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate).Int64(), int64(0)) + + // case: seal object + s.sealObject(primarySP, gvg, bucketName, objectName, objectId, checksums) + + // assertions + streamRecordsAfter = s.getStreamRecords(streamAddresses) + gvgFamilyRate, gvgRate, taxRate, userTotalRate := s.calculateStorageRates(primarySP, bucketName, objectName, payloadSize, 0) + s.T().Logf("gvgFamilyRate: %v, gvgRate: %v, taxRate: %v, userTotalRate: %v", gvgFamilyRate, gvgRate, taxRate, userTotalRate) + s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) + s.Require().Equal(streamRecordsAfter.User.LockBalance, sdkmath.ZeroInt()) + s.Require().Equal(streamRecordsAfter.User.NetflowRate.Sub(streamRecordsBefore.User.NetflowRate), userTotalRate.Neg()) + s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate), gvgFamilyRate) + s.Require().Equal(streamRecordsAfter.GVG.NetflowRate.Sub(streamRecordsBefore.GVG.NetflowRate), gvgRate) + s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate), taxRate) + taxRate0 := taxRate + dstPrimarySP := s.CreateNewStorageProvider() + + // create a new object without seal + s.createObject(user, bucketName, false) + + s.SetSPPrice(dstPrimarySP, "2", "1.45") + _, secondarySPIDs := s.GetSecondarySP(dstPrimarySP, primarySP) + gvgID, _ := s.BaseSuite.CreateGlobalVirtualGroup(dstPrimarySP, 0, secondarySPIDs, 1) + gvgResp, err := s.Client.VirtualGroupQueryClient.GlobalVirtualGroup(context.Background(), &virtualgrouptypes.QueryGlobalVirtualGroupRequest{ + GlobalVirtualGroupId: gvgID, + }) + s.Require().NoError(err) + dstGVG := gvgResp.GlobalVirtualGroup + s.Require().True(found) + + queryFamilyResponse, err = s.Client.GlobalVirtualGroupFamily(ctx, &virtualgrouptypes.QueryGlobalVirtualGroupFamilyRequest{ + FamilyId: dstGVG.FamilyId, + }) + s.Require().NoError(err) + family = queryFamilyResponse.GlobalVirtualGroupFamily + streamAddresses = []string{ + user.GetAddr().String(), + family.VirtualPaymentAddress, + dstGVG.VirtualPaymentAddress, + paymenttypes.ValidatorTaxPoolAddress.String(), + } + fundAddress := primarySP.FundingKey.GetAddr() + streamRecordsBefore = s.getStreamRecords(streamAddresses) + + queryBalanceRequest := banktypes.QueryBalanceRequest{Denom: s.Config.Denom, Address: fundAddress.String()} + fundBalanceBefore, err := s.Client.BankQueryClient.Balance(context.Background(), &queryBalanceRequest) + s.Require().NoError(err) + + // MigrateBucket + msgMigrateBucket, msgCompleteMigrateBucket := s.NewMigrateBucket(primarySP, dstPrimarySP, user, bucketName, gvg.FamilyId, dstGVG.FamilyId, bucketInfo.BucketInfo.Id) + s.SendTxBlock(user, msgMigrateBucket) + s.Require().NoError(err) + + // complete MigrateBucket + s.SendTxBlock(dstPrimarySP.OperatorKey, msgCompleteMigrateBucket) + streamRecordsAfter = s.getStreamRecords(streamAddresses) + fundBalanceAfter, err := s.Client.BankQueryClient.Balance(context.Background(), &queryBalanceRequest) + s.Require().NoError(err) + s.T().Logf("fundBalanceBefore: %v, fundBalanceAfter: %v, diff: %v", fundBalanceBefore, fundBalanceAfter, fundBalanceAfter.Balance.Amount.Sub(fundBalanceBefore.Balance.Amount)) + s.Require().True(fundBalanceAfter.Balance.Amount.Sub(fundBalanceBefore.Balance.Amount).GT(sdkmath.NewInt(0)), "migrate sp fund address need settle") + gvgFamilyRate, gvgRate, taxRate, userTotalRate = s.calculateStorageRates(dstPrimarySP, bucketName, objectName, payloadSize, time.Now().Unix()) + s.T().Logf("gvgFamilyRate: %v, gvgRate: %v, taxRate: %v, userTotalRate: %v", gvgFamilyRate, gvgRate, taxRate, userTotalRate) + s.T().Logf("NetflowRate: %v, userTotalRate: %v, actual taxRate diff: %v, expect taxRate diff: %v", streamRecordsAfter.User.NetflowRate.Neg(), userTotalRate.Neg(), streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate), taxRate.Sub(taxRate0)) + + s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) + s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate), gvgFamilyRate) + s.Require().Equal(streamRecordsAfter.GVG.NetflowRate.Sub(streamRecordsBefore.GVG.NetflowRate), gvgRate) + // tax rate diff + s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate), taxRate.Sub(taxRate0)) + s.Require().Equal(streamRecordsAfter.User.NetflowRate.Neg(), userTotalRate.Abs()) + + // force delete bucket + headBucketResp, _ := s.Client.HeadBucket(ctx, &storagetypes.QueryHeadBucketRequest{BucketName: bucketName}) + s.T().Log("headBucketResp", core.YamlString(headBucketResp)) + msgDiscontinueBucket := storagetypes.NewMsgDiscontinueBucket(dstPrimarySP.GcKey.GetAddr(), bucketName, "test") + txRes := s.SendTxBlock(dstPrimarySP.GcKey, msgDiscontinueBucket) + deleteAt := filterDiscontinueBucketEventFromTx(txRes).DeleteAt + + for { + time.Sleep(200 * time.Millisecond) + statusRes, err := s.TmClient.TmClient.Status(context.Background()) + s.Require().NoError(err) + blockTime := statusRes.SyncInfo.LatestBlockTime.Unix() + + s.T().Logf("current blockTime: %d, delete blockTime: %d", blockTime, deleteAt) + + if blockTime > deleteAt { + break + } + } + + _, err = s.Client.HeadBucket(ctx, &storagetypes.QueryHeadBucketRequest{BucketName: bucketName}) + s.Require().ErrorContains(err, "No such bucket") +} + +func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_FrozenAccount_ThenDiscontinueBucket() { + var err error + ctx := context.Background() + primarySP := s.PickStorageProvider() + s.SetSPPrice(primarySP, "1", "1.15") + + gvg, found := primarySP.GetFirstGlobalVirtualGroup() + s.Require().True(found) + queryFamilyResponse, err := s.Client.GlobalVirtualGroupFamily(ctx, &virtualgrouptypes.QueryGlobalVirtualGroupFamilyRequest{ + FamilyId: gvg.FamilyId, + }) + s.Require().NoError(err) + s.T().Log("queryFamilyResponse", core.YamlString(queryFamilyResponse)) + user := s.GenAndChargeAccounts(1, 10)[0] + + bucketChargedReadQuota := uint64(1000) + params := s.queryParams() + reserveTime := params.VersionedParams.ReserveTime + queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, + }) + s.T().Logf("queryGetSpStoragePriceByTimeResp %s, err: %v", queryGetSpStoragePriceByTimeResp, err) + s.Require().NoError(err) + + readPrice := queryGetSpStoragePriceByTimeResp.GlobalSpStorePrice.ReadPrice + totalUserRate := readPrice.MulInt(sdkmath.NewIntFromUint64(bucketChargedReadQuota)).TruncateInt() + taxRateParam := params.VersionedParams.ValidatorTaxRate + taxStreamRate := taxRateParam.MulInt(totalUserRate).TruncateInt() + expectedRate := totalUserRate.Add(taxStreamRate) + paymentAccountBNBNeeded := expectedRate.Mul(sdkmath.NewIntFromUint64(reserveTime)) + + // create payment account and deposit + msgCreatePaymentAccount := &paymenttypes.MsgCreatePaymentAccount{ + Creator: user.GetAddr().String(), + } + _ = s.SendTxBlock(user, msgCreatePaymentAccount) + paymentAccountsReq := &paymenttypes.QueryPaymentAccountsByOwnerRequest{Owner: user.GetAddr().String()} + paymentAccounts, err := s.Client.PaymentQueryClient.PaymentAccountsByOwner(ctx, paymentAccountsReq) + s.Require().NoError(err) + s.T().Logf("paymentAccounts %s", core.YamlString(paymentAccounts)) + paymentAddr := paymentAccounts.PaymentAccounts[0] + s.Require().Lenf(paymentAccounts.PaymentAccounts, 1, "paymentAccounts %s", core.YamlString(paymentAccounts)) + msgDeposit := &paymenttypes.MsgDeposit{ + Creator: user.GetAddr().String(), + To: paymentAddr, + Amount: paymentAccountBNBNeeded, + } + _ = s.SendTxBlock(user, msgDeposit) + + paymentParams, err := s.Client.PaymentQueryClient.Params(ctx, &paymenttypes.QueryParamsRequest{}) + s.T().Logf("paymentParams %s, err: %v", paymentParams, err) + s.Require().NoError(err) + + bucketName := "ch" + storagetestutils.GenRandomBucketName() + msgCreateBucket := storagetypes.NewMsgCreateBucket( + user.GetAddr(), bucketName, storagetypes.VISIBILITY_TYPE_PRIVATE, primarySP.OperatorKey.GetAddr(), + sdk.MustAccAddressFromHex(paymentAddr), math.MaxUint, nil, bucketChargedReadQuota) + msgCreateBucket.PrimarySpApproval.GlobalVirtualGroupFamilyId = gvg.FamilyId + msgCreateBucket.PrimarySpApproval.Sig, err = primarySP.ApprovalKey.Sign(msgCreateBucket.GetApprovalBytes()) + s.Require().NoError(err) + s.SendTxBlock(user, msgCreateBucket) + + queryHeadBucketRequest := storagetypes.QueryHeadBucketRequest{ + BucketName: bucketName, + } + _, err = s.Client.HeadBucket(context.Background(), &queryHeadBucketRequest) + s.Require().NoError(err) + bucketInfo, err := s.Client.HeadBucket(context.Background(), &storagetypes.QueryHeadBucketRequest{ + BucketName: bucketName, + }) + s.Require().NoError(err) + + // wait until settle time + paymentAccountStreamRecord := s.getStreamRecord(paymentAddr) + retryCount := 0 + for { + latestBlock, err := s.TmClient.TmClient.Block(ctx, nil) + s.Require().NoError(err) + currentTimestamp := latestBlock.Block.Time.Unix() + s.T().Logf("currentTimestamp %d, userStreamRecord.SettleTimestamp %d", currentTimestamp, paymentAccountStreamRecord.SettleTimestamp) + if currentTimestamp > paymentAccountStreamRecord.SettleTimestamp { + break + } + time.Sleep(time.Second) + retryCount++ + if retryCount > 60 { + s.T().Fatalf("wait for settle time timeout") + } + } + // check auto settle + paymentAccountStreamRecordAfterAutoSettle := s.getStreamRecord(paymentAddr) + s.T().Logf("paymentAccountStreamRecordAfterAutoSettle %s", core.YamlString(paymentAccountStreamRecordAfterAutoSettle)) + s.Require().NotEqual(paymentAccountStreamRecordAfterAutoSettle.Status, paymenttypes.STREAM_ACCOUNT_STATUS_ACTIVE) + + dstPrimarySP := s.CreateNewStorageProvider() + s.SetSPPrice(dstPrimarySP, "2", "1.45") + _, secondarySPIDs := s.GetSecondarySP(dstPrimarySP, primarySP) + gvgID, _ := s.BaseSuite.CreateGlobalVirtualGroup(dstPrimarySP, 0, secondarySPIDs, 1) + gvgResp, err := s.Client.VirtualGroupQueryClient.GlobalVirtualGroup(context.Background(), &virtualgrouptypes.QueryGlobalVirtualGroupRequest{ + GlobalVirtualGroupId: gvgID, + }) + s.Require().NoError(err) + dstGVG := gvgResp.GlobalVirtualGroup + s.Require().True(found) + + queryFamilyResponse, err = s.Client.GlobalVirtualGroupFamily(ctx, &virtualgrouptypes.QueryGlobalVirtualGroupFamilyRequest{ + FamilyId: dstGVG.FamilyId, + }) + s.Require().NoError(err) + family := queryFamilyResponse.GlobalVirtualGroupFamily + streamAddresses := []string{ + paymentAddr, + family.VirtualPaymentAddress, + dstGVG.VirtualPaymentAddress, + paymenttypes.ValidatorTaxPoolAddress.String(), + } + fundAddress := primarySP.FundingKey.GetAddr() + streamRecordsBefore := s.getStreamRecords(streamAddresses) + + queryBalanceRequest := banktypes.QueryBalanceRequest{Denom: s.Config.Denom, Address: fundAddress.String()} + fundBalanceBefore, err := s.Client.BankQueryClient.Balance(context.Background(), &queryBalanceRequest) + s.Require().NoError(err) + + // MigrateBucket + msgMigrateBucket, msgCompleteMigrateBucket := s.NewMigrateBucket(primarySP, dstPrimarySP, user, bucketName, gvg.FamilyId, dstGVG.FamilyId, bucketInfo.BucketInfo.Id) + s.SendTxBlock(user, msgMigrateBucket) + s.Require().NoError(err) + + // complete MigrateBucket + s.SendTxBlock(dstPrimarySP.OperatorKey, msgCompleteMigrateBucket) + streamRecordsAfter := s.getStreamRecords(streamAddresses) + fundBalanceAfter, err := s.Client.BankQueryClient.Balance(context.Background(), &queryBalanceRequest) + s.Require().NoError(err) + s.T().Logf("fundBalanceBefore: %v, fundBalanceAfter: %v, diff: %v", fundBalanceBefore, fundBalanceAfter, fundBalanceAfter.Balance.Amount.Sub(fundBalanceBefore.Balance.Amount)) + s.Require().True(fundBalanceAfter.Balance.Amount.Sub(fundBalanceBefore.Balance.Amount).GT(sdkmath.NewInt(0)), "migrate sp fund address need settle") + gvgFamilyRate, taxRate, userTotalRate := s.calculateReadRates(dstPrimarySP, bucketName) + s.T().Logf("gvgFamilyRate: %v, taxRate: %v, userTotalRate: %v", gvgFamilyRate, taxRate, userTotalRate) + s.T().Logf("NetflowRate: %v, userTotalRate: %v, actual taxRate diff: %v, expect taxRate diff: %v", streamRecordsAfter.User.NetflowRate.Neg(), userTotalRate.Neg(), streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate), taxRate) + + s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) + s.Require().Equal(streamRecordsAfter.User.LockBalance, sdkmath.ZeroInt()) + s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate), gvgFamilyRate) + // tax rate diff + s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate), taxRate) + s.Require().Equal(streamRecordsAfter.User.FrozenNetflowRate.Neg(), userTotalRate.Abs()) + + // force delete bucket + msgDiscontinueBucket := storagetypes.NewMsgDiscontinueBucket(dstPrimarySP.GcKey.GetAddr(), bucketName, "test") + txRes := s.SendTxBlock(dstPrimarySP.GcKey, msgDiscontinueBucket) + deleteAt := filterDiscontinueBucketEventFromTx(txRes).DeleteAt + + for { + time.Sleep(200 * time.Millisecond) + statusRes, err := s.TmClient.TmClient.Status(context.Background()) + s.Require().NoError(err) + blockTime := statusRes.SyncInfo.LatestBlockTime.Unix() + + s.T().Logf("current blockTime: %d, delete blockTime: %d", blockTime, deleteAt) + + if blockTime > deleteAt { + break + } + } + + _, err = s.Client.HeadBucket(ctx, &storagetypes.QueryHeadBucketRequest{BucketName: bucketName}) + s.Require().ErrorContains(err, "No such bucket") +} + func (s *PaymentTestSuite) GetSecondarySP(sps ...*core.StorageProvider) ([]*core.StorageProvider, []uint32) { var secondarySPs []*core.StorageProvider var secondarySPIDs []uint32 @@ -2160,11 +2473,9 @@ func (s *PaymentTestSuite) reduceBNBBalance(user, to keys.KeyManager, leftBalanc s.T().Logf("balance: %v", queryBalanceResponse.Balance.Amount) } -func (s *PaymentTestSuite) transferBNB(user, to keys.KeyManager, amount sdkmath.Int) { - - msgSend := banktypes.NewMsgSend(user.GetAddr(), to.GetAddr(), sdk.NewCoins( +func (s *PaymentTestSuite) transferBNB(from, to keys.KeyManager, amount sdkmath.Int) { + msgSend := banktypes.NewMsgSend(from.GetAddr(), to.GetAddr(), sdk.NewCoins( sdk.NewCoin(s.Config.Denom, amount), )) - s.SendTxBlock(user, msgSend) - + s.SendTxBlock(from, msgSend) } diff --git a/e2e/tests/storage_test.go b/e2e/tests/storage_test.go index 48b94c0d0..f995d7ee7 100644 --- a/e2e/tests/storage_test.go +++ b/e2e/tests/storage_test.go @@ -11,8 +11,6 @@ import ( "testing" "time" - sptypes "github.com/bnb-chain/greenfield/x/sp/types" - sdkmath "cosmossdk.io/math" ctypes "github.com/cometbft/cometbft/rpc/core/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -29,6 +27,7 @@ import ( "github.com/bnb-chain/greenfield/sdk/keys" "github.com/bnb-chain/greenfield/sdk/types" storageutils "github.com/bnb-chain/greenfield/testutil/storage" + sptypes "github.com/bnb-chain/greenfield/x/sp/types" storagetypes "github.com/bnb-chain/greenfield/x/storage/types" types2 "github.com/bnb-chain/greenfield/x/virtualgroup/types" ) diff --git a/proto/greenfield/sp/params.proto b/proto/greenfield/sp/params.proto index 2d62ae111..491492011 100644 --- a/proto/greenfield/sp/params.proto +++ b/proto/greenfield/sp/params.proto @@ -31,4 +31,8 @@ message Params { int64 maintenance_duration_quota = 5 [(gogoproto.moretags) = "yaml:\"maintenance_duration_quota\""]; // the number of blocks to be wait for sp to be in maintenance mode again if already requested int64 num_of_lockup_blocks_for_maintenance = 6 [(gogoproto.moretags) = "yaml:\"num_of_lockup_blocks_for_maintenance\""]; + // the time interval to update global storage price + uint64 update_global_price_interval = 7 [(gogoproto.moretags) = "yaml:\"update_global_price_interval\""]; + // the max times allowed to update price during an interval + uint32 max_update_price_times = 8 [(gogoproto.moretags) = "yaml:\"max_update_price_times\""]; } diff --git a/swagger/static/swagger.yaml b/swagger/static/swagger.yaml index 548f757cd..41710c4e9 100644 --- a/swagger/static/swagger.yaml +++ b/swagger/static/swagger.yaml @@ -1551,79 +1551,19 @@ paths: type: boolean tags: - Query - /greenfield/sp/get_secondary_sp_store_price_by_time/{timestamp}: + /greenfield/sp/global_sp_store_price_by_time/{timestamp}: get: - summary: get secondary store price by time - operationId: QueryGetSecondarySpStorePriceByTime + summary: get global store price by time + operationId: QueryGlobalSpStorePriceByTime responses: '200': description: A successful response. schema: type: object properties: - secondary_sp_store_price: + global_sp_store_price: type: object properties: - update_time_sec: - type: string - format: int64 - title: update time, unix timestamp in seconds - store_price: - type: string - title: store price, in bnb wei per charge byte - title: >- - global secondary sp store price, the price for all secondary - sps - default: - description: An unexpected error response. - schema: - type: object - properties: - error: - type: string - code: - type: integer - format: int32 - message: - type: string - details: - type: array - items: - type: object - properties: - type_url: - type: string - value: - type: string - format: byte - parameters: - - name: timestamp - description: >- - unix timestamp in seconds. If it's 0, it will return the latest - price. - in: path - required: true - type: string - format: int64 - tags: - - Query - /greenfield/sp/get_sp_storage_price_by_time/{sp_addr}/{timestamp}: - get: - summary: get storage price of specific sp and time - operationId: QueryGetSpStoragePriceByTime - responses: - '200': - description: A successful response. - schema: - type: object - properties: - sp_storage_price: - type: object - properties: - sp_id: - type: integer - format: int64 - title: sp id update_time_sec: type: string format: int64 @@ -1631,14 +1571,13 @@ paths: read_price: type: string title: read price, in bnb wei per charge byte - free_read_quota: + primary_store_price: type: string - format: uint64 - title: free read quota, in byte - store_price: + title: primary store price, in bnb wei per charge byte + secondary_store_price: type: string - title: store price, in bnb wei per charge byte - title: storage price of a specific sp + title: secondary store price, in bnb wei per charge byte + title: global sp store price, the price for all sps default: description: An unexpected error response. schema: @@ -1662,11 +1601,6 @@ paths: type: string format: byte parameters: - - name: sp_addr - description: operator address of sp - in: path - required: true - type: string - name: timestamp description: >- unix timestamp in seconds. If it's 0, it will return the latest @@ -1722,6 +1656,14 @@ paths: title: >- the number of blocks to be wait for sp to be in maintenance mode again if already requested + update_global_price_interval: + type: string + format: uint64 + title: the time interval to update global storage price + max_update_price_times: + type: integer + format: int64 + title: the max times allowed to update price during an interval description: >- QueryParamsResponse is response type for the Query/Params RPC method. @@ -1749,6 +1691,68 @@ paths: format: byte tags: - Query + /greenfield/sp/sp_storage_price/{sp_addr}: + get: + summary: get the latest storage price of specific sp + operationId: QuerySpStoragePrice + responses: + '200': + description: A successful response. + schema: + type: object + properties: + sp_storage_price: + type: object + properties: + sp_id: + type: integer + format: int64 + title: sp id + update_time_sec: + type: string + format: int64 + title: update time, unix timestamp in seconds + read_price: + type: string + title: read price, in bnb wei per charge byte + free_read_quota: + type: string + format: uint64 + title: free read quota, in byte + store_price: + type: string + title: store price, in bnb wei per charge byte + title: storage price of a specific sp + default: + description: An unexpected error response. + schema: + type: object + properties: + error: + type: string + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + type_url: + type: string + value: + type: string + format: byte + parameters: + - name: sp_addr + description: operator address of sp + in: path + required: true + type: string + tags: + - Query /greenfield/sp/storage_provider_by_operator_address: get: summary: Queries a StorageProvider by specify operator address. @@ -32778,6 +32782,23 @@ definitions: type: string description: details define other optional details. description: Description defines a storage provider description. + greenfield.sp.GlobalSpStorePrice: + type: object + properties: + update_time_sec: + type: string + format: int64 + title: update time, unix timestamp in seconds + read_price: + type: string + title: read price, in bnb wei per charge byte + primary_store_price: + type: string + title: primary store price, in bnb wei per charge byte + secondary_store_price: + type: string + title: secondary store price, in bnb wei per charge byte + title: global sp store price, the price for all sps greenfield.sp.MaintenanceRecord: type: object properties: @@ -32830,31 +32851,21 @@ definitions: title: >- the number of blocks to be wait for sp to be in maintenance mode again if already requested + update_global_price_interval: + type: string + format: uint64 + title: the time interval to update global storage price + max_update_price_times: + type: integer + format: int64 + title: the max times allowed to update price during an interval description: Params defines the parameters for the module. - greenfield.sp.QueryGetSecondarySpStorePriceByTimeResponse: + greenfield.sp.QueryGlobalSpStorePriceByTimeResponse: type: object properties: - secondary_sp_store_price: + global_sp_store_price: type: object properties: - update_time_sec: - type: string - format: int64 - title: update time, unix timestamp in seconds - store_price: - type: string - title: store price, in bnb wei per charge byte - title: global secondary sp store price, the price for all secondary sps - greenfield.sp.QueryGetSpStoragePriceByTimeResponse: - type: object - properties: - sp_storage_price: - type: object - properties: - sp_id: - type: integer - format: int64 - title: sp id update_time_sec: type: string format: int64 @@ -32862,14 +32873,13 @@ definitions: read_price: type: string title: read price, in bnb wei per charge byte - free_read_quota: + primary_store_price: type: string - format: uint64 - title: free read quota, in byte - store_price: + title: primary store price, in bnb wei per charge byte + secondary_store_price: type: string - title: store price, in bnb wei per charge byte - title: storage price of a specific sp + title: secondary store price, in bnb wei per charge byte + title: global sp store price, the price for all sps greenfield.sp.QueryParamsResponse: type: object properties: @@ -32906,7 +32916,40 @@ definitions: title: >- the number of blocks to be wait for sp to be in maintenance mode again if already requested + update_global_price_interval: + type: string + format: uint64 + title: the time interval to update global storage price + max_update_price_times: + type: integer + format: int64 + title: the max times allowed to update price during an interval description: QueryParamsResponse is response type for the Query/Params RPC method. + greenfield.sp.QuerySpStoragePriceResponse: + type: object + properties: + sp_storage_price: + type: object + properties: + sp_id: + type: integer + format: int64 + title: sp id + update_time_sec: + type: string + format: int64 + title: update time, unix timestamp in seconds + read_price: + type: string + title: read price, in bnb wei per charge byte + free_read_quota: + type: string + format: uint64 + title: free read quota, in byte + store_price: + type: string + title: store price, in bnb wei per charge byte + title: storage price of a specific sp greenfield.sp.QueryStorageProviderByOperatorAddressResponse: type: object properties: @@ -33235,17 +33278,6 @@ definitions: PageRequest.count_total was set, its value is undefined otherwise - greenfield.sp.SecondarySpStorePrice: - type: object - properties: - update_time_sec: - type: string - format: int64 - title: update time, unix timestamp in seconds - store_price: - type: string - title: store price, in bnb wei per charge byte - title: global secondary sp store price, the price for all secondary sps greenfield.sp.SpStoragePrice: type: object properties: diff --git a/x/bridge/client/cli/tx_test.go b/x/bridge/client/cli/tx_test.go index 3f04f8dfb..09124a371 100644 --- a/x/bridge/client/cli/tx_test.go +++ b/x/bridge/client/cli/tx_test.go @@ -9,7 +9,9 @@ import ( abci "github.com/cometbft/cometbft/abci/types" rpcclientmock "github.com/cometbft/cometbft/rpc/client/mock" "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/cosmos/cosmos-sdk/testutil" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/suite" @@ -19,8 +21,6 @@ import ( "github.com/bnb-chain/greenfield/sdk/client/test" "github.com/bnb-chain/greenfield/testutil/sample" "github.com/bnb-chain/greenfield/x/bridge/client/cli" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/testutil" ) type CLITestSuite struct { diff --git a/x/challenge/client/cli/query_test.go b/x/challenge/client/cli/query_test.go index cfb109862..1ac6147f3 100644 --- a/x/challenge/client/cli/query_test.go +++ b/x/challenge/client/cli/query_test.go @@ -3,12 +3,12 @@ package cli_test import ( "fmt" + "github.com/cosmos/cosmos-sdk/client/flags" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/gogoproto/proto" "github.com/bnb-chain/greenfield/x/challenge/client/cli" "github.com/bnb-chain/greenfield/x/challenge/types" - "github.com/cosmos/cosmos-sdk/client/flags" ) func (s *CLITestSuite) TestQueryCmd() { diff --git a/x/payment/client/cli/query_test.go b/x/payment/client/cli/query_test.go index 7d791d968..a02d24818 100644 --- a/x/payment/client/cli/query_test.go +++ b/x/payment/client/cli/query_test.go @@ -3,13 +3,13 @@ package cli_test import ( "fmt" + "github.com/cosmos/cosmos-sdk/client/flags" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/gogoproto/proto" "github.com/bnb-chain/greenfield/testutil/sample" "github.com/bnb-chain/greenfield/x/payment/client/cli" "github.com/bnb-chain/greenfield/x/payment/types" - "github.com/cosmos/cosmos-sdk/client/flags" ) func (s *CLITestSuite) TestQueryCmd() { diff --git a/x/permission/client/cli/query_test.go b/x/permission/client/cli/query_test.go index 44d63f5c6..5ffb5532b 100644 --- a/x/permission/client/cli/query_test.go +++ b/x/permission/client/cli/query_test.go @@ -3,12 +3,12 @@ package cli_test import ( "fmt" + "github.com/cosmos/cosmos-sdk/client/flags" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/gogoproto/proto" "github.com/bnb-chain/greenfield/x/payment/client/cli" "github.com/bnb-chain/greenfield/x/payment/types" - "github.com/cosmos/cosmos-sdk/client/flags" ) func (s *CLITestSuite) TestQueryCmd() { diff --git a/x/sp/abci.go b/x/sp/abci.go index 0dbf50802..a7cda816d 100644 --- a/x/sp/abci.go +++ b/x/sp/abci.go @@ -1,13 +1,25 @@ package sp import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/bnb-chain/greenfield/x/sp/keeper" "github.com/bnb-chain/greenfield/x/sp/types" - sdk "github.com/cosmos/cosmos-sdk/types" ) func EndBlocker(ctx sdk.Context, k keeper.Keeper) { if ctx.BlockHeight()%types.MaintenanceRecordsGCFrequencyInBlocks == 0 { k.ForceUpdateMaintenanceRecords(ctx) } + + blockTime := ctx.BlockTime().Unix() + params := k.GetParams(ctx) + price, err := k.GetGlobalSpStorePriceByTime(ctx, blockTime+1) + if err != nil || blockTime-price.UpdateTimeSec > int64(params.UpdateGlobalPriceInterval) { // no global price yet or need to update + err = k.UpdateGlobalSpStorePrice(ctx) + if err != nil { + ctx.Logger().Error("fail to update global sp store price", "err", err) + } + k.ClearSpUpdatePriceTimes(ctx) + } } diff --git a/x/sp/client/cli/query_test.go b/x/sp/client/cli/query_test.go index f7dbf1a80..7c59b700b 100644 --- a/x/sp/client/cli/query_test.go +++ b/x/sp/client/cli/query_test.go @@ -3,13 +3,13 @@ package cli_test import ( "fmt" + "github.com/cosmos/cosmos-sdk/client/flags" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/gogoproto/proto" "github.com/bnb-chain/greenfield/testutil/sample" "github.com/bnb-chain/greenfield/x/sp/client/cli" "github.com/bnb-chain/greenfield/x/sp/types" - "github.com/cosmos/cosmos-sdk/client/flags" ) func (s *CLITestSuite) TestQueryCmd() { diff --git a/x/sp/keeper/msg_server.go b/x/sp/keeper/msg_server.go index ce6096ee1..edf9e3a67 100644 --- a/x/sp/keeper/msg_server.go +++ b/x/sp/keeper/msg_server.go @@ -152,10 +152,7 @@ func (k msgServer) CreateStorageProvider(goCtx context.Context, msg *types.MsgCr FreeReadQuota: msg.FreeReadQuota, } k.SetSpStoragePrice(ctx, spStoragePrice) - err = k.UpdateGlobalSpStorePrice(ctx) - if err != nil { - return nil, err - } + k.SetSpUpdatePriceTimes(ctx, sp.Id, k.GetSpUpdatePriceTimes(ctx, sp.Id)+1) if err = ctx.EventManager().EmitTypedEvents(&types.EventCreateStorageProvider{ SpId: sp.Id, @@ -318,6 +315,12 @@ func (k msgServer) UpdateSpStoragePrice(goCtx context.Context, msg *types.MsgUpd return nil, types.ErrStorageProviderNotInService } + updateTimes := k.GetSpUpdatePriceTimes(ctx, sp.Id) + params := k.GetParams(ctx) + if updateTimes+1 >= params.MaxUpdatePriceTimes { + return nil, types.ErrStorageProviderPriceUpdateNotAllow + } + current := ctx.BlockTime().Unix() spStorePrice := types.SpStoragePrice{ UpdateTimeSec: current, @@ -327,10 +330,8 @@ func (k msgServer) UpdateSpStoragePrice(goCtx context.Context, msg *types.MsgUpd FreeReadQuota: msg.FreeReadQuota, } k.SetSpStoragePrice(ctx, spStorePrice) - err := k.UpdateGlobalSpStorePrice(ctx) - if err != nil { - return nil, errors.Wrapf(err, "update secondary sp store price failed") - } + k.SetSpUpdatePriceTimes(ctx, sp.Id, updateTimes+1) + return &types.MsgUpdateSpStoragePriceResponse{}, nil } diff --git a/x/sp/keeper/sp_status.go b/x/sp/keeper/sp_status.go index acdf83560..0a7359a6a 100644 --- a/x/sp/keeper/sp_status.go +++ b/x/sp/keeper/sp_status.go @@ -2,9 +2,10 @@ package keeper import ( "cosmossdk.io/errors" - "github.com/bnb-chain/greenfield/x/sp/types" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/bnb-chain/greenfield/x/sp/types" ) func (k Keeper) UpdateToInMaintenance(ctx sdk.Context, sp *types.StorageProvider, requestDuration int64) error { diff --git a/x/sp/keeper/sp_storage_price.go b/x/sp/keeper/sp_storage_price.go index c9f0ac3f9..b51473868 100644 --- a/x/sp/keeper/sp_storage_price.go +++ b/x/sp/keeper/sp_storage_price.go @@ -1,6 +1,7 @@ package keeper import ( + "encoding/binary" "fmt" "sort" @@ -145,3 +146,35 @@ func (k Keeper) GetGlobalSpStorePriceByTime(ctx sdk.Context, time int64) (val ty val.UpdateTimeSec = updateTimeSec return val, nil } + +func (k Keeper) SetSpUpdatePriceTimes(ctx sdk.Context, spId uint32, times uint32) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.SpStoragePriceUpdateTimesKeyPrefix) + idBz := make([]byte, 4) + binary.BigEndian.PutUint32(idBz, spId) + timesBz := make([]byte, 4) + binary.BigEndian.PutUint32(timesBz, times) + store.Set(idBz, timesBz) +} + +func (k Keeper) GetSpUpdatePriceTimes(ctx sdk.Context, spId uint32) uint32 { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.SpStoragePriceUpdateTimesKeyPrefix) + idBz := make([]byte, 4) + binary.BigEndian.PutUint32(idBz, spId) + timesBz := store.Get(idBz) + if timesBz == nil { + return 0 + } + times := binary.BigEndian.Uint32(timesBz) + return times +} + +func (k Keeper) ClearSpUpdatePriceTimes(ctx sdk.Context) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.SpStoragePriceUpdateTimesKeyPrefix) + + iterator := storetypes.KVStorePrefixIterator(store, []byte{}) + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + store.Delete(iterator.Key()) + } +} diff --git a/x/sp/types/errors.go b/x/sp/types/errors.go index 1824ca068..ed55ff5c4 100644 --- a/x/sp/types/errors.go +++ b/x/sp/types/errors.go @@ -23,6 +23,7 @@ var ( ErrStorageProviderBlsKeyExists = errors.Register(ModuleName, 15, "StorageProvider already exist for this bls pubkey; must use new bls pubkey") ErrStorageProviderStatusUpdateNotAllow = errors.Register(ModuleName, 16, "StorageProvider status is not allow to change") ErrStorageProviderMaintenanceAddrExists = errors.Register(ModuleName, 17, "StorageProvider already exist for this maintenance address; must use new StorageProvider maintenance address.") + ErrStorageProviderPriceUpdateNotAllow = errors.Register(ModuleName, 18, "StorageProvider cannot update price due to frequency limited.") ErrSignerNotGovModule = errors.Register(ModuleName, 40, "signer is not gov module account") ErrSignerEmpty = errors.Register(ModuleName, 41, "signer is empty") diff --git a/x/sp/types/keys.go b/x/sp/types/keys.go index e9ca69c2e..d0d3d464e 100644 --- a/x/sp/types/keys.go +++ b/x/sp/types/keys.go @@ -24,16 +24,17 @@ const ( var ( ParamsKey = []byte{0x01} - StorageProviderKey = []byte{0x21} // prefix for each key to a storage provider - StorageProviderByOperatorAddrKey = []byte{0x23} // prefix for each key to a storage provider index, by operator address - StorageProviderByFundingAddrKey = []byte{0x24} // prefix for each key to a storage provider index, by funding address - StorageProviderBySealAddrKey = []byte{0x25} // prefix for each key to a storage provider index, by seal address - StorageProviderByApprovalAddrKey = []byte{0x26} // prefix for each key to a storage provider index, by approval address - StorageProviderByGcAddrKey = []byte{0x27} // prefix for each key to a storage provider index, by gc address - SpStoragePriceKeyPrefix = []byte{0x28} - GlobalSpStorePriceKeyPrefix = []byte{0x29} - StorageProviderByBlsPubKeyKey = []byte{0x30} // prefix for each key to a storage provider index, by bls pub key - StorageProviderSequenceKey = []byte{0x31} + StorageProviderKey = []byte{0x21} // prefix for each key to a storage provider + StorageProviderByOperatorAddrKey = []byte{0x23} // prefix for each key to a storage provider index, by operator address + StorageProviderByFundingAddrKey = []byte{0x24} // prefix for each key to a storage provider index, by funding address + StorageProviderBySealAddrKey = []byte{0x25} // prefix for each key to a storage provider index, by seal address + StorageProviderByApprovalAddrKey = []byte{0x26} // prefix for each key to a storage provider index, by approval address + StorageProviderByGcAddrKey = []byte{0x27} // prefix for each key to a storage provider index, by gc address + SpStoragePriceKeyPrefix = []byte{0x28} + GlobalSpStorePriceKeyPrefix = []byte{0x29} + StorageProviderByBlsPubKeyKey = []byte{0x30} // prefix for each key to a storage provider index, by bls pub key + StorageProviderSequenceKey = []byte{0x31} + SpStoragePriceUpdateTimesKeyPrefix = []byte{0x32} StorageProviderMaintenanceRecordPrefix = []byte{0x41} ) @@ -109,9 +110,7 @@ func ParseSpStoragePriceKey(key []byte) (spId uint32) { return } -func GlobalSpStorePriceKey( - timestamp int64, -) []byte { +func GlobalSpStorePriceKey(timestamp int64) []byte { timeBytes := make([]byte, 8) binary.BigEndian.PutUint64(timeBytes, uint64(timestamp)) return timeBytes diff --git a/x/sp/types/params.go b/x/sp/types/params.go index d25650a30..bdf8ff2e9 100644 --- a/x/sp/types/params.go +++ b/x/sp/types/params.go @@ -22,6 +22,10 @@ const ( DefaultMaintenanceDurationQuota = 21600 // 6 hour // DefaultNumOfLockUpBlocksForMaintenance defines blocks difference which Sp update itself to Maintenance mode is allowed DefaultNumOfLockUpBlocksForMaintenance = 21600 + // DefaultUpdateGlobalPriceInterval defines the default time duration for updating global storage price + DefaultUpdateGlobalPriceInterval uint64 = 30 * 24 * 60 * 60 // 30 days + // DefaultMaxUpdatePriceTimes defines the max allowed times to update price for each sp in one interval + DefaultMaxUpdatePriceTimes uint32 = 3 ) var ( @@ -38,6 +42,8 @@ var ( KeyNumOfHistoricalBlocksForMaintenanceRecords = []byte("NumOfHistoricalBlocksForMaintenanceRecords") KeyMaintenanceDurationQuota = []byte("MaintenanceDurationQuota") KeyNumOfLockUpBlocksForMaintenance = []byte("NumOfLockUpBlocksForMaintenance") + KeyUpdateGlobalPriceInterval = []byte("UpdateGlobalPriceInterval") + KeyMaxUpdatePriceTimes = []byte("MaxUpdatePriceTimes") ) var _ paramtypes.ParamSet = (*Params)(nil) @@ -49,7 +55,8 @@ func ParamKeyTable() paramtypes.KeyTable { // NewParams creates a new Params instance func NewParams(depositDenom string, minDeposit math.Int, secondarySpStorePriceRatio sdk.Dec, - historicalBlocksForMaintenanceRecords, maintenanceDurationQuota, lockUpBlocksForMaintenance int64) Params { + historicalBlocksForMaintenanceRecords, maintenanceDurationQuota, lockUpBlocksForMaintenance int64, + updateGlobalPriceInterval uint64, maxUpdatePriceTimes uint32) Params { return Params{ DepositDenom: depositDenom, MinDeposit: minDeposit, @@ -57,13 +64,16 @@ func NewParams(depositDenom string, minDeposit math.Int, secondarySpStorePriceRa NumOfHistoricalBlocksForMaintenanceRecords: historicalBlocksForMaintenanceRecords, MaintenanceDurationQuota: maintenanceDurationQuota, NumOfLockupBlocksForMaintenance: lockUpBlocksForMaintenance, + UpdateGlobalPriceInterval: updateGlobalPriceInterval, + MaxUpdatePriceTimes: maxUpdatePriceTimes, } } // DefaultParams returns a default set of parameters func DefaultParams() Params { return NewParams(DefaultDepositDenom, DefaultMinDeposit, DefaultSecondarySpStorePriceRatio, - DefaultNumOfHistoricalBlocksForMaintenanceRecords, DefaultMaintenanceDurationQuota, DefaultNumOfLockUpBlocksForMaintenance) + DefaultNumOfHistoricalBlocksForMaintenanceRecords, DefaultMaintenanceDurationQuota, DefaultNumOfLockUpBlocksForMaintenance, + DefaultUpdateGlobalPriceInterval, DefaultMaxUpdatePriceTimes) } // ParamSetPairs get the params.ParamSet @@ -75,6 +85,8 @@ func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { paramtypes.NewParamSetPair(KeyNumOfHistoricalBlocksForMaintenanceRecords, &p.NumOfHistoricalBlocksForMaintenanceRecords, validateHistoricalBlocksForMaintenanceRecords), paramtypes.NewParamSetPair(KeyMaintenanceDurationQuota, &p.MaintenanceDurationQuota, validateMaintenanceDurationQuota), paramtypes.NewParamSetPair(KeyNumOfLockUpBlocksForMaintenance, &p.NumOfLockupBlocksForMaintenance, validateLockUpBlocksForMaintenance), + paramtypes.NewParamSetPair(KeyUpdateGlobalPriceInterval, &p.UpdateGlobalPriceInterval, validateUpdateGlobalPriceInterval), + paramtypes.NewParamSetPair(KeyMaxUpdatePriceTimes, &p.MaxUpdatePriceTimes, validateMaxUpdatePriceTimes), } } @@ -100,6 +112,13 @@ func (p Params) Validate() error { if err := validateLockUpBlocksForMaintenance(p.NumOfLockupBlocksForMaintenance); err != nil { return err } + if err := validateUpdateGlobalPriceInterval(p.UpdateGlobalPriceInterval); err != nil { + return err + } + if err := validateMaxUpdatePriceTimes(p.MaxUpdatePriceTimes); err != nil { + return err + } + return nil } @@ -175,6 +194,7 @@ func validateMaintenanceDurationQuota(i interface{}) error { } return nil } + func validateLockUpBlocksForMaintenance(i interface{}) error { v, ok := i.(int64) if !ok { @@ -185,3 +205,25 @@ func validateLockUpBlocksForMaintenance(i interface{}) error { } return nil } + +func validateUpdateGlobalPriceInterval(i interface{}) error { + v, ok := i.(uint64) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + if v == 0 { + return errors.New("UpdateGlobalPriceInterval cannot be zero") + } + return nil +} + +func validateMaxUpdatePriceTimes(i interface{}) error { + v, ok := i.(uint32) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + if v == 0 { + return errors.New("MaxUpdatePriceTimes cannot be zero") + } + return nil +} diff --git a/x/sp/types/params.pb.go b/x/sp/types/params.pb.go index eb8246bf7..409be5ac5 100644 --- a/x/sp/types/params.pb.go +++ b/x/sp/types/params.pb.go @@ -39,6 +39,10 @@ type Params struct { MaintenanceDurationQuota int64 `protobuf:"varint,5,opt,name=maintenance_duration_quota,json=maintenanceDurationQuota,proto3" json:"maintenance_duration_quota,omitempty" yaml:"maintenance_duration_quota"` // the number of blocks to be wait for sp to be in maintenance mode again if already requested NumOfLockupBlocksForMaintenance int64 `protobuf:"varint,6,opt,name=num_of_lockup_blocks_for_maintenance,json=numOfLockupBlocksForMaintenance,proto3" json:"num_of_lockup_blocks_for_maintenance,omitempty" yaml:"num_of_lockup_blocks_for_maintenance"` + // the time interval to update global storage price + UpdateGlobalPriceInterval uint64 `protobuf:"varint,7,opt,name=update_global_price_interval,json=updateGlobalPriceInterval,proto3" json:"update_global_price_interval,omitempty" yaml:"update_global_price_interval"` + // the max times allowed to update price during an interval + MaxUpdatePriceTimes uint32 `protobuf:"varint,8,opt,name=max_update_price_times,json=maxUpdatePriceTimes,proto3" json:"max_update_price_times,omitempty" yaml:"max_update_price_times"` } func (m *Params) Reset() { *m = Params{} } @@ -101,6 +105,20 @@ func (m *Params) GetNumOfLockupBlocksForMaintenance() int64 { return 0 } +func (m *Params) GetUpdateGlobalPriceInterval() uint64 { + if m != nil { + return m.UpdateGlobalPriceInterval + } + return 0 +} + +func (m *Params) GetMaxUpdatePriceTimes() uint32 { + if m != nil { + return m.MaxUpdatePriceTimes + } + return 0 +} + func init() { proto.RegisterType((*Params)(nil), "greenfield.sp.Params") } @@ -108,37 +126,43 @@ func init() { func init() { proto.RegisterFile("greenfield/sp/params.proto", fileDescriptor_a5353d8e6e407d7e) } var fileDescriptor_a5353d8e6e407d7e = []byte{ - // 479 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x53, 0x4d, 0x6b, 0xd4, 0x4e, - 0x1c, 0x4e, 0xfe, 0xfd, 0x77, 0xd1, 0xd1, 0x5e, 0x82, 0x87, 0x98, 0x43, 0x52, 0xe3, 0x0b, 0xa5, - 0xb2, 0x1b, 0xc1, 0x83, 0x50, 0x3d, 0x2d, 0x41, 0x2c, 0x28, 0xd6, 0xf4, 0x26, 0xc8, 0x30, 0x99, - 0xcc, 0xee, 0x0e, 0xdd, 0x79, 0x71, 0x66, 0x02, 0xee, 0x45, 0xfc, 0x08, 0x1e, 0x3d, 0x56, 0x3f, - 0x83, 0x1f, 0xa2, 0xc7, 0xe2, 0x49, 0x3c, 0x04, 0xd9, 0xbd, 0x78, 0xde, 0x4f, 0x20, 0x33, 0x09, - 0x6d, 0x04, 0x2b, 0xf4, 0x94, 0xe4, 0xf7, 0x3c, 0xf3, 0xbc, 0x64, 0x66, 0x40, 0x34, 0x55, 0x84, - 0xf0, 0x09, 0x25, 0xf3, 0x2a, 0xd3, 0x32, 0x93, 0x48, 0x21, 0xa6, 0x47, 0x52, 0x09, 0x23, 0x82, - 0xad, 0x73, 0x6c, 0xa4, 0x65, 0x74, 0x13, 0x0b, 0xcd, 0x84, 0x86, 0x0e, 0xcc, 0xda, 0x8f, 0x96, - 0x19, 0xdd, 0x98, 0x8a, 0xa9, 0x68, 0xe7, 0xf6, 0xad, 0x9d, 0xa6, 0x5f, 0x36, 0xc1, 0xe0, 0xc0, - 0x09, 0x06, 0xb7, 0xc1, 0x56, 0x45, 0xa4, 0xd0, 0xd4, 0xc0, 0x8a, 0x70, 0xc1, 0x42, 0x7f, 0xdb, - 0xdf, 0xb9, 0x5a, 0x5c, 0xef, 0x86, 0xb9, 0x9d, 0x05, 0x6f, 0xc0, 0x35, 0x46, 0x39, 0xec, 0x66, - 0xe1, 0x7f, 0x96, 0x32, 0x7e, 0x72, 0xd2, 0x24, 0xde, 0x8f, 0x26, 0xb9, 0x37, 0xa5, 0x66, 0x56, - 0x97, 0x23, 0x2c, 0x58, 0xe7, 0xdd, 0x3d, 0x86, 0xba, 0x3a, 0xca, 0xcc, 0x42, 0x12, 0x3d, 0xda, - 0xe7, 0xe6, 0xdb, 0xd7, 0x21, 0xe8, 0xa2, 0xed, 0x73, 0x53, 0x00, 0x46, 0x79, 0xde, 0xea, 0x05, - 0x1f, 0x7c, 0x10, 0x6b, 0x82, 0x05, 0xaf, 0x90, 0x5a, 0x40, 0x2d, 0xa1, 0x36, 0x42, 0x11, 0x28, - 0x15, 0xc5, 0x04, 0x2a, 0x64, 0xa8, 0x08, 0x37, 0x2e, 0x6d, 0x99, 0x13, 0xdc, 0xb3, 0xcc, 0x09, - 0x2e, 0xa2, 0x33, 0x8f, 0x43, 0x79, 0x68, 0x1d, 0x0e, 0xac, 0x41, 0x61, 0xf5, 0x83, 0xcf, 0x3e, - 0x78, 0xc0, 0x6b, 0x06, 0xc5, 0x04, 0xce, 0xa8, 0xb5, 0xa7, 0x18, 0xcd, 0x61, 0x39, 0x17, 0xf8, - 0x48, 0xc3, 0x89, 0x50, 0x90, 0x21, 0xca, 0x0d, 0xe1, 0x88, 0xdb, 0x48, 0x04, 0x0b, 0x55, 0xe9, - 0xf0, 0xff, 0x6d, 0x7f, 0x67, 0x63, 0xfc, 0x78, 0xdd, 0x24, 0x8f, 0x16, 0x88, 0xcd, 0xf7, 0xd2, - 0xcb, 0x2a, 0xa4, 0xc5, 0x2e, 0xaf, 0xd9, 0xcb, 0xc9, 0xb3, 0xb3, 0x05, 0x63, 0xc7, 0x7f, 0x2a, - 0xd4, 0x8b, 0x73, 0x76, 0xd1, 0x92, 0x03, 0x0c, 0xa2, 0xbe, 0x46, 0x55, 0xbb, 0x5f, 0xc3, 0xe1, - 0xdb, 0x5a, 0x18, 0x14, 0x6e, 0xba, 0x30, 0x77, 0xd7, 0x4d, 0x72, 0xab, 0x0d, 0x73, 0x31, 0x37, - 0x2d, 0xc2, 0x1e, 0x98, 0x77, 0xd8, 0x2b, 0x0b, 0x05, 0xef, 0xc1, 0x9d, 0xae, 0x85, 0x4d, 0x52, - 0xcb, 0x0b, 0x1a, 0x84, 0x03, 0x67, 0x97, 0xad, 0x9b, 0xe4, 0xfe, 0x1f, 0xdd, 0xff, 0xb9, 0x2a, - 0x2d, 0x12, 0xd7, 0xf7, 0xb9, 0x23, 0xfd, 0xad, 0xeb, 0xde, 0x95, 0x4f, 0xc7, 0x89, 0xf7, 0xeb, - 0x38, 0xf1, 0xc7, 0xf9, 0xc9, 0x32, 0xf6, 0x4f, 0x97, 0xb1, 0xff, 0x73, 0x19, 0xfb, 0x1f, 0x57, - 0xb1, 0x77, 0xba, 0x8a, 0xbd, 0xef, 0xab, 0xd8, 0x7b, 0xbd, 0xdb, 0xdb, 0xfe, 0x92, 0x97, 0x43, - 0x3c, 0x43, 0x94, 0x67, 0xbd, 0xfb, 0xf2, 0xce, 0xde, 0x18, 0x77, 0x0c, 0xca, 0x81, 0x3b, 0xf1, - 0x0f, 0x7f, 0x07, 0x00, 0x00, 0xff, 0xff, 0x4d, 0x34, 0x14, 0x4a, 0x4f, 0x03, 0x00, 0x00, + // 569 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x53, 0x4f, 0x6f, 0xd3, 0x30, + 0x1c, 0x6d, 0xd8, 0x28, 0xc3, 0xb0, 0x4b, 0x40, 0x28, 0xab, 0x20, 0xe9, 0x32, 0xfe, 0x54, 0x43, + 0x6d, 0x90, 0x38, 0x20, 0x0d, 0x4e, 0x51, 0x04, 0x54, 0x02, 0x31, 0x32, 0xe0, 0x80, 0x84, 0x2c, + 0x27, 0x71, 0x5b, 0x6b, 0xb1, 0x1d, 0x62, 0x07, 0xb5, 0x17, 0xc4, 0x47, 0xe0, 0xc8, 0x71, 0x7c, + 0x07, 0x3e, 0xc4, 0x8e, 0x13, 0x27, 0xc4, 0x21, 0x42, 0x2d, 0x07, 0xce, 0xfd, 0x04, 0xc8, 0x4e, + 0xd8, 0x8a, 0xb4, 0x4d, 0xda, 0x29, 0xc9, 0x7b, 0xef, 0xf7, 0xde, 0xef, 0xe7, 0xf8, 0x07, 0x5a, + 0xc3, 0x1c, 0x63, 0x36, 0x20, 0x38, 0x4d, 0x3c, 0x91, 0x79, 0x19, 0xca, 0x11, 0x15, 0xbd, 0x2c, + 0xe7, 0x92, 0x9b, 0xab, 0x47, 0x5c, 0x4f, 0x64, 0xad, 0xb5, 0x98, 0x0b, 0xca, 0x05, 0xd4, 0xa4, + 0x57, 0x7d, 0x54, 0xca, 0xd6, 0xd5, 0x21, 0x1f, 0xf2, 0x0a, 0x57, 0x6f, 0x15, 0xea, 0xfe, 0x6e, + 0x82, 0xe6, 0xb6, 0x36, 0x34, 0x37, 0xc0, 0x6a, 0x82, 0x33, 0x2e, 0x88, 0x84, 0x09, 0x66, 0x9c, + 0x5a, 0x46, 0xdb, 0xe8, 0x5c, 0x0c, 0x2f, 0xd7, 0x60, 0xa0, 0x30, 0xf3, 0x1d, 0xb8, 0x44, 0x09, + 0x83, 0x35, 0x66, 0x9d, 0x53, 0x12, 0xff, 0xd1, 0x7e, 0xe9, 0x34, 0x7e, 0x96, 0xce, 0xed, 0x21, + 0x91, 0xa3, 0x22, 0xea, 0xc5, 0x9c, 0xd6, 0xd9, 0xf5, 0xa3, 0x2b, 0x92, 0x5d, 0x4f, 0x4e, 0x32, + 0x2c, 0x7a, 0x7d, 0x26, 0xbf, 0x7f, 0xeb, 0x82, 0xba, 0xb5, 0x3e, 0x93, 0x21, 0xa0, 0x84, 0x05, + 0x95, 0x9f, 0xf9, 0xc9, 0x00, 0xb6, 0xc0, 0x31, 0x67, 0x09, 0xca, 0x27, 0x50, 0x64, 0x50, 0x48, + 0x9e, 0x63, 0x98, 0xe5, 0x24, 0xc6, 0x30, 0x47, 0x92, 0x70, 0x6b, 0xe9, 0xcc, 0x91, 0x01, 0x8e, + 0x17, 0x22, 0x03, 0x1c, 0x87, 0xad, 0xc3, 0x8c, 0x9d, 0x6c, 0x47, 0x25, 0x6c, 0xab, 0x80, 0x50, + 0xf9, 0x9b, 0x5f, 0x0d, 0x70, 0x8f, 0x15, 0x14, 0xf2, 0x01, 0x1c, 0x11, 0x15, 0x4f, 0x62, 0x94, + 0xc2, 0x28, 0xe5, 0xf1, 0xae, 0x80, 0x03, 0x9e, 0x43, 0x8a, 0x08, 0x93, 0x98, 0x21, 0xa6, 0x5a, + 0xc2, 0x31, 0xcf, 0x13, 0x61, 0x2d, 0xb7, 0x8d, 0xce, 0x92, 0xff, 0x70, 0x5e, 0x3a, 0x0f, 0x26, + 0x88, 0xa6, 0x5b, 0xee, 0x59, 0x1d, 0xdc, 0x70, 0x93, 0x15, 0xf4, 0xc5, 0xe0, 0xe9, 0x61, 0x81, + 0xaf, 0xf5, 0x8f, 0x79, 0xfe, 0xfc, 0x48, 0x1d, 0x56, 0x62, 0x33, 0x06, 0xad, 0x45, 0x8f, 0xa4, + 0xd0, 0x47, 0xc3, 0xe0, 0xfb, 0x82, 0x4b, 0x64, 0x9d, 0xd7, 0xcd, 0xdc, 0x9a, 0x97, 0xce, 0x7a, + 0xd5, 0xcc, 0xc9, 0x5a, 0x37, 0xb4, 0x16, 0xc8, 0xa0, 0xe6, 0x5e, 0x2a, 0xca, 0xfc, 0x08, 0x6e, + 0xd6, 0x53, 0xa8, 0x4e, 0x8a, 0xec, 0x84, 0x09, 0xac, 0xa6, 0x8e, 0xf3, 0xe6, 0xa5, 0x73, 0xf7, + 0xbf, 0xd9, 0x4f, 0xad, 0x72, 0x43, 0x47, 0xcf, 0xfb, 0x4c, 0x8b, 0x8e, 0x9b, 0xd5, 0x1c, 0x81, + 0xeb, 0x45, 0x96, 0x20, 0x89, 0xe1, 0x30, 0xe5, 0x11, 0x4a, 0xeb, 0x5b, 0xa0, 0x04, 0xf9, 0x07, + 0x94, 0x5a, 0x17, 0xda, 0x46, 0x67, 0xd9, 0xbf, 0x33, 0x2f, 0x9d, 0x8d, 0x2a, 0xf7, 0x34, 0xb5, + 0x1b, 0xae, 0x55, 0xf4, 0x13, 0xcd, 0xea, 0xff, 0xdd, 0xaf, 0x39, 0xf3, 0x0d, 0xb8, 0x46, 0xd1, + 0x18, 0xd6, 0xf5, 0x55, 0xa1, 0x24, 0x14, 0x0b, 0x6b, 0xa5, 0x6d, 0x74, 0x56, 0xfd, 0xf5, 0x79, + 0xe9, 0xdc, 0xf8, 0x77, 0x94, 0xc7, 0xe9, 0xdc, 0xf0, 0x0a, 0x45, 0xe3, 0xd7, 0x1a, 0xd7, 0xd6, + 0xaf, 0x14, 0xba, 0xb5, 0xf2, 0x65, 0xcf, 0x69, 0xfc, 0xd9, 0x73, 0x0c, 0x3f, 0xd8, 0x9f, 0xda, + 0xc6, 0xc1, 0xd4, 0x36, 0x7e, 0x4d, 0x6d, 0xe3, 0xf3, 0xcc, 0x6e, 0x1c, 0xcc, 0xec, 0xc6, 0x8f, + 0x99, 0xdd, 0x78, 0xbb, 0xb9, 0x70, 0x81, 0x23, 0x16, 0x75, 0xe3, 0x11, 0x22, 0xcc, 0x5b, 0xd8, + 0xf8, 0xb1, 0xda, 0x79, 0x7d, 0x91, 0xa3, 0xa6, 0xde, 0xd9, 0xfb, 0x7f, 0x03, 0x00, 0x00, 0xff, + 0xff, 0xc5, 0xe6, 0x36, 0x68, 0x11, 0x04, 0x00, 0x00, } func (this *Params) Equal(that interface{}) bool { @@ -178,6 +202,12 @@ func (this *Params) Equal(that interface{}) bool { if this.NumOfLockupBlocksForMaintenance != that1.NumOfLockupBlocksForMaintenance { return false } + if this.UpdateGlobalPriceInterval != that1.UpdateGlobalPriceInterval { + return false + } + if this.MaxUpdatePriceTimes != that1.MaxUpdatePriceTimes { + return false + } return true } func (m *Params) Marshal() (dAtA []byte, err error) { @@ -200,6 +230,16 @@ func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.MaxUpdatePriceTimes != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.MaxUpdatePriceTimes)) + i-- + dAtA[i] = 0x40 + } + if m.UpdateGlobalPriceInterval != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.UpdateGlobalPriceInterval)) + i-- + dAtA[i] = 0x38 + } if m.NumOfLockupBlocksForMaintenance != 0 { i = encodeVarintParams(dAtA, i, uint64(m.NumOfLockupBlocksForMaintenance)) i-- @@ -279,6 +319,12 @@ func (m *Params) Size() (n int) { if m.NumOfLockupBlocksForMaintenance != 0 { n += 1 + sovParams(uint64(m.NumOfLockupBlocksForMaintenance)) } + if m.UpdateGlobalPriceInterval != 0 { + n += 1 + sovParams(uint64(m.UpdateGlobalPriceInterval)) + } + if m.MaxUpdatePriceTimes != 0 { + n += 1 + sovParams(uint64(m.MaxUpdatePriceTimes)) + } return n } @@ -474,6 +520,44 @@ func (m *Params) Unmarshal(dAtA []byte) error { break } } + case 7: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field UpdateGlobalPriceInterval", wireType) + } + m.UpdateGlobalPriceInterval = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.UpdateGlobalPriceInterval |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 8: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field MaxUpdatePriceTimes", wireType) + } + m.MaxUpdatePriceTimes = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.MaxUpdatePriceTimes |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } default: iNdEx = preIndex skippy, err := skipParams(dAtA[iNdEx:]) diff --git a/x/storage/client/cli/query_test.go b/x/storage/client/cli/query_test.go index 36141b89b..6a5b73e1e 100644 --- a/x/storage/client/cli/query_test.go +++ b/x/storage/client/cli/query_test.go @@ -3,13 +3,13 @@ package cli_test import ( "fmt" + "github.com/cosmos/cosmos-sdk/client/flags" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/gogoproto/proto" "github.com/bnb-chain/greenfield/testutil/sample" "github.com/bnb-chain/greenfield/x/storage/client/cli" "github.com/bnb-chain/greenfield/x/storage/types" - "github.com/cosmos/cosmos-sdk/client/flags" ) func (s *CLITestSuite) TestQueryCmd() { diff --git a/x/storage/keeper/keeper_test.go b/x/storage/keeper/keeper_test.go index 5c0c44b2c..6188eddba 100644 --- a/x/storage/keeper/keeper_test.go +++ b/x/storage/keeper/keeper_test.go @@ -1,6 +1,8 @@ package keeper_test -import "github.com/bnb-chain/greenfield/testutil/sample" +import ( + "github.com/bnb-chain/greenfield/testutil/sample" +) func (s *TestSuite) TestClearDiscontinueBucketCount() { acc1 := sample.RandAccAddress() diff --git a/x/storage/keeper/payment.go b/x/storage/keeper/payment.go index 87d6953e4..b2fdd8c7d 100644 --- a/x/storage/keeper/payment.go +++ b/x/storage/keeper/payment.go @@ -3,13 +3,12 @@ package keeper import ( "fmt" - sptypes "github.com/bnb-chain/greenfield/x/sp/types" - "cosmossdk.io/errors" sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/bnb-chain/greenfield/x/payment/types" + sptypes "github.com/bnb-chain/greenfield/x/sp/types" storagetypes "github.com/bnb-chain/greenfield/x/storage/types" vgtypes "github.com/bnb-chain/greenfield/x/virtualgroup/types" ) diff --git a/x/virtualgroup/client/cli/query_test.go b/x/virtualgroup/client/cli/query_test.go index 51838ba12..b8299e5d7 100644 --- a/x/virtualgroup/client/cli/query_test.go +++ b/x/virtualgroup/client/cli/query_test.go @@ -3,12 +3,12 @@ package cli_test import ( "fmt" + "github.com/cosmos/cosmos-sdk/client/flags" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" "github.com/cosmos/gogoproto/proto" "github.com/bnb-chain/greenfield/x/virtualgroup/client/cli" "github.com/bnb-chain/greenfield/x/virtualgroup/types" - "github.com/cosmos/cosmos-sdk/client/flags" ) func (s *CLITestSuite) TestQueryCmd() { From 0f540f11ebeb189808ed2c438109a1794e51f07b Mon Sep 17 00:00:00 2001 From: forcodedancing Date: Wed, 9 Aug 2023 16:51:08 -0600 Subject: [PATCH 03/13] update e2e tests --- e2e/core/basesuite.go | 2 +- e2e/tests/payment_test.go | 200 +++++------ e2e/tests/sp_test.go | 183 ++++++++-- e2e/tests/storage_bill_test.go | 448 ++++++++++--------------- x/payment/keeper/storage_fee_charge.go | 14 +- x/sp/keeper/msg_server.go | 2 +- x/sp/keeper/sp_storage_price.go | 2 +- x/storage/keeper/payment.go | 77 ++--- 8 files changed, 484 insertions(+), 444 deletions(-) diff --git a/e2e/core/basesuite.go b/e2e/core/basesuite.go index 107f6f677..416c6cce8 100644 --- a/e2e/core/basesuite.go +++ b/e2e/core/basesuite.go @@ -127,7 +127,7 @@ func (s *BaseSuite) InitChain() { func (s *BaseSuite) SetupSuite() { s.Config = InitConfig() initValidatorOnce.Do(func() { - //s.InitChain() + s.InitChain() }) s.Client, _ = client.NewGreenfieldClient(s.Config.TendermintAddr, s.Config.ChainId) diff --git a/e2e/tests/payment_test.go b/e2e/tests/payment_test.go index a60c7727d..d009b2520 100644 --- a/e2e/tests/payment_test.go +++ b/e2e/tests/payment_test.go @@ -49,7 +49,6 @@ type PaymentTestSuite struct { func (s *PaymentTestSuite) SetupSuite() { s.BaseSuite.SetupSuite() s.defaultParams = s.queryParams() - } func (s *PaymentTestSuite) SetupTest() { @@ -1218,11 +1217,11 @@ func (s *PaymentTestSuite) TestDiscontinue_InOneBlock_WithPriceChange() { streamRecordsBefore := s.getStreamRecords(streamAddresses) // query storage price - priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + priceRes, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, }) s.Require().NoError(err) - s.T().Log("price", priceRes.SpStoragePrice) + s.T().Log("price", priceRes.GlobalSpStorePrice) // create bucket bucketName := s.createBucket(sp, user, 1200987) @@ -1232,13 +1231,8 @@ func (s *PaymentTestSuite) TestDiscontinue_InOneBlock_WithPriceChange() { s.sealObject(sp, gvg, bucketName, objectName1, objectId1, checksums1) // update new price - msgUpdatePrice := &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice, - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice.MulInt64(10000), - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(10000)) + defer s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice) // for payment time.Sleep(2 * time.Second) @@ -1298,15 +1292,6 @@ func (s *PaymentTestSuite) TestDiscontinue_InOneBlock_WithPriceChange() { s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.GVG.NetflowRate.Sub(streamRecordsBefore.GVG.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate).Int64(), int64(0)) - - // revert price - msgUpdatePrice = &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice, - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice, - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) } func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithoutPriceChange() { @@ -1420,11 +1405,11 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChange() { streamRecordsBefore := s.getStreamRecords(streamAddresses) // query storage price - priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + priceRes, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, }) s.Require().NoError(err) - s.T().Log("price", priceRes.SpStoragePrice) + s.T().Log("price", priceRes.GlobalSpStorePrice) // create bucket bucketName := s.createBucket(sp, user, 0) @@ -1443,13 +1428,8 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChange() { } // update new price - msgUpdatePrice := &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice, - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice.MulInt64(10000), - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(10000)) + defer s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice) // create & seal objects for i := 0; i < 2; i++ { @@ -1495,13 +1475,7 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChange() { deleteAt := filterDiscontinueBucketEventFromTx(txRes).DeleteAt // update new price - msgUpdatePrice = &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice.MulInt64(100), - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice.MulInt64(10000), - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice.MulInt64(100), priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(10000)) for { time.Sleep(200 * time.Millisecond) @@ -1523,15 +1497,6 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChange() { s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.GVG.NetflowRate.Sub(streamRecordsBefore.GVG.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate).Int64(), int64(0)) - - // revert price - msgUpdatePrice = &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice, - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice, - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) } func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChangeReserveTimeChange() { @@ -1539,13 +1504,21 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChangeReserveTimeCh ctx := context.Background() sp := s.PickStorageProvider() - gvg, found := sp.GetFirstGlobalVirtualGroup() - s.Require().True(found) + + _, secondarySps := s.GetSecondarySP(sp) + gvgID, _ := s.BaseSuite.CreateGlobalVirtualGroup(sp, 0, secondarySps, 1) + gvgResp, err := s.Client.VirtualGroupQueryClient.GlobalVirtualGroup(context.Background(), &virtualgrouptypes.QueryGlobalVirtualGroupRequest{ + GlobalVirtualGroupId: gvgID, + }) + s.Require().NoError(err) + gvg := gvgResp.GlobalVirtualGroup + queryFamilyResponse, err := s.Client.GlobalVirtualGroupFamily(ctx, &virtualgrouptypes.QueryGlobalVirtualGroupFamilyRequest{ FamilyId: gvg.FamilyId, }) s.Require().NoError(err) family := queryFamilyResponse.GlobalVirtualGroupFamily + user := s.GenAndChargeAccounts(1, 1000000)[0] streamAddresses := []string{ @@ -1557,14 +1530,14 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChangeReserveTimeCh streamRecordsBefore := s.getStreamRecords(streamAddresses) // query storage price - priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + priceRes, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, }) s.Require().NoError(err) - s.T().Log("price", priceRes.SpStoragePrice) + s.T().Log("price", priceRes.GlobalSpStorePrice) // create bucket - bucketName := s.createBucket(sp, user, 10200) + bucketName := s.createBucketWithGVG(sp, gvg, user, 10200) // create objects for i := 0; i < 2; i++ { @@ -1580,13 +1553,8 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChangeReserveTimeCh } // update new price - msgUpdatePrice := &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice, - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice.MulInt64(10000), - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(10000)) + defer s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice) // create & seal objects for i := 0; i < 2; i++ { @@ -1641,13 +1609,7 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChangeReserveTimeCh deleteAt := filterDiscontinueBucketEventFromTx(txRes).DeleteAt // update new price - msgUpdatePrice = &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice.MulInt64(100), - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice.MulInt64(10000), - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice.MulInt64(100), priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(10000)) for { time.Sleep(200 * time.Millisecond) @@ -1669,15 +1631,6 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChangeReserveTimeCh s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.GVG.NetflowRate.Sub(streamRecordsBefore.GVG.NetflowRate).Int64(), int64(0)) s.Require().True(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate).Int64() <= int64(0)) // there are other auto settling - - // revert price - msgUpdatePrice = &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice, - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice, - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) } func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChangeReserveTimeChange_FrozenAccount() { @@ -1708,14 +1661,14 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChangeReserveTimeCh streamRecordsBefore := s.getStreamRecords(streamAddresses) // query storage price - priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + priceRes, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, }) s.Require().NoError(err) - s.T().Log("price", priceRes.SpStoragePrice) + s.T().Log("price", priceRes.GlobalSpStorePrice) // create bucket - bucketName := s.createBucket(sp, user, 0) + bucketName := s.createBucketWithGVG(sp, gvg, user, 0) // create objects for i := 0; i < 2; i++ { @@ -1733,13 +1686,8 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChangeReserveTimeCh s.Require().True(userStreamRecord.LockBalance.IsPositive()) // update new price - msgUpdatePrice := &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice, - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice.MulInt64(10000), - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(10000)) + defer s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice) // update params params.VersionedParams.ReserveTime = 8 @@ -1802,13 +1750,7 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChangeReserveTimeCh deleteAt := filterDiscontinueBucketEventFromTx(txRes).DeleteAt // update new price - msgUpdatePrice = &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice.MulInt64(100), - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice.MulInt64(10000), - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice.MulInt64(100), priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(10000)) for { time.Sleep(200 * time.Millisecond) @@ -1833,15 +1775,6 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChangeReserveTimeCh s.Require().True(streamRecordsAfter.User.LockBalance.IsZero()) s.Require().True(streamRecordsAfter.User.StaticBalance.Int64() == userStreamRecord.LockBalance.Int64()) - - // revert price - msgUpdatePrice = &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice, - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice, - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) } func (s *PaymentTestSuite) TestDiscontinue_MultiObjects() { @@ -2143,7 +2076,7 @@ func (s *PaymentTestSuite) getChargeSize(payloadSize uint64) uint64 { } } -func (s *PaymentTestSuite) calculateLockFee(sp *core.StorageProvider, bucketName, objectName string, payloadSize uint64) sdkmath.Int { +func (s *PaymentTestSuite) calculateLockFee(bucketName, objectName string, payloadSize uint64) sdkmath.Int { ctx := context.Background() params := s.queryParams() @@ -2157,7 +2090,7 @@ func (s *PaymentTestSuite) calculateLockFee(sp *core.StorageProvider, bucketName secondarySpCount := storageParams.Params.VersionedParams.RedundantDataChunkNum + storageParams.Params.VersionedParams.RedundantParityChunkNum chargeSize := s.getChargeSize(payloadSize) - _, primaryPrice, secondaryPrice := s.getPrices(sp, headBucketExtraResponse.ExtraInfo.PriceTime) + _, primaryPrice, secondaryPrice := s.getPrices(headBucketExtraResponse.ExtraInfo.PriceTime) gvgFamilyRate := primaryPrice.MulInt(sdkmath.NewIntFromUint64(chargeSize)).TruncateInt() gvgRate := secondaryPrice.MulInt(sdkmath.NewIntFromUint64(chargeSize)).TruncateInt() @@ -2166,7 +2099,7 @@ func (s *PaymentTestSuite) calculateLockFee(sp *core.StorageProvider, bucketName return gvgFamilyRate.Add(gvgRate).Add(taxRate).MulRaw(int64(params.VersionedParams.ReserveTime)) } -func (s *PaymentTestSuite) getPrices(sp *core.StorageProvider, timestamp int64) (sdk.Dec, sdk.Dec, sdk.Dec) { +func (s *PaymentTestSuite) getPrices(timestamp int64) (sdk.Dec, sdk.Dec, sdk.Dec) { ctx := context.Background() spStoragePriceByTimeResp, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ @@ -2179,7 +2112,7 @@ func (s *PaymentTestSuite) getPrices(sp *core.StorageProvider, timestamp int64) spStoragePriceByTimeResp.GlobalSpStorePrice.SecondaryStorePrice } -func (s *PaymentTestSuite) calculateReadRates(sp *core.StorageProvider, bucketName string) (sdkmath.Int, sdkmath.Int, sdkmath.Int) { +func (s *PaymentTestSuite) calculateReadRates(bucketName string) (sdkmath.Int, sdkmath.Int, sdkmath.Int) { ctx := context.Background() params := s.queryParams() @@ -2190,14 +2123,14 @@ func (s *PaymentTestSuite) calculateReadRates(sp *core.StorageProvider, bucketNa headBucketResponse, err := s.Client.HeadBucket(ctx, &headBucketRequest) s.Require().NoError(err) - readPrice, _, _ := s.getPrices(sp, headBucketResponse.BucketInfo.CreateAt) + readPrice, _, _ := s.getPrices(headBucketResponse.BucketInfo.CreateAt) gvgFamilyRate := readPrice.MulInt64(int64(headBucketResponse.BucketInfo.ChargedReadQuota)).TruncateInt() taxRate := params.VersionedParams.ValidatorTaxRate.MulInt(gvgFamilyRate).TruncateInt() return gvgFamilyRate, taxRate, gvgFamilyRate.Add(taxRate) } -func (s *PaymentTestSuite) calculateReadRatesCurrentTimestamp(sp *core.StorageProvider, bucketName string) (sdkmath.Int, sdkmath.Int, sdkmath.Int) { +func (s *PaymentTestSuite) calculateReadRatesCurrentTimestamp(bucketName string) (sdkmath.Int, sdkmath.Int, sdkmath.Int) { ctx := context.Background() params := s.queryParams() @@ -2208,14 +2141,14 @@ func (s *PaymentTestSuite) calculateReadRatesCurrentTimestamp(sp *core.StoragePr headBucketResponse, err := s.Client.HeadBucket(ctx, &headBucketRequest) s.Require().NoError(err) - readPrice, _, _ := s.getPrices(sp, time.Now().Unix()) + readPrice, _, _ := s.getPrices(time.Now().Unix()) gvgFamilyRate := readPrice.MulInt64(int64(headBucketResponse.BucketInfo.ChargedReadQuota)).TruncateInt() taxRate := params.VersionedParams.ValidatorTaxRate.MulInt(gvgFamilyRate).TruncateInt() return gvgFamilyRate, taxRate, gvgFamilyRate.Add(taxRate) } -func (s *PaymentTestSuite) calculateStorageRates(sp *core.StorageProvider, bucketName, objectName string, payloadSize uint64, priceTime int64) (sdkmath.Int, sdkmath.Int, sdkmath.Int, sdkmath.Int) { +func (s *PaymentTestSuite) calculateStorageRates(bucketName, objectName string, payloadSize uint64, priceTime int64) (sdkmath.Int, sdkmath.Int, sdkmath.Int, sdkmath.Int) { params := s.queryParams() queryHeadObjectRequest := storagetypes.QueryHeadObjectRequest{ @@ -2236,7 +2169,7 @@ func (s *PaymentTestSuite) calculateStorageRates(sp *core.StorageProvider, bucke } chargeSize := s.getChargeSize(payloadSize) - _, primaryPrice, secondaryPrice := s.getPrices(sp, priceTime) + _, primaryPrice, secondaryPrice := s.getPrices(priceTime) s.T().Logf("===secondaryPrice: %v,primaryPrice: %v===", secondaryPrice, primaryPrice) gvgFamilyRate := primaryPrice.MulInt(sdkmath.NewIntFromUint64(chargeSize)).TruncateInt() gvgRate := secondaryPrice.MulInt(sdkmath.NewIntFromUint64(chargeSize)).TruncateInt() @@ -2245,7 +2178,7 @@ func (s *PaymentTestSuite) calculateStorageRates(sp *core.StorageProvider, bucke return gvgFamilyRate, gvgRate, taxRate, gvgFamilyRate.Add(gvgRate).Add(taxRate) } -func (s *PaymentTestSuite) calculateStorageRatesCurrentTimestamp(sp *core.StorageProvider, bucketName, objectName string, payloadSize uint64) (sdkmath.Int, sdkmath.Int, sdkmath.Int, sdkmath.Int) { +func (s *PaymentTestSuite) calculateStorageRatesCurrentTimestamp(bucketName, objectName string, payloadSize uint64) (sdkmath.Int, sdkmath.Int, sdkmath.Int, sdkmath.Int) { params := s.queryParams() queryHeadObjectRequest := storagetypes.QueryHeadObjectRequest{ @@ -2258,7 +2191,7 @@ func (s *PaymentTestSuite) calculateStorageRatesCurrentTimestamp(sp *core.Storag fmt.Println("secondarySpCount", secondarySpCount) chargeSize := s.getChargeSize(payloadSize) - _, primaryPrice, secondaryPrice := s.getPrices(sp, time.Now().Unix()) + _, primaryPrice, secondaryPrice := s.getPrices(time.Now().Unix()) gvgFamilyRate := primaryPrice.MulInt(sdkmath.NewIntFromUint64(chargeSize)).TruncateInt() gvgRate := secondaryPrice.MulInt(sdkmath.NewIntFromUint64(chargeSize)).TruncateInt() @@ -2427,6 +2360,27 @@ func (s *PaymentTestSuite) createBucket(sp *core.StorageProvider, user keys.KeyM return bucketName } +func (s *PaymentTestSuite) createBucketWithGVG(sp *core.StorageProvider, gvg *virtualgrouptypes.GlobalVirtualGroup, user keys.KeyManager, readQuota uint64) string { + var err error + // CreateBucket + bucketName := "ch" + storagetestutils.GenRandomBucketName() + msgCreateBucket := storagetypes.NewMsgCreateBucket( + user.GetAddr(), bucketName, storagetypes.VISIBILITY_TYPE_PRIVATE, sp.OperatorKey.GetAddr(), + nil, math.MaxUint, nil, readQuota) + msgCreateBucket.PrimarySpApproval.GlobalVirtualGroupFamilyId = gvg.FamilyId + msgCreateBucket.PrimarySpApproval.Sig, err = sp.ApprovalKey.Sign(msgCreateBucket.GetApprovalBytes()) + s.Require().NoError(err) + s.SendTxBlock(user, msgCreateBucket) + + queryHeadBucketRequest := storagetypes.QueryHeadBucketRequest{ + BucketName: bucketName, + } + _, err = s.Client.HeadBucket(context.Background(), &queryHeadBucketRequest) + s.Require().NoError(err) + + return bucketName +} + func (s *PaymentTestSuite) createObject(user keys.KeyManager, bucketName string, empty bool) (keys.KeyManager, string, string, storagetypes.Uint, [][]byte, uint64) { var err error sp := s.BaseSuite.PickStorageProviderByBucketName(bucketName) @@ -2666,3 +2620,23 @@ func (s *PaymentTestSuite) queryParams() paymenttypes.Params { s.T().Log("params", core.YamlString(queryParamsResponse.Params)) return queryParamsResponse.Params } + +func (s *PaymentTestSuite) updateGlobalSpPrice(readPrice, storePrice sdk.Dec) { + ctx := context.Background() + globalPriceResBefore, _ := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{Timestamp: 0}) + s.T().Log("globalPriceResBefore", core.YamlString(globalPriceResBefore)) + + for _, sp := range s.BaseSuite.StorageProviders { + msgUpdateSpStoragePrice := &sptypes.MsgUpdateSpStoragePrice{ + SpAddress: sp.OperatorKey.GetAddr().String(), + ReadPrice: readPrice, + StorePrice: storePrice, + FreeReadQuota: 1024 * 1024, + } + s.SendTxBlock(sp.OperatorKey, msgUpdateSpStoragePrice) + } + time.Sleep(2 * time.Second) + + globalPriceResAfter, _ := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{Timestamp: 0}) + s.T().Log("globalPriceResAfter1", core.YamlString(globalPriceResAfter)) +} diff --git a/e2e/tests/sp_test.go b/e2e/tests/sp_test.go index da1c20b80..a28b0f7c3 100644 --- a/e2e/tests/sp_test.go +++ b/e2e/tests/sp_test.go @@ -27,10 +27,12 @@ import ( type StorageProviderTestSuite struct { core.BaseSuite + defaultParams sptypes.Params } func (s *StorageProviderTestSuite) SetupSuite() { s.BaseSuite.SetupSuite() + s.defaultParams = s.queryParams() } func (s *StorageProviderTestSuite) SetupTest() { @@ -155,9 +157,23 @@ func (s *StorageProviderTestSuite) TestDeposit() { s.Require().Equal(txRes.Code, uint32(0)) } -func (s *StorageProviderTestSuite) TestSpStoragePrice() { +func (s *StorageProviderTestSuite) TestUpdateSpStoragePrice() { ctx := context.Background() - s.CheckGlobalSpStorePrice() + defer s.revertParams() + + // update params + params := s.queryParams() + params.UpdateGlobalPriceInterval = 10 + params.MaxUpdatePriceTimes = 2 + s.updateParams(params) + + // query sp storage price by time before it exists, expect error + _, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 1, + }) + s.Require().Error(err) + + // check update price sp := s.BaseSuite.PickStorageProvider() spAddr := sp.OperatorKey.GetAddr().String() spStoragePrice, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ @@ -165,31 +181,74 @@ func (s *StorageProviderTestSuite) TestSpStoragePrice() { }) s.Require().NoError(err) s.T().Log(spStoragePrice) - // update storage price - newReadPrice := sdk.NewDec(core.RandInt64(100, 200)) - newStorePrice := sdk.NewDec(core.RandInt64(10000, 20000)) + + // update storage price - first update is ok msgUpdateSpStoragePrice := &sptypes.MsgUpdateSpStoragePrice{ SpAddress: spAddr, - ReadPrice: newReadPrice, - StorePrice: newStorePrice, + ReadPrice: spStoragePrice.SpStoragePrice.ReadPrice, + StorePrice: spStoragePrice.SpStoragePrice.StorePrice, FreeReadQuota: spStoragePrice.SpStoragePrice.FreeReadQuota, } _ = s.SendTxBlock(sp.OperatorKey, msgUpdateSpStoragePrice) - // query and assert - spStoragePrice2, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: spAddr, - }) - s.Require().NoError(err) - s.T().Log(spStoragePrice2) - // check price changed as expected - s.Require().Equal(newReadPrice, spStoragePrice2.SpStoragePrice.ReadPrice) - s.Require().Equal(newStorePrice, spStoragePrice2.SpStoragePrice.StorePrice) + + // update storage price - secondary update is ok + msgUpdateSpStoragePrice = &sptypes.MsgUpdateSpStoragePrice{ + SpAddress: spAddr, + ReadPrice: spStoragePrice.SpStoragePrice.ReadPrice, + StorePrice: spStoragePrice.SpStoragePrice.StorePrice, + FreeReadQuota: spStoragePrice.SpStoragePrice.FreeReadQuota, + } + _ = s.SendTxBlock(sp.OperatorKey, msgUpdateSpStoragePrice) + + // update storage price - third update is not ok + msgUpdateSpStoragePrice = &sptypes.MsgUpdateSpStoragePrice{ + SpAddress: spAddr, + ReadPrice: spStoragePrice.SpStoragePrice.ReadPrice, + StorePrice: spStoragePrice.SpStoragePrice.StorePrice, + FreeReadQuota: spStoragePrice.SpStoragePrice.FreeReadQuota, + } + s.SendTxBlockWithExpectErrorString(msgUpdateSpStoragePrice, sp.OperatorKey, "cannot update price due to frequency limited") + + time.Sleep(12 * time.Second) + + // verify price is updated after interval + globalPriceResBefore, _ := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{Timestamp: 0}) + s.T().Log("globalPriceResBefore", core.YamlString(globalPriceResBefore)) + priceChanged := false + globalPriceResAfter1, _ := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{Timestamp: 0}) + s.T().Log("globalPriceResAfter1", core.YamlString(globalPriceResAfter1)) + for _, sp := range s.BaseSuite.StorageProviders { + msgUpdateSpStoragePrice = &sptypes.MsgUpdateSpStoragePrice{ + SpAddress: sp.OperatorKey.GetAddr().String(), + ReadPrice: spStoragePrice.SpStoragePrice.ReadPrice.MulInt64(10), + StorePrice: spStoragePrice.SpStoragePrice.StorePrice.MulInt64(10), + FreeReadQuota: spStoragePrice.SpStoragePrice.FreeReadQuota, + } + s.SendTxBlock(sp.OperatorKey, msgUpdateSpStoragePrice) + + globalPriceResAfter1, _ = s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{Timestamp: 0}) + s.T().Log("globalPriceResAfter1", core.YamlString(globalPriceResAfter1)) + if !globalPriceResAfter1.GlobalSpStorePrice.PrimaryStorePrice.Equal(globalPriceResBefore.GlobalSpStorePrice.PrimaryStorePrice) { + s.CheckGlobalSpStorePrice() + priceChanged = true + break + } + } + + time.Sleep(12 * time.Second) + globalPriceResAfter2, _ := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{Timestamp: 0}) + s.T().Log("globalPriceResAfter2", core.YamlString(globalPriceResAfter2)) + s.CheckGlobalSpStorePrice() - // query sp storage price by time before it exists, expect error - _, err = s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ - Timestamp: 1, - }) - s.Require().Error(err) + if !priceChanged { //if price not changed, then after 10 seconds, it should change + s.Require().NotEqual(globalPriceResAfter2.GlobalSpStorePrice.PrimaryStorePrice, globalPriceResBefore.GlobalSpStorePrice.PrimaryStorePrice) + s.Require().NotEqual(globalPriceResAfter2.GlobalSpStorePrice.SecondaryStorePrice, globalPriceResBefore.GlobalSpStorePrice.SecondaryStorePrice) + s.Require().NotEqual(globalPriceResAfter2.GlobalSpStorePrice.ReadPrice, globalPriceResBefore.GlobalSpStorePrice.ReadPrice) + } else { //if price not changed already, then after 10 seconds, it should not change + s.Require().Equal(globalPriceResAfter2.GlobalSpStorePrice.PrimaryStorePrice, globalPriceResAfter1.GlobalSpStorePrice.PrimaryStorePrice) + s.Require().Equal(globalPriceResAfter2.GlobalSpStorePrice.SecondaryStorePrice, globalPriceResAfter1.GlobalSpStorePrice.SecondaryStorePrice) + s.Require().Equal(globalPriceResAfter2.GlobalSpStorePrice.ReadPrice, globalPriceResAfter1.GlobalSpStorePrice.ReadPrice) + } } func (s *StorageProviderTestSuite) CheckGlobalSpStorePrice() { @@ -382,3 +441,85 @@ func (s *StorageProviderTestSuite) TestUpdateStorageProviderStatus() { s.Require().NoError(err) s.Require().Equal(sptypes.STATUS_IN_SERVICE, spResp.StorageProvider.Status) } + +func (s *StorageProviderTestSuite) queryParams() sptypes.Params { + queryParamsRequest := sptypes.QueryParamsRequest{} + queryParamsResponse, err := s.Client.SpQueryClient.Params(context.Background(), &queryParamsRequest) + s.Require().NoError(err) + s.T().Log("params", core.YamlString(queryParamsResponse.Params)) + return queryParamsResponse.Params +} + +func (s *StorageProviderTestSuite) revertParams() { + s.updateParams(s.defaultParams) +} + +func (s *StorageProviderTestSuite) updateParams(params sptypes.Params) { + var err error + validator := s.Validator.GetAddr() + + ctx := context.Background() + + queryParamsRequest := &sptypes.QueryParamsRequest{} + queryParamsResponse, err := s.Client.SpQueryClient.Params(ctx, queryParamsRequest) + s.Require().NoError(err) + s.T().Log("params before", core.YamlString(queryParamsResponse.Params)) + + msgUpdateParams := &sptypes.MsgUpdateParams{ + Authority: authtypes.NewModuleAddress(govtypes.ModuleName).String(), + Params: params, + } + + msgProposal, err := v1.NewMsgSubmitProposal( + []sdk.Msg{msgUpdateParams}, + sdk.Coins{sdk.NewCoin(s.BaseSuite.Config.Denom, types.NewIntFromInt64WithDecimal(100, types.DecimalBNB))}, + validator.String(), + "test", "test", "test", + ) + s.Require().NoError(err) + + txRes := s.SendTxBlock(s.Validator, msgProposal) + s.Require().Equal(txRes.Code, uint32(0)) + + // 3. query proposal and get proposal ID + var proposalId uint64 + for _, event := range txRes.Logs[0].Events { + if event.Type == "submit_proposal" { + for _, attr := range event.Attributes { + if attr.Key == "proposal_id" { + proposalId, err = strconv.ParseUint(attr.Value, 10, 0) + s.Require().NoError(err) + break + } + } + break + } + } + s.Require().True(proposalId != 0) + + queryProposal := &v1.QueryProposalRequest{ProposalId: proposalId} + _, err = s.Client.GovQueryClientV1.Proposal(ctx, queryProposal) + s.Require().NoError(err) + + // 4. submit MsgVote and wait the proposal exec + msgVote := v1.NewMsgVote(validator, proposalId, v1.OptionYes, "test") + txRes = s.SendTxBlock(s.Validator, msgVote) + s.Require().Equal(txRes.Code, uint32(0)) + + queryVoteParamsReq := v1.QueryParamsRequest{ParamsType: "voting"} + queryVoteParamsResp, err := s.Client.GovQueryClientV1.Params(ctx, &queryVoteParamsReq) + s.Require().NoError(err) + + // 5. wait a voting period and confirm that the proposal success. + s.T().Logf("voting period %s", *queryVoteParamsResp.Params.VotingPeriod) + time.Sleep(*queryVoteParamsResp.Params.VotingPeriod) + time.Sleep(1 * time.Second) + proposalRes, err := s.Client.GovQueryClientV1.Proposal(ctx, queryProposal) + s.Require().NoError(err) + s.Require().Equal(proposalRes.Proposal.Status, v1.ProposalStatus_PROPOSAL_STATUS_PASSED) + + queryParamsRequest = &sptypes.QueryParamsRequest{} + queryParamsResponse, err = s.Client.SpQueryClient.Params(ctx, queryParamsRequest) + s.Require().NoError(err) + s.T().Log("params after", core.YamlString(queryParamsResponse.Params)) +} diff --git a/e2e/tests/storage_bill_test.go b/e2e/tests/storage_bill_test.go index ab8c9febb..8068877fc 100644 --- a/e2e/tests/storage_bill_test.go +++ b/e2e/tests/storage_bill_test.go @@ -441,20 +441,15 @@ func (s *PaymentTestSuite) TestStorageBill_DeleteObjectBucket_WithPriceChange() s.Require().NoError(err) // sp price changes - priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + priceRes, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, }) s.Require().NoError(err) - s.T().Log("price", priceRes.SpStoragePrice) + s.T().Log("price", priceRes.GlobalSpStorePrice) // update new price - msgUpdatePrice := &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice.MulInt64(1000), - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice.MulInt64(10000), - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice.MulInt64(1000), priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(10000)) + defer s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice) s.SendTxBlock(user, msgDeleteObject) s.SendTxBlock(user, msgDeleteBucket) @@ -466,15 +461,6 @@ func (s *PaymentTestSuite) TestStorageBill_DeleteObjectBucket_WithPriceChange() s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.GVG.NetflowRate.Sub(streamRecordsBefore.GVG.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate).Int64(), int64(0)) - - // revert price - msgUpdatePrice = &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice, - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice, - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) } func (s *PaymentTestSuite) TestStorageBill_DeleteObjectBucket_WithPriceChangeReserveTimeChange() { @@ -555,20 +541,15 @@ func (s *PaymentTestSuite) TestStorageBill_DeleteObjectBucket_WithPriceChangeRes s.Require().NoError(err) // sp price changes - priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + priceRes, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, }) s.Require().NoError(err) - s.T().Log("price", priceRes.SpStoragePrice) + s.T().Log("price", priceRes.GlobalSpStorePrice) // update new price - msgUpdatePrice := &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice.MulInt64(1000), - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice.MulInt64(10000), - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice.MulInt64(1000), priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(10000)) + defer s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice) // update params params := s.queryParams() @@ -589,15 +570,6 @@ func (s *PaymentTestSuite) TestStorageBill_DeleteObjectBucket_WithPriceChangeRes s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.GVG.NetflowRate.Sub(streamRecordsBefore.GVG.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate).Int64(), int64(0)) - - // revert price - msgUpdatePrice = &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice, - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice, - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) } func (s *PaymentTestSuite) TestStorageBill_DeleteObject_WithStoreLessThanReserveTime() { @@ -637,8 +609,8 @@ func (s *PaymentTestSuite) TestStorageBill_DeleteObject_WithStoreLessThanReserve paymenttypes.ValidatorTaxPoolAddress.String(), } streamRecordsBefore := s.getStreamRecords(streamAddresses) - _, _, userRateRead := s.calculateReadRates(sp, bucketName) - _, _, _, userRateStore := s.calculateStorageRates(sp, bucketName, objectName1, payloadSize, 0) + _, _, userRateRead := s.calculateReadRates(bucketName) + _, _, _, userRateStore := s.calculateStorageRates(bucketName, objectName1, payloadSize, 0) msgDeleteObject := storagetypes.NewMsgDeleteObject(user.GetAddr(), bucketName, objectName1) s.SendTxBlock(user, msgDeleteObject) @@ -709,8 +681,8 @@ func (s *PaymentTestSuite) TestStorageBill_DeleteObject_WithStoreMoreThanReserve paymenttypes.ValidatorTaxPoolAddress.String(), } streamRecordsBefore := s.getStreamRecords(streamAddresses) - _, _, userRateRead := s.calculateReadRates(sp, bucketName) - _, _, _, userRateStore := s.calculateStorageRates(sp, bucketName, objectName1, payloadSize, 0) + _, _, userRateRead := s.calculateReadRates(bucketName) + _, _, _, userRateStore := s.calculateStorageRates(bucketName, objectName1, payloadSize, 0) msgDeleteObject := storagetypes.NewMsgDeleteObject(user.GetAddr(), bucketName, objectName1) simulateResponse := s.SimulateTx(msgDeleteObject, user) @@ -860,7 +832,7 @@ func (s *PaymentTestSuite) TestStorageBill_CreateObject_WithZeroNoneZeroPayload( streamRecordsAfter := s.getStreamRecords(streamAddresses) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) s.Require().Equal(streamRecordsAfter.User.LockBalance, sdkmath.ZeroInt()) - gvgFamilyRate, gvgRate, taxRate, userTotalRate := s.calculateStorageRates(sp, bucketName, objectName, payloadSize, 0) + gvgFamilyRate, gvgRate, taxRate, userTotalRate := s.calculateStorageRates(bucketName, objectName, payloadSize, 0) s.Require().Equal(streamRecordsAfter.User.NetflowRate.Sub(streamRecordsBefore.User.NetflowRate), userTotalRate.Neg()) s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate), gvgFamilyRate) s.Require().Equal(streamRecordsAfter.GVG.NetflowRate.Sub(streamRecordsBefore.GVG.NetflowRate), gvgRate) @@ -873,7 +845,7 @@ func (s *PaymentTestSuite) TestStorageBill_CreateObject_WithZeroNoneZeroPayload( // assertions streamRecordsAfter = s.getStreamRecords(streamAddresses) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) - lockFee := s.calculateLockFee(sp, bucketName, objectName, payloadSize) + lockFee := s.calculateLockFee(bucketName, objectName, payloadSize) s.Require().Equal(streamRecordsAfter.User.LockBalance.Sub(streamRecordsBefore.User.LockBalance), lockFee) s.Require().Equal(streamRecordsAfter.User.NetflowRate.Sub(streamRecordsBefore.User.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), int64(0)) @@ -912,7 +884,7 @@ func (s *PaymentTestSuite) TestStorageBill_CreateObject_WithReserveTimeValidator // assertions streamRecordsAfter := s.getStreamRecords(streamAddresses) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) - lockFee := s.calculateLockFee(sp, bucketName, objectName, payloadSize) + lockFee := s.calculateLockFee(bucketName, objectName, payloadSize) s.Require().Equal(streamRecordsAfter.User.LockBalance.Sub(streamRecordsBefore.User.LockBalance), lockFee) s.Require().Equal(streamRecordsAfter.User.NetflowRate.Sub(streamRecordsBefore.User.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), int64(0)) @@ -936,7 +908,7 @@ func (s *PaymentTestSuite) TestStorageBill_CreateObject_WithReserveTimeValidator // assertions streamRecordsAfter = s.getStreamRecords(streamAddresses) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) - lockFeeAfterParameterChange := s.calculateLockFee(sp, bucketName, objectName, payloadSize) + lockFeeAfterParameterChange := s.calculateLockFee(bucketName, objectName, payloadSize) s.Require().Equal(streamRecordsAfter.User.LockBalance.Sub(streamRecordsBefore.User.LockBalance), lockFeeAfterParameterChange) s.Require().Equal(streamRecordsAfter.User.NetflowRate.Sub(streamRecordsBefore.User.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), int64(0)) @@ -974,7 +946,7 @@ func (s *PaymentTestSuite) TestStorageBill_CancelCreateObject() { // assertions streamRecordsAfter := s.getStreamRecords(streamAddresses) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) - lockFee := s.calculateLockFee(sp, bucketName, objectName, payloadSize) + lockFee := s.calculateLockFee(bucketName, objectName, payloadSize) s.Require().Equal(streamRecordsAfter.User.LockBalance.Sub(streamRecordsBefore.User.LockBalance), lockFee) s.Require().Equal(streamRecordsAfter.User.NetflowRate.Sub(streamRecordsBefore.User.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), int64(0)) @@ -1023,7 +995,7 @@ func (s *PaymentTestSuite) TestStorageBill_SealObject_WithoutPriceChange() { // assertions streamRecordsAfter := s.getStreamRecords(streamAddresses) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) - lockFee := s.calculateLockFee(sp, bucketName, objectName, payloadSize) + lockFee := s.calculateLockFee(bucketName, objectName, payloadSize) s.Require().Equal(streamRecordsAfter.User.LockBalance.Sub(streamRecordsBefore.User.LockBalance), lockFee) s.Require().Equal(streamRecordsAfter.User.NetflowRate.Sub(streamRecordsBefore.User.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), int64(0)) @@ -1037,7 +1009,7 @@ func (s *PaymentTestSuite) TestStorageBill_SealObject_WithoutPriceChange() { streamRecordsAfter = s.getStreamRecords(streamAddresses) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) s.Require().Equal(streamRecordsAfter.User.LockBalance, sdkmath.ZeroInt()) - gvgFamilyRate, gvgRate, taxRate, userTotalRate := s.calculateStorageRates(sp, bucketName, objectName, payloadSize, 0) + gvgFamilyRate, gvgRate, taxRate, userTotalRate := s.calculateStorageRates(bucketName, objectName, payloadSize, 0) s.Require().Equal(streamRecordsAfter.User.NetflowRate.Sub(streamRecordsBefore.User.NetflowRate), userTotalRate.Neg()) s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate), gvgFamilyRate) s.Require().Equal(streamRecordsAfter.GVG.NetflowRate.Sub(streamRecordsBefore.GVG.NetflowRate), gvgRate) @@ -1069,29 +1041,26 @@ func (s *PaymentTestSuite) TestStorageBill_SealObject_WithPriceChange() { // case: seal object with read price change and storage price change _, _, objectName, objectId, checksums, payloadSize := s.createObject(user, bucketName, false) - priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + priceRes, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, }) s.Require().NoError(err) + s.T().Log("price", priceRes.GlobalSpStorePrice) + // update new price - msgUpdatePrice := &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice.MulInt64(2), - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice.MulInt64(2), - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice.MulInt64(2), priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(2)) + defer s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice) streamRecordsBefore := s.getStreamRecords(streamAddresses) - gvgFamilyRateReadBefore, taxRateReadBefore, userTotalRateReadBefore := s.calculateReadRates(sp, bucketName) + gvgFamilyRateReadBefore, taxRateReadBefore, userTotalRateReadBefore := s.calculateReadRates(bucketName) // seal object s.sealObject(sp, gvg, bucketName, objectName, objectId, checksums) // assertions streamRecordsAfter := s.getStreamRecords(streamAddresses) - gvgFamilyRateReadAfter, taxRateReadAfter, userTotalRateReadAfter := s.calculateReadRatesCurrentTimestamp(sp, bucketName) - gvgFamilyRateStore, gvgRateStore, taxRateStore, userTotalRateStore := s.calculateStorageRatesCurrentTimestamp(sp, bucketName, objectName, payloadSize) + gvgFamilyRateReadAfter, taxRateReadAfter, userTotalRateReadAfter := s.calculateReadRatesCurrentTimestamp(bucketName) + gvgFamilyRateStore, gvgRateStore, taxRateStore, userTotalRateStore := s.calculateStorageRatesCurrentTimestamp(bucketName, objectName, payloadSize) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) s.Require().Equal(streamRecordsAfter.User.LockBalance, sdkmath.ZeroInt()) @@ -1129,29 +1098,25 @@ func (s *PaymentTestSuite) TestStorageBill_SealObject_WithPriceChangeValidatorTa // case: seal object with read price change and storage price change _, _, objectName, objectId, checksums, payloadSize := s.createObject(user, bucketName, false) - priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + priceRes, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, }) s.Require().NoError(err) - // update new price - msgUpdatePrice := &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice.MulInt64(2), - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice.MulInt64(2), - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) + s.T().Log("price", priceRes.GlobalSpStorePrice) + + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice.MulInt64(2), priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(2)) + defer s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice) streamRecordsBefore := s.getStreamRecords(streamAddresses) - gvgFamilyRateReadBefore, taxRateReadBefore, userTotalRateReadBefore := s.calculateReadRates(sp, bucketName) + gvgFamilyRateReadBefore, taxRateReadBefore, userTotalRateReadBefore := s.calculateReadRates(bucketName) // seal object s.sealObject(sp, gvg, bucketName, objectName, objectId, checksums) // assertions streamRecordsAfter := s.getStreamRecords(streamAddresses) - gvgFamilyRateReadAfter, taxRateReadAfter, userTotalRateReadAfter := s.calculateReadRatesCurrentTimestamp(sp, bucketName) - gvgFamilyRateStore, gvgRateStore, taxRateStore, userTotalRateStore := s.calculateStorageRatesCurrentTimestamp(sp, bucketName, objectName, payloadSize) + gvgFamilyRateReadAfter, taxRateReadAfter, userTotalRateReadAfter := s.calculateReadRatesCurrentTimestamp(bucketName) + gvgFamilyRateStore, gvgRateStore, taxRateStore, userTotalRateStore := s.calculateStorageRatesCurrentTimestamp(bucketName, objectName, payloadSize) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) s.Require().Equal(streamRecordsAfter.User.LockBalance, sdkmath.ZeroInt()) @@ -1175,8 +1140,8 @@ func (s *PaymentTestSuite) TestStorageBill_SealObject_WithPriceChangeValidatorTa // assertions streamRecordsAfter = s.getStreamRecords(streamAddresses) - gvgFamilyRateReadAfter, taxRateReadAfter, userTotalRateReadAfter = s.calculateReadRatesCurrentTimestamp(sp, bucketName) - gvgFamilyRateStore, gvgRateStore, taxRateStore, userTotalRateStore = s.calculateStorageRatesCurrentTimestamp(sp, bucketName, objectName, payloadSize*2) + gvgFamilyRateReadAfter, taxRateReadAfter, userTotalRateReadAfter = s.calculateReadRatesCurrentTimestamp(bucketName) + gvgFamilyRateStore, gvgRateStore, taxRateStore, userTotalRateStore = s.calculateStorageRatesCurrentTimestamp(bucketName, objectName, payloadSize*2) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) s.Require().Equal(streamRecordsAfter.User.LockBalance, sdkmath.ZeroInt()) @@ -1185,15 +1150,6 @@ func (s *PaymentTestSuite) TestStorageBill_SealObject_WithPriceChangeValidatorTa s.Require().Equal(streamRecordsAfter.GVG.NetflowRate.Sub(streamRecordsBefore.GVG.NetflowRate), gvgRateStore) s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate), gvgFamilyRateReadAfter.Sub(gvgFamilyRateReadBefore).Add(gvgFamilyRateStore)) s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate), taxRateReadAfter.Sub(taxRateReadBefore).Add(taxRateStore)) - - // revert price - msgUpdatePrice = &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice, - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice, - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) } func (s *PaymentTestSuite) TestStorageBill_RejectSealObject_WithPriceChange() { @@ -1221,18 +1177,15 @@ func (s *PaymentTestSuite) TestStorageBill_RejectSealObject_WithPriceChange() { // case: seal object with read price change and storage price change _, _, objectName, _, _, _ := s.createObject(user, bucketName, false) - priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + priceRes, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, }) s.Require().NoError(err) + s.T().Log("price", priceRes.GlobalSpStorePrice) + // update new price - msgUpdatePrice := &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice.MulInt64(2), - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice.MulInt64(2), - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice.MulInt64(2), priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(2)) + defer s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice) streamRecordsBefore := s.getStreamRecords(streamAddresses) s.Require().True(streamRecordsBefore.User.LockBalance.IsPositive()) @@ -1249,15 +1202,6 @@ func (s *PaymentTestSuite) TestStorageBill_RejectSealObject_WithPriceChange() { s.Require().Equal(streamRecordsAfter.GVG.NetflowRate.Sub(streamRecordsBefore.GVG.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate).Int64(), int64(0)) - - // revert price - msgUpdatePrice = &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice, - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice, - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) } func (s *PaymentTestSuite) TestStorageBill_FullLifecycle() { @@ -1276,11 +1220,11 @@ func (s *PaymentTestSuite) TestStorageBill_FullLifecycle() { user := s.GenAndChargeAccounts(1, 1000000)[0] // query storage price - priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + priceRes, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, }) s.Require().NoError(err) - s.T().Log("price", priceRes.SpStoragePrice) + s.T().Log("price", priceRes.GlobalSpStorePrice) streamAddresses := []string{ user.GetAddr().String(), @@ -1314,13 +1258,8 @@ func (s *PaymentTestSuite) TestStorageBill_FullLifecycle() { s.sealObject(sp, gvg, bucketName3, objectName5, objectId5, checksums5) // update new price - msgUpdatePrice := &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice, - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice.MulInt64(10000), - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice.MulInt64(50), priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(10000)) + defer s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice) // update params params = s.queryParams() @@ -1376,15 +1315,6 @@ func (s *PaymentTestSuite) TestStorageBill_FullLifecycle() { s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.GVG.NetflowRate.Sub(streamRecordsBefore.GVG.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate).Int64(), int64(0)) - - // revert price - msgUpdatePrice = &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice, - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice, - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) } // TestStorageBill_CopyObject_WithoutPriceChange @@ -1421,7 +1351,7 @@ func (s *PaymentTestSuite) TestStorageBill_CopyObject_WithoutPriceChange() { // assertions streamRecordsAfter := s.getStreamRecords(streamAddresses) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) - lockFee := s.calculateLockFee(sp, bucketName, objectName, payloadSize) + lockFee := s.calculateLockFee(bucketName, objectName, payloadSize) s.Require().Equal(streamRecordsAfter.User.LockBalance.Sub(streamRecordsBefore.User.LockBalance), lockFee) s.Require().Equal(streamRecordsAfter.User.NetflowRate.Sub(streamRecordsBefore.User.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), int64(0)) @@ -1435,7 +1365,7 @@ func (s *PaymentTestSuite) TestStorageBill_CopyObject_WithoutPriceChange() { streamRecordsAfter = s.getStreamRecords(streamAddresses) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) s.Require().Equal(streamRecordsAfter.User.LockBalance, sdkmath.ZeroInt()) - gvgFamilyRate, gvgRate, taxRate, userTotalRate := s.calculateStorageRates(sp, bucketName, objectName, payloadSize, 0) + gvgFamilyRate, gvgRate, taxRate, userTotalRate := s.calculateStorageRates(bucketName, objectName, payloadSize, 0) s.Require().Equal(streamRecordsAfter.User.NetflowRate.Sub(streamRecordsBefore.User.NetflowRate), userTotalRate.Neg()) s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate), gvgFamilyRate) s.Require().Equal(streamRecordsAfter.GVG.NetflowRate.Sub(streamRecordsBefore.GVG.NetflowRate), gvgRate) @@ -1492,7 +1422,7 @@ func (s *PaymentTestSuite) TestStorageBill_CopyObject_WithPriceChange() { // assertions streamRecordsAfter := s.getStreamRecords(streamAddresses) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) - lockFee := s.calculateLockFee(sp, bucketName, objectName, payloadSize) + lockFee := s.calculateLockFee(bucketName, objectName, payloadSize) s.Require().Equal(streamRecordsAfter.User.LockBalance.Sub(streamRecordsBefore.User.LockBalance), lockFee) s.Require().Equal(streamRecordsAfter.User.NetflowRate.Sub(streamRecordsBefore.User.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), int64(0)) @@ -1506,40 +1436,37 @@ func (s *PaymentTestSuite) TestStorageBill_CopyObject_WithPriceChange() { streamRecordsAfter = s.getStreamRecords(streamAddresses) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) s.Require().Equal(streamRecordsAfter.User.LockBalance, sdkmath.ZeroInt()) - gvgFamilyRate, gvgRate, taxRate, userTotalRate := s.calculateStorageRates(sp, bucketName, objectName, payloadSize, 0) + gvgFamilyRate, gvgRate, taxRate, userTotalRate := s.calculateStorageRates(bucketName, objectName, payloadSize, 0) s.Require().Equal(streamRecordsAfter.User.NetflowRate.Sub(streamRecordsBefore.User.NetflowRate), userTotalRate.Neg()) s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate), gvgFamilyRate) s.Require().Equal(streamRecordsAfter.GVG.NetflowRate.Sub(streamRecordsBefore.GVG.NetflowRate), gvgRate) s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate), taxRate) - priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), + priceRes, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, }) s.Require().NoError(err) + s.T().Log("price", priceRes.GlobalSpStorePrice) + // update new price - msgUpdatePrice := &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: priceRes.SpStoragePrice.ReadPrice, - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: priceRes.SpStoragePrice.StorePrice.MulInt64(1000), - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(1000)) + defer s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice) distBucketName := s.createBucket(sp, user, 0) distObjectName := storagetestutils.GenRandomObjectName() objectIfo, err := s.copyObject(user, sp, bucketName, objectName, distBucketName, distObjectName) s.Require().NoError(err) s.sealObject(sp, gvg, distBucketName, distObjectName, objectIfo.Id, objectIfo.Checksums) + // assertions streamRecordsAfterCopy := s.getStreamRecords(streamAddresses) s.Require().Equal(streamRecordsAfterCopy.User.StaticBalance, sdkmath.ZeroInt()) s.Require().Equal(streamRecordsAfterCopy.User.LockBalance, sdkmath.ZeroInt()) - gvgFamilyRate1, gvgRate1, taxRate1, userTotalRate1 := s.calculateStorageRates(sp, distBucketName, distObjectName, payloadSize, 0) + gvgFamilyRate1, gvgRate1, taxRate1, userTotalRate1 := s.calculateStorageRates(distBucketName, distObjectName, payloadSize, 0) s.Require().Equal(streamRecordsAfterCopy.GVGFamily.NetflowRate.Sub(streamRecordsAfter.GVGFamily.NetflowRate), gvgFamilyRate1) s.Require().Equal(streamRecordsAfterCopy.GVG.NetflowRate.Sub(streamRecordsAfter.GVG.NetflowRate), gvgRate1) s.Require().Equal(streamRecordsAfterCopy.Tax.NetflowRate.Sub(streamRecordsAfter.Tax.NetflowRate), taxRate1) s.Require().Equal(streamRecordsAfterCopy.User.NetflowRate.Sub(streamRecordsAfter.User.NetflowRate).BigInt().String(), userTotalRate1.Neg().BigInt().String()) - } // TestStorageBill_UpdateBucketQuota @@ -1548,8 +1475,7 @@ func (s *PaymentTestSuite) TestStorageBill_UpdateBucketQuota() { ctx := context.Background() sp := s.PickStorageProvider() user := s.GenAndChargeAccounts(1, 10)[0] - // recover price - defer s.SetSPPrice(sp, "12.34", "0") + gvg, found := sp.GetFirstGlobalVirtualGroup() s.Require().True(found) queryFamilyResponse, err := s.Client.GlobalVirtualGroupFamily(ctx, &virtualgrouptypes.QueryGlobalVirtualGroupFamilyRequest{ @@ -1625,17 +1551,10 @@ func (s *PaymentTestSuite) TestStorageBill_UpdateBucketQuota() { return expectedOutFlows[i].ToAddress < expectedOutFlows[j].ToAddress }) s.Require().Equal(expectedOutFlows, userOutFlowsResponse.OutFlows) + // update new price - spPriceRes, _ := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - }) - msgUpdatePrice := &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: spPriceRes.SpStoragePrice.ReadPrice.MulInt64(100), - FreeReadQuota: spPriceRes.SpStoragePrice.FreeReadQuota, - StorePrice: spPriceRes.SpStoragePrice.StorePrice, - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(10000)) + defer s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice) // case: update bucket read quota bucketInfo, err = s.updateBucket(user, bucketName, "", readQuota*2) @@ -1674,14 +1593,9 @@ func (s *PaymentTestSuite) TestStorageBill_UpdateBucketQuota() { return expectedOutFlows[i].ToAddress < expectedOutFlows[j].ToAddress }) s.Require().Equal(expectedOutFlows, userOutFlowsResponse.OutFlows) + // set big read price - msgUpdatePrice = &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: spPriceRes.SpStoragePrice.ReadPrice.MulInt64(1024 * 1024 * 1024), - FreeReadQuota: spPriceRes.SpStoragePrice.FreeReadQuota, - StorePrice: spPriceRes.SpStoragePrice.StorePrice, - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice.MulInt64(1024*1024*1025), priceRes.GlobalSpStorePrice.PrimaryStorePrice) chargedReadQuota := readQuota * 1024 * 1024 msgUpdateBucketInfo := storagetypes.NewMsgUpdateBucketInfo( @@ -1695,7 +1609,6 @@ func (s *PaymentTestSuite) TestStorageBill_UpdatePaymentAddress() { var err error ctx := context.Background() sp := s.PickStorageProvider() - defer s.SetSPPrice(sp, "12.34", "0") gvg, found := sp.GetFirstGlobalVirtualGroup() s.Require().True(found) queryFamilyResponse, err := s.Client.GlobalVirtualGroupFamily(ctx, &virtualgrouptypes.QueryGlobalVirtualGroupFamilyRequest{ @@ -1774,17 +1687,10 @@ func (s *PaymentTestSuite) TestStorageBill_UpdatePaymentAddress() { return expectedOutFlows[i].ToAddress < expectedOutFlows[j].ToAddress }) s.Require().Equal(expectedOutFlows, userOutFlowsResponse.OutFlows) + // update new price - spPriceRes, _ := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - }) - msgUpdatePrice := &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: spPriceRes.SpStoragePrice.ReadPrice.MulInt64(100), - FreeReadQuota: spPriceRes.SpStoragePrice.FreeReadQuota, - StorePrice: spPriceRes.SpStoragePrice.StorePrice, - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice.MulInt64(100), priceRes.GlobalSpStorePrice.PrimaryStorePrice) + defer s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice) // case: update bucket paymentAccountAddr bucketInfo, err = s.updateBucket(user, bucketName, paymentAccountAddr, readQuota) @@ -1792,7 +1698,7 @@ func (s *PaymentTestSuite) TestStorageBill_UpdatePaymentAddress() { // check price and rate calculation priceRes, err = s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ - Timestamp: bucketInfo.CreateAt, + Timestamp: 0, }) s.T().Logf("priceRes %s, err: %v", priceRes, err) s.Require().NoError(err) @@ -1826,13 +1732,7 @@ func (s *PaymentTestSuite) TestStorageBill_UpdatePaymentAddress() { s.Require().Equal(expectedOutFlows, userOutFlowsResponse.OutFlows) // set big read price - msgUpdatePrice = &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: spPriceRes.SpStoragePrice.ReadPrice.MulInt64(1024 * 1024 * 1024), - FreeReadQuota: spPriceRes.SpStoragePrice.FreeReadQuota, - StorePrice: spPriceRes.SpStoragePrice.StorePrice, - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice.MulInt64(1024*1024*1024), priceRes.GlobalSpStorePrice.PrimaryStorePrice) chargedReadQuota := readQuota * 1024 * 1024 * 1024 * 1024 msgUpdateBucketInfo := storagetypes.NewMsgUpdateBucketInfo( @@ -1851,8 +1751,6 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket() { var err error ctx := context.Background() primarySP := s.PickStorageProvider() - s.SetSPPrice(primarySP, "1", "1.15") - gvg, found := primarySP.GetFirstGlobalVirtualGroup() s.Require().True(found) queryFamilyResponse, err := s.Client.GlobalVirtualGroupFamily(ctx, &virtualgrouptypes.QueryGlobalVirtualGroupFamilyRequest{ @@ -1862,14 +1760,13 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket() { family := queryFamilyResponse.GlobalVirtualGroupFamily user := s.GenAndChargeAccounts(1, 10)[0] - streamAddresses := []string{ + streamAddresses0 := []string{ user.GetAddr().String(), family.VirtualPaymentAddress, gvg.VirtualPaymentAddress, paymenttypes.ValidatorTaxPoolAddress.String(), } - streamAddresses0 := streamAddresses paymentParams, err := s.Client.PaymentQueryClient.Params(ctx, &paymenttypes.QueryParamsRequest{}) s.T().Logf("paymentParams %s, err: %v", paymentParams, err) s.Require().NoError(err) @@ -1881,13 +1778,13 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket() { s.Require().NoError(err) // create object with none zero payload size - streamRecordsBefore := s.getStreamRecords(streamAddresses) + streamRecordsBefore := s.getStreamRecords(streamAddresses0) _, _, objectName, objectId, checksums, payloadSize := s.createObject(user, bucketName, false) // assertions - streamRecordsAfter := s.getStreamRecords(streamAddresses) + streamRecordsAfter := s.getStreamRecords(streamAddresses0) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) - lockFee := s.calculateLockFee(primarySP, bucketName, objectName, payloadSize) + lockFee := s.calculateLockFee(bucketName, objectName, payloadSize) s.Require().Equal(streamRecordsAfter.User.LockBalance.Sub(streamRecordsBefore.User.LockBalance), lockFee) s.Require().Equal(streamRecordsAfter.User.NetflowRate.Sub(streamRecordsBefore.User.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), int64(0)) @@ -1898,8 +1795,8 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket() { s.sealObject(primarySP, gvg, bucketName, objectName, objectId, checksums) // assertions - streamRecordsAfter = s.getStreamRecords(streamAddresses) - gvgFamilyRate, gvgRate, taxRate, userTotalRate := s.calculateStorageRates(primarySP, bucketName, objectName, payloadSize, 0) + streamRecordsAfter = s.getStreamRecords(streamAddresses0) + gvgFamilyRate, gvgRate, taxRate, userTotalRate := s.calculateStorageRates(bucketName, objectName, payloadSize, 0) s.T().Logf("gvgFamilyRate: %v, gvgRate: %v, taxRate: %v, userTotalRate: %v", gvgFamilyRate, gvgRate, taxRate, userTotalRate) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) s.Require().Equal(streamRecordsAfter.User.LockBalance, sdkmath.ZeroInt()) @@ -1908,9 +1805,19 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket() { s.Require().Equal(streamRecordsAfter.GVG.NetflowRate.Sub(streamRecordsBefore.GVG.NetflowRate), gvgRate) s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate), taxRate) taxRate0 := taxRate + dstPrimarySP := s.CreateNewStorageProvider() - s.SetSPPrice(dstPrimarySP, "2", "1.45") + // update price + priceRes, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, + }) + s.Require().NoError(err) + s.T().Log("price", priceRes.GlobalSpStorePrice) + + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice.MulInt64(2), priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(10)) + defer s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice) + _, secondarySPIDs := s.GetSecondarySP(dstPrimarySP, primarySP) gvgID, _ := s.BaseSuite.CreateGlobalVirtualGroup(dstPrimarySP, 0, secondarySPIDs, 1) gvgResp, err := s.Client.VirtualGroupQueryClient.GlobalVirtualGroup(context.Background(), &virtualgrouptypes.QueryGlobalVirtualGroupRequest{ @@ -1924,33 +1831,35 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket() { FamilyId: dstGVG.FamilyId, }) s.Require().NoError(err) - family = queryFamilyResponse.GlobalVirtualGroupFamily - streamAddresses = []string{ + dstFamily := queryFamilyResponse.GlobalVirtualGroupFamily + + streamAddresses1 := []string{ user.GetAddr().String(), - family.VirtualPaymentAddress, + dstFamily.VirtualPaymentAddress, dstGVG.VirtualPaymentAddress, paymenttypes.ValidatorTaxPoolAddress.String(), } - fundAddress := primarySP.FundingKey.GetAddr() - streamRecordsBefore = s.getStreamRecords(streamAddresses) + streamRecordsBefore = s.getStreamRecords(streamAddresses1) + fundAddress := primarySP.FundingKey.GetAddr() queryBalanceRequest := banktypes.QueryBalanceRequest{Denom: s.Config.Denom, Address: fundAddress.String()} fundBalanceBefore, err := s.Client.BankQueryClient.Balance(context.Background(), &queryBalanceRequest) s.Require().NoError(err) - // MigrationBucket + // MigrateBucket msgMigrationBucket, msgCompleteMigrationBucket := s.NewMigrateBucket(primarySP, dstPrimarySP, user, bucketName, gvg.FamilyId, dstGVG.FamilyId, bucketInfo.BucketInfo.Id) s.SendTxBlock(user, msgMigrationBucket) s.Require().NoError(err) - // complete MigrationBucket + // complete MigrateBucket s.SendTxBlock(dstPrimarySP.OperatorKey, msgCompleteMigrationBucket) - streamRecordsAfter = s.getStreamRecords(streamAddresses) + + streamRecordsAfter = s.getStreamRecords(streamAddresses1) fundBalanceAfter, err := s.Client.BankQueryClient.Balance(context.Background(), &queryBalanceRequest) s.Require().NoError(err) s.T().Logf("fundBalanceBefore: %v, fundBalanceAfter: %v, diff: %v", fundBalanceBefore, fundBalanceAfter, fundBalanceAfter.Balance.Amount.Sub(fundBalanceBefore.Balance.Amount)) s.Require().True(fundBalanceAfter.Balance.Amount.Sub(fundBalanceBefore.Balance.Amount).GT(sdkmath.NewInt(0)), "migrate sp fund address need settle") - gvgFamilyRate, gvgRate, taxRate, userTotalRate = s.calculateStorageRates(dstPrimarySP, bucketName, objectName, payloadSize, time.Now().Unix()) + gvgFamilyRate, gvgRate, taxRate, userTotalRate = s.calculateStorageRates(bucketName, objectName, payloadSize, time.Now().Unix()) s.T().Logf("gvgFamilyRate: %v, gvgRate: %v, taxRate: %v, userTotalRate: %v", gvgFamilyRate, gvgRate, taxRate, userTotalRate) s.T().Logf("NetflowRate: %v, userTotalRate: %v, actual taxRate diff: %v, expect taxRate diff: %v", streamRecordsAfter.User.NetflowRate.Neg(), userTotalRate.Neg(), streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate), taxRate.Sub(taxRate0)) @@ -1962,39 +1871,46 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket() { s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate), taxRate.Sub(taxRate0)) s.Require().Equal(streamRecordsAfter.User.NetflowRate.Neg(), userTotalRate.Abs()) - s.SetSPPrice(primarySP, "12.3", "100") + // try to migrate again + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice.MulInt64(120), priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(5000)) queryBalanceRequest.Address = dstPrimarySP.FundingKey.GetAddr().String() fundBalanceBefore, err = s.Client.BankQueryClient.Balance(context.Background(), &queryBalanceRequest) s.Require().NoError(err) streamRecordsBefore = s.getStreamRecords(streamAddresses0) - // send msgMigrationBucket - msgMigrationBucket, msgCompleteMigrationBucket = s.NewMigrateBucket(dstPrimarySP, primarySP, user, bucketName, dstGVG.FamilyId, gvg.FamilyId, bucketInfo.BucketInfo.Id) + // send msgMigrateBucket + msgMigrationBucket, msgCompleteMigrationBucket = s.NewMigrateBucket(dstPrimarySP, primarySP, user, bucketName, dstGVG.FamilyId, gvg.FamilyId, bucketInfo.BucketInfo.Id) s.SendTxBlock(user, msgMigrationBucket) - s.Require().NoError(err) - s.reduceBNBBalance(user, s.Validator, sdkmath.NewIntWithDecimal(1, 1)) - s.SendTxBlockWithExpectErrorString(msgCompleteMigrationBucket, primarySP.OperatorKey, "apply stream record changes for user failed") + s.reduceBNBBalance(user, s.Validator, sdkmath.NewIntWithDecimal(1, 1)) - s.SetSPPrice(primarySP, "12.3", "13") - readPrice, primaryPrice, secondaryPrice := s.getPrices(primarySP, time.Now().Unix()) - s.T().Logf("readPrice: %v, primaryPrice: %v,secondaryPrice: %v", readPrice, primaryPrice, secondaryPrice) + s.SendTxBlock(primarySP.OperatorKey, msgCompleteMigrationBucket) + // account will be frozen + streamRecordsAfter = s.getStreamRecords(streamAddresses0) + s.Require().Equal(streamRecordsAfter.User.Status, paymenttypes.STREAM_ACCOUNT_STATUS_FROZEN) + // deposit to the account s.transferBNB(s.Validator, user, sdkmath.NewIntWithDecimal(10000, 18)) + msgDeposit := &paymenttypes.MsgDeposit{ + Creator: user.GetAddr().String(), + To: user.GetAddr().String(), + Amount: sdkmath.NewIntWithDecimal(1000, 18), + } + _ = s.SendTxBlock(user, msgDeposit) + streamRecordsAfter = s.getStreamRecords(streamAddresses0) + s.Require().Equal(streamRecordsAfter.User.Status, paymenttypes.STREAM_ACCOUNT_STATUS_ACTIVE) - s.SendTxBlock(primarySP.OperatorKey, msgCompleteMigrationBucket) streamRecordsAfter = s.getStreamRecords(streamAddresses0) fundBalanceAfter, err = s.Client.BankQueryClient.Balance(context.Background(), &queryBalanceRequest) s.Require().NoError(err) s.T().Logf("fundBalanceBefore: %v, fundBalanceAfter: %v, diff: %v", fundBalanceBefore, fundBalanceAfter, fundBalanceAfter.Balance.Amount.Sub(fundBalanceBefore.Balance.Amount)) s.Require().True(fundBalanceAfter.Balance.Amount.Sub(fundBalanceBefore.Balance.Amount).GT(sdkmath.NewInt(0)), "migrate sp fund address need settle") taxRate1 := taxRate - gvgFamilyRate, gvgRate, taxRate, userTotalRate = s.calculateStorageRates(primarySP, bucketName, objectName, payloadSize, time.Now().Unix()) + gvgFamilyRate, gvgRate, taxRate, userTotalRate = s.calculateStorageRates(bucketName, objectName, payloadSize, time.Now().Unix()) s.T().Logf("gvgFamilyRate: %v, gvgRate: %v, taxRate: %v, userTotalRate: %v", gvgFamilyRate, gvgRate, taxRate, userTotalRate) s.T().Logf("NetflowRate: %v, userTotalRate: %v, actual taxRate diff: %v, expect taxRate diff: %v", streamRecordsAfter.User.NetflowRate.Neg(), userTotalRate.Neg(), streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate), taxRate.Sub(taxRate0)) - s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) s.Require().Equal(streamRecordsAfter.User.LockBalance, sdkmath.ZeroInt()) s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate), gvgFamilyRate) s.Require().Equal(streamRecordsAfter.GVG.NetflowRate.Sub(streamRecordsBefore.GVG.NetflowRate), gvgRate) @@ -2003,12 +1919,10 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket() { s.Require().Equal(streamRecordsAfter.User.NetflowRate.Neg(), userTotalRate.Abs()) } -func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_ThenDiscontinueBucket() { +func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_LockedFee_ThenDiscontinueBucket() { var err error ctx := context.Background() primarySP := s.PickStorageProvider() - s.SetSPPrice(primarySP, "1", "1.15") - gvg, found := primarySP.GetFirstGlobalVirtualGroup() s.Require().True(found) queryFamilyResponse, err := s.Client.GlobalVirtualGroupFamily(ctx, &virtualgrouptypes.QueryGlobalVirtualGroupFamilyRequest{ @@ -2042,7 +1956,7 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_ThenDiscontinueBucket() // assertions streamRecordsAfter := s.getStreamRecords(streamAddresses) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) - lockFee := s.calculateLockFee(primarySP, bucketName, objectName, payloadSize) + lockFee := s.calculateLockFee(bucketName, objectName, payloadSize) s.Require().Equal(streamRecordsAfter.User.LockBalance.Sub(streamRecordsBefore.User.LockBalance), lockFee) s.Require().Equal(streamRecordsAfter.User.NetflowRate.Sub(streamRecordsBefore.User.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), int64(0)) @@ -2054,7 +1968,7 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_ThenDiscontinueBucket() // assertions streamRecordsAfter = s.getStreamRecords(streamAddresses) - gvgFamilyRate, gvgRate, taxRate, userTotalRate := s.calculateStorageRates(primarySP, bucketName, objectName, payloadSize, 0) + gvgFamilyRate, gvgRate, taxRate, userTotalRate := s.calculateStorageRates(bucketName, objectName, payloadSize, 0) s.T().Logf("gvgFamilyRate: %v, gvgRate: %v, taxRate: %v, userTotalRate: %v", gvgFamilyRate, gvgRate, taxRate, userTotalRate) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) s.Require().Equal(streamRecordsAfter.User.LockBalance, sdkmath.ZeroInt()) @@ -2068,7 +1982,16 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_ThenDiscontinueBucket() // create a new object without seal s.createObject(user, bucketName, false) - s.SetSPPrice(dstPrimarySP, "2", "1.45") + // update price after lock + priceRes, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, + }) + s.Require().NoError(err) + s.T().Log("price", priceRes.GlobalSpStorePrice) + + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(10000)) + defer s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice) + _, secondarySPIDs := s.GetSecondarySP(dstPrimarySP, primarySP) gvgID, _ := s.BaseSuite.CreateGlobalVirtualGroup(dstPrimarySP, 0, secondarySPIDs, 1) gvgResp, err := s.Client.VirtualGroupQueryClient.GlobalVirtualGroup(context.Background(), &virtualgrouptypes.QueryGlobalVirtualGroupRequest{ @@ -2108,7 +2031,7 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_ThenDiscontinueBucket() s.Require().NoError(err) s.T().Logf("fundBalanceBefore: %v, fundBalanceAfter: %v, diff: %v", fundBalanceBefore, fundBalanceAfter, fundBalanceAfter.Balance.Amount.Sub(fundBalanceBefore.Balance.Amount)) s.Require().True(fundBalanceAfter.Balance.Amount.Sub(fundBalanceBefore.Balance.Amount).GT(sdkmath.NewInt(0)), "migrate sp fund address need settle") - gvgFamilyRate, gvgRate, taxRate, userTotalRate = s.calculateStorageRates(dstPrimarySP, bucketName, objectName, payloadSize, time.Now().Unix()) + gvgFamilyRate, gvgRate, taxRate, userTotalRate = s.calculateStorageRates(bucketName, objectName, payloadSize, time.Now().Unix()) s.T().Logf("gvgFamilyRate: %v, gvgRate: %v, taxRate: %v, userTotalRate: %v", gvgFamilyRate, gvgRate, taxRate, userTotalRate) s.T().Logf("NetflowRate: %v, userTotalRate: %v, actual taxRate diff: %v, expect taxRate diff: %v", streamRecordsAfter.User.NetflowRate.Neg(), userTotalRate.Neg(), streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate), taxRate.Sub(taxRate0)) @@ -2147,8 +2070,6 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_FrozenAccount_ThenDisco var err error ctx := context.Background() primarySP := s.PickStorageProvider() - s.SetSPPrice(primarySP, "1", "1.15") - gvg, found := primarySP.GetFirstGlobalVirtualGroup() s.Require().True(found) queryFamilyResponse, err := s.Client.GlobalVirtualGroupFamily(ctx, &virtualgrouptypes.QueryGlobalVirtualGroupFamilyRequest{ @@ -2158,7 +2079,6 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_FrozenAccount_ThenDisco s.T().Log("queryFamilyResponse", core.YamlString(queryFamilyResponse)) user := s.GenAndChargeAccounts(1, 10)[0] - bucketChargedReadQuota := uint64(1000) params := s.queryParams() reserveTime := params.VersionedParams.ReserveTime queryGetSpStoragePriceByTimeResp, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ @@ -2168,11 +2088,11 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_FrozenAccount_ThenDisco s.Require().NoError(err) readPrice := queryGetSpStoragePriceByTimeResp.GlobalSpStorePrice.ReadPrice - totalUserRate := readPrice.MulInt(sdkmath.NewIntFromUint64(bucketChargedReadQuota)).TruncateInt() - taxRateParam := params.VersionedParams.ValidatorTaxRate - taxStreamRate := taxRateParam.MulInt(totalUserRate).TruncateInt() - expectedRate := totalUserRate.Add(taxStreamRate) - paymentAccountBNBNeeded := expectedRate.Mul(sdkmath.NewIntFromUint64(reserveTime)) + bucketChargedReadQuota := uint64(1000) + readRate := readPrice.MulInt(sdkmath.NewIntFromUint64(bucketChargedReadQuota)).TruncateInt() + readTaxRate := params.VersionedParams.ValidatorTaxRate.MulInt(readRate).TruncateInt() + readTotalRate := readRate.Add(readTaxRate) + paymentAccountBNBNeeded := readTotalRate.Mul(sdkmath.NewIntFromUint64(reserveTime)) // create payment account and deposit msgCreatePaymentAccount := &paymenttypes.MsgCreatePaymentAccount{ @@ -2183,6 +2103,7 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_FrozenAccount_ThenDisco paymentAccounts, err := s.Client.PaymentQueryClient.PaymentAccountsByOwner(ctx, paymentAccountsReq) s.Require().NoError(err) s.T().Logf("paymentAccounts %s", core.YamlString(paymentAccounts)) + paymentAddr := paymentAccounts.PaymentAccounts[0] s.Require().Lenf(paymentAccounts.PaymentAccounts, 1, "paymentAccounts %s", core.YamlString(paymentAccounts)) msgDeposit := &paymenttypes.MsgDeposit{ @@ -2192,10 +2113,6 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_FrozenAccount_ThenDisco } _ = s.SendTxBlock(user, msgDeposit) - paymentParams, err := s.Client.PaymentQueryClient.Params(ctx, &paymenttypes.QueryParamsRequest{}) - s.T().Logf("paymentParams %s, err: %v", paymentParams, err) - s.Require().NoError(err) - bucketName := "ch" + storagetestutils.GenRandomBucketName() msgCreateBucket := storagetypes.NewMsgCreateBucket( user.GetAddr(), bucketName, storagetypes.VISIBILITY_TYPE_PRIVATE, primarySP.OperatorKey.GetAddr(), @@ -2235,10 +2152,21 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_FrozenAccount_ThenDisco // check auto settle paymentAccountStreamRecordAfterAutoSettle := s.getStreamRecord(paymentAddr) s.T().Logf("paymentAccountStreamRecordAfterAutoSettle %s", core.YamlString(paymentAccountStreamRecordAfterAutoSettle)) - s.Require().NotEqual(paymentAccountStreamRecordAfterAutoSettle.Status, paymenttypes.STREAM_ACCOUNT_STATUS_ACTIVE) + s.Require().Equal(paymentAccountStreamRecordAfterAutoSettle.Status, paymenttypes.STREAM_ACCOUNT_STATUS_FROZEN) + s.Require().Equal(paymentAccountStreamRecordAfterAutoSettle.NetflowRate.Int64(), int64(0)) + s.Require().Equal(paymentAccountStreamRecordAfterAutoSettle.FrozenNetflowRate.Int64(), readTotalRate.Neg().Int64()) dstPrimarySP := s.CreateNewStorageProvider() - s.SetSPPrice(dstPrimarySP, "2", "1.45") + // update price + priceRes, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ + Timestamp: 0, + }) + s.Require().NoError(err) + s.T().Log("price", priceRes.GlobalSpStorePrice) + + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice.MulInt64(10), priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(10000)) + defer s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice) + _, secondarySPIDs := s.GetSecondarySP(dstPrimarySP, primarySP) gvgID, _ := s.BaseSuite.CreateGlobalVirtualGroup(dstPrimarySP, 0, secondarySPIDs, 1) gvgResp, err := s.Client.VirtualGroupQueryClient.GlobalVirtualGroup(context.Background(), &virtualgrouptypes.QueryGlobalVirtualGroupRequest{ @@ -2253,15 +2181,16 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_FrozenAccount_ThenDisco }) s.Require().NoError(err) family := queryFamilyResponse.GlobalVirtualGroupFamily + streamAddresses := []string{ paymentAddr, family.VirtualPaymentAddress, dstGVG.VirtualPaymentAddress, paymenttypes.ValidatorTaxPoolAddress.String(), } - fundAddress := primarySP.FundingKey.GetAddr() streamRecordsBefore := s.getStreamRecords(streamAddresses) + fundAddress := primarySP.FundingKey.GetAddr() queryBalanceRequest := banktypes.QueryBalanceRequest{Denom: s.Config.Denom, Address: fundAddress.String()} fundBalanceBefore, err := s.Client.BankQueryClient.Balance(context.Background(), &queryBalanceRequest) s.Require().NoError(err) @@ -2273,21 +2202,38 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_FrozenAccount_ThenDisco // complete MigrateBucket s.SendTxBlock(dstPrimarySP.OperatorKey, msgCompleteMigrateBucket) + + time.Sleep(1 * time.Second) streamRecordsAfter := s.getStreamRecords(streamAddresses) fundBalanceAfter, err := s.Client.BankQueryClient.Balance(context.Background(), &queryBalanceRequest) s.Require().NoError(err) + s.T().Logf("fundBalanceBefore: %v, fundBalanceAfter: %v, diff: %v", fundBalanceBefore, fundBalanceAfter, fundBalanceAfter.Balance.Amount.Sub(fundBalanceBefore.Balance.Amount)) s.Require().True(fundBalanceAfter.Balance.Amount.Sub(fundBalanceBefore.Balance.Amount).GT(sdkmath.NewInt(0)), "migrate sp fund address need settle") - gvgFamilyRate, taxRate, userTotalRate := s.calculateReadRates(dstPrimarySP, bucketName) + + gvgFamilyRate, taxRate, userTotalRate := s.calculateReadRatesCurrentTimestamp(bucketName) s.T().Logf("gvgFamilyRate: %v, taxRate: %v, userTotalRate: %v", gvgFamilyRate, taxRate, userTotalRate) - s.T().Logf("NetflowRate: %v, userTotalRate: %v, actual taxRate diff: %v, expect taxRate diff: %v", streamRecordsAfter.User.NetflowRate.Neg(), userTotalRate.Neg(), streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate), taxRate) + + expectedOutFlows := []paymenttypes.OutFlow{ + {ToAddress: family.VirtualPaymentAddress, Rate: gvgFamilyRate, Status: paymenttypes.OUT_FLOW_STATUS_FROZEN}, + {ToAddress: paymenttypes.ValidatorTaxPoolAddress.String(), Rate: taxRate, Status: paymenttypes.OUT_FLOW_STATUS_FROZEN}, + } + userOutFlowsResponse, err := s.Client.OutFlows(ctx, &paymenttypes.QueryOutFlowsRequest{Account: paymentAddr}) + s.Require().NoError(err) + sort.Slice(userOutFlowsResponse.OutFlows, func(i, j int) bool { + return userOutFlowsResponse.OutFlows[i].ToAddress < userOutFlowsResponse.OutFlows[j].ToAddress + }) + sort.Slice(expectedOutFlows, func(i, j int) bool { + return expectedOutFlows[i].ToAddress < expectedOutFlows[j].ToAddress + }) + s.Require().Equal(expectedOutFlows, userOutFlowsResponse.OutFlows) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) s.Require().Equal(streamRecordsAfter.User.LockBalance, sdkmath.ZeroInt()) - s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate), gvgFamilyRate) - // tax rate diff - s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate), taxRate) + s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), int64(0)) + s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate).Int64(), int64(0)) s.Require().Equal(streamRecordsAfter.User.FrozenNetflowRate.Neg(), userTotalRate.Abs()) + s.Require().Equal(streamRecordsAfter.User.NetflowRate.Neg(), sdkmath.ZeroInt()) // force delete bucket msgDiscontinueBucket := storagetypes.NewMsgDiscontinueBucket(dstPrimarySP.GcKey.GetAddr(), bucketName, "test") @@ -2309,6 +2255,12 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_FrozenAccount_ThenDisco _, err = s.Client.HeadBucket(ctx, &storagetypes.QueryHeadBucketRequest{BucketName: bucketName}) s.Require().ErrorContains(err, "No such bucket") + + // check streams after delete + streamRecordsAfter = s.getStreamRecords(streamAddresses) + s.Require().Equal(streamRecordsAfter.User.FrozenNetflowRate.Neg(), sdkmath.ZeroInt()) + s.Require().Equal(streamRecordsAfter.User.NetflowRate.Neg(), sdkmath.ZeroInt()) + s.Require().Equal(streamRecordsAfter.User.OutFlowCount, uint64(0)) } func (s *PaymentTestSuite) GetSecondarySP(sps ...*core.StorageProvider) ([]*core.StorageProvider, []uint32) { @@ -2333,6 +2285,7 @@ func (s *PaymentTestSuite) GetSecondarySP(sps ...*core.StorageProvider) ([]*core } return secondarySPs, secondarySPIDs } + func (s *PaymentTestSuite) NewMigrateBucket(srcSP, dstSP *core.StorageProvider, user keys.KeyManager, bucketName string, srcID, dstID uint32, bucketID sdkmath.Uint) (*storagetypes.MsgMigrateBucket, *storagetypes.MsgCompleteMigrateBucket) { secondarySPs, _ := s.GetSecondarySP(srcSP, dstSP) @@ -2364,35 +2317,6 @@ func (s *PaymentTestSuite) NewMigrateBucket(srcSP, dstSP *core.StorageProvider, return msgMigrationBucket, msgCompleteMigrationBucket } -func (s *PaymentTestSuite) SetSPPrice(sp *core.StorageProvider, readPrice, storePrice string) { - ctx := context.Background() - - priceRes, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - }) - s.Require().NoError(err) - ReadPrice, err := sdk.NewDecFromStr(readPrice) - s.Require().NoError(err) - StorePrice := priceRes.SpStoragePrice.StorePrice - if storePrice != "0" { - StorePrice, err = sdk.NewDecFromStr(storePrice) - s.Require().NoError(err) - } - - msgUpdatePrice := &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: sp.OperatorKey.GetAddr().String(), - ReadPrice: ReadPrice, - FreeReadQuota: priceRes.SpStoragePrice.FreeReadQuota, - StorePrice: StorePrice, - } - s.SendTxBlock(sp.OperatorKey, msgUpdatePrice) - priceRes, err = s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorKey.GetAddr().String(), - }) - s.Require().NoError(err) - s.T().Logf("priceRes read price: %s, store price: %v", - priceRes.SpStoragePrice.ReadPrice, priceRes.SpStoragePrice.StorePrice) -} // CreatePaymentAccount create new payment account and return latest payment account func (s *PaymentTestSuite) CreatePaymentAccount(user keys.KeyManager, amount, decimal int64) string { diff --git a/x/payment/keeper/storage_fee_charge.go b/x/payment/keeper/storage_fee_charge.go index 6518e82d9..07c22d5cd 100644 --- a/x/payment/keeper/storage_fee_charge.go +++ b/x/payment/keeper/storage_fee_charge.go @@ -64,7 +64,7 @@ func (k Keeper) ApplyUserFlowsList(ctx sdk.Context, userFlowsList []types.UserFl if err != nil { return err } - } else { // frozen status, should be called in end block for stop serving + } else { // frozen status, should be called in end block for stop serving (uncharge fee) or for bucket migration (charge fee) err = k.applyFrozenUserFlows(ctx, userFlows, from, streamRecord) if err != nil { return err @@ -126,15 +126,15 @@ func (k Keeper) applyFrozenUserFlows(ctx sdk.Context, userFlows types.UserFlows, //var frozenRateChanges []types.StreamRecordChange totalActiveRate, totalFrozenRate := sdk.ZeroInt(), sdk.ZeroInt() for _, flowChange := range userFlows.Flows { - outFlow := k.GetOutFlow(ctx, sdk.MustAccAddressFromHex(streamRecord.Account), types.OUT_FLOW_STATUS_FROZEN, sdk.MustAccAddressFromHex(flowChange.ToAddress)) + outFlow := k.GetOutFlow(ctx, sdk.MustAccAddressFromHex(streamRecord.Account), types.OUT_FLOW_STATUS_ACTIVE, sdk.MustAccAddressFromHex(flowChange.ToAddress)) if outFlow != nil { - frozenOutFlows = append(frozenOutFlows, flowChange) - //frozenRateChanges = append(frozenRateChanges, *types.NewDefaultStreamRecordChangeWithAddr(sdk.MustAccAddressFromHex(flowChange.ToAddress)).WithFrozenRateChange(flowChange.Rate)) - totalFrozenRate = totalFrozenRate.Add(flowChange.Rate) - } else { activeOutFlows = append(activeOutFlows, flowChange) activeRateChanges = append(activeRateChanges, *types.NewDefaultStreamRecordChangeWithAddr(sdk.MustAccAddressFromHex(flowChange.ToAddress)).WithRateChange(flowChange.Rate)) totalActiveRate = totalActiveRate.Add(flowChange.Rate) + } else { + frozenOutFlows = append(frozenOutFlows, flowChange) + //frozenRateChanges = append(frozenRateChanges, *types.NewDefaultStreamRecordChangeWithAddr(sdk.MustAccAddressFromHex(flowChange.ToAddress)).WithFrozenRateChange(flowChange.Rate)) + totalFrozenRate = totalFrozenRate.Add(flowChange.Rate) } } streamRecordChange := types.NewDefaultStreamRecordChangeWithAddr(from). @@ -146,7 +146,7 @@ func (k Keeper) applyFrozenUserFlows(ctx sdk.Context, userFlows types.UserFlows, // update flows deltaActiveFlowCount := k.MergeActiveOutFlows(ctx, from, activeOutFlows) // can be negative - deltaFrozenFlowCount := k.MergeFrozenOutFlows(ctx, from, frozenOutFlows) // can be negative + deltaFrozenFlowCount := k.MergeFrozenOutFlows(ctx, from, frozenOutFlows) // can be negative streamRecord.OutFlowCount = uint64(int64(streamRecord.OutFlowCount) + int64(deltaActiveFlowCount) + int64(deltaFrozenFlowCount)) k.SetStreamRecord(ctx, streamRecord) diff --git a/x/sp/keeper/msg_server.go b/x/sp/keeper/msg_server.go index edf9e3a67..e6081f3db 100644 --- a/x/sp/keeper/msg_server.go +++ b/x/sp/keeper/msg_server.go @@ -317,7 +317,7 @@ func (k msgServer) UpdateSpStoragePrice(goCtx context.Context, msg *types.MsgUpd updateTimes := k.GetSpUpdatePriceTimes(ctx, sp.Id) params := k.GetParams(ctx) - if updateTimes+1 >= params.MaxUpdatePriceTimes { + if updateTimes+1 > params.MaxUpdatePriceTimes { return nil, types.ErrStorageProviderPriceUpdateNotAllow } diff --git a/x/sp/keeper/sp_storage_price.go b/x/sp/keeper/sp_storage_price.go index b51473868..500cb55f3 100644 --- a/x/sp/keeper/sp_storage_price.go +++ b/x/sp/keeper/sp_storage_price.go @@ -93,7 +93,7 @@ func (k Keeper) UpdateGlobalSpStorePrice(ctx sdk.Context) error { } price, found := k.GetSpStoragePrice(ctx, sp.Id) if !found { - return fmt.Errorf("cannot find secondaryStorePrice for storage provider %d", sp.Id) + return fmt.Errorf("cannot find price for storage provider %d", sp.Id) } storePrices = append(storePrices, price.StorePrice) readPrices = append(readPrices, price.ReadPrice) diff --git a/x/storage/keeper/payment.go b/x/storage/keeper/payment.go index b2fdd8c7d..fc7c01410 100644 --- a/x/storage/keeper/payment.go +++ b/x/storage/keeper/payment.go @@ -21,11 +21,11 @@ func (k Keeper) ChargeBucketReadFee(ctx sdk.Context, bucketInfo *storagetypes.Bu internalBucketInfo.PriceTime = ctx.BlockTime().Unix() bill, err := k.GetBucketReadBill(ctx, bucketInfo, internalBucketInfo) if err != nil { - return fmt.Errorf("charge bucket read fee failed, get bucket bill failed, bucket: %s, err: %s", bucketInfo.BucketName, err.Error()) + return fmt.Errorf("charge bucket read fee failed, get bucket bill failed: %s %s", bucketInfo.BucketName, err.Error()) } err = k.paymentKeeper.ApplyUserFlowsList(ctx, []types.UserFlows{bill}) if err != nil { - ctx.Logger().Error("charge initial read fee failed", "err", err.Error()) + ctx.Logger().Error("charge initial read fee failed", "bucket", bucketInfo.BucketName, "err", err.Error()) return err } return nil @@ -34,12 +34,12 @@ func (k Keeper) ChargeBucketReadFee(ctx sdk.Context, bucketInfo *storagetypes.Bu func (k Keeper) UnChargeBucketReadFee(ctx sdk.Context, bucketInfo *storagetypes.BucketInfo, internalBucketInfo *storagetypes.InternalBucketInfo) error { if internalBucketInfo.TotalChargeSize > 0 { - return fmt.Errorf("unexpected total store charge size: %d", internalBucketInfo.TotalChargeSize) + return fmt.Errorf("unexpected total store charge size: %s, %d", bucketInfo.BucketName, internalBucketInfo.TotalChargeSize) } bill, err := k.GetBucketReadBill(ctx, bucketInfo, internalBucketInfo) if err != nil { - return fmt.Errorf("uncharge bucket read fee failed, get bucket bill failed, bucket: %s, err: %s", bucketInfo.BucketName, err.Error()) + return fmt.Errorf("uncharge bucket read fee failed, get bucket bill failed: %s %s", bucketInfo.BucketName, err.Error()) } if len(bill.Flows) == 0 { return nil @@ -47,7 +47,7 @@ func (k Keeper) UnChargeBucketReadFee(ctx sdk.Context, bucketInfo *storagetypes. bill.Flows = getNegFlows(bill.Flows) err = k.paymentKeeper.ApplyUserFlowsList(ctx, []types.UserFlows{bill}) if err != nil { - ctx.Logger().Error("uncharge bucket read fee failed", "err", err.Error()) + ctx.Logger().Error("uncharge bucket read fee failed", "bucket", bucketInfo.BucketName, "err", err.Error()) return err } return nil @@ -66,7 +66,7 @@ func (k Keeper) GetBucketReadBill(ctx sdk.Context, bucketInfo *storagetypes.Buck price, err := k.spKeeper.GetGlobalSpStorePriceByTime(ctx, internalBucketInfo.PriceTime) if err != nil { - return userFlows, fmt.Errorf("get storage price failed: %w", err) + return userFlows, fmt.Errorf("get storage price failed: %d %w", internalBucketInfo.PriceTime, err) } // primary sp total rate @@ -81,7 +81,7 @@ func (k Keeper) GetBucketReadBill(ctx sdk.Context, bucketInfo *storagetypes.Buck versionedParams, err := k.paymentKeeper.GetVersionedParamsWithTs(ctx, internalBucketInfo.PriceTime) if err != nil { - return userFlows, fmt.Errorf("failed to get validator tax rate: %w, time: %d", err, internalBucketInfo.PriceTime) + return userFlows, fmt.Errorf("failed to get validator tax rate: %d %w", internalBucketInfo.PriceTime, err) } validatorTaxRate := versionedParams.ValidatorTaxRate.MulInt(primaryTotalFlowRate).TruncateInt() if validatorTaxRate.IsPositive() { @@ -111,7 +111,7 @@ func (k Keeper) LockObjectStoreFee(ctx sdk.Context, primarySpId uint32, bucketIn paymentAddr := sdk.MustAccAddressFromHex(bucketInfo.PaymentAddress) amount, err := k.GetObjectLockFee(ctx, primarySpId, objectInfo.CreateAt, objectInfo.PayloadSize) if err != nil { - return fmt.Errorf("get object store fee rate failed: %w", err) + return fmt.Errorf("get object store fee rate failed: %s %s %w", bucketInfo.BucketName, objectInfo.ObjectName, err) } if ctx.IsCheckTx() { _ = ctx.EventManager().EmitTypedEvents(&types.EventFeePreview{ @@ -124,10 +124,10 @@ func (k Keeper) LockObjectStoreFee(ctx sdk.Context, primarySpId uint32, bucketIn change := types.NewDefaultStreamRecordChangeWithAddr(paymentAddr).WithLockBalanceChange(amount) streamRecord, err := k.paymentKeeper.UpdateStreamRecordByAddr(ctx, change) if err != nil { - return fmt.Errorf("update stream record failed: %w", err) + return fmt.Errorf("update stream record failed: %s %s %w", bucketInfo.BucketName, objectInfo.ObjectName, err) } if streamRecord.StaticBalance.IsNegative() { - return fmt.Errorf("static balance is not enough, lacks %s", streamRecord.StaticBalance.Neg().String()) + return fmt.Errorf("static balance is not enough for %s %s, lacks %s", bucketInfo.BucketName, objectInfo.ObjectName, streamRecord.StaticBalance.Neg().String()) } return nil } @@ -137,13 +137,13 @@ func (k Keeper) UnlockObjectStoreFee(ctx sdk.Context, primarySpId uint32, bucket lockedBalance, err := k.GetObjectLockFee(ctx, primarySpId, objectInfo.CreateAt, objectInfo.PayloadSize) if err != nil { - return fmt.Errorf("get object store fee rate failed: %w", err) + return fmt.Errorf("get object store fee rate failed: %s %s %w", bucketInfo.BucketName, objectInfo.ObjectName, err) } paymentAddr := sdk.MustAccAddressFromHex(bucketInfo.PaymentAddress) change := types.NewDefaultStreamRecordChangeWithAddr(paymentAddr).WithLockBalanceChange(lockedBalance.Neg()) _, err = k.paymentKeeper.UpdateStreamRecordByAddr(ctx, change) if err != nil { - return fmt.Errorf("update stream record failed: %w", err) + return fmt.Errorf("update stream record failed: %s %s %w", bucketInfo.BucketName, objectInfo.ObjectName, err) } return nil } @@ -153,7 +153,7 @@ func (k Keeper) UnlockAndChargeObjectStoreFee(ctx sdk.Context, primarySpId uint3 // unlock store fee err := k.UnlockObjectStoreFee(ctx, primarySpId, bucketInfo, objectInfo) if err != nil { - return fmt.Errorf("unlock store fee failed: %w", err) + return fmt.Errorf("unlock store fee failed: %s %s %w", bucketInfo.BucketName, objectInfo.ObjectName, err) } return k.ChargeObjectStoreFee(ctx, primarySpId, bucketInfo, internalBucketInfo, objectInfo) @@ -191,18 +191,18 @@ func (k Keeper) ChargeObjectStoreFee(ctx sdk.Context, primarySpId uint32, bucket internalBucketInfo *storagetypes.InternalBucketInfo, objectInfo *storagetypes.ObjectInfo) error { chargeSize, err := k.GetObjectChargeSize(ctx, objectInfo.PayloadSize, objectInfo.CreateAt) if err != nil { - return fmt.Errorf("get charge size error: %w", err) + return fmt.Errorf("get charge size failed: %s %s %w", bucketInfo.BucketName, objectInfo.ObjectName, err) } priceChanged, _, _, _, _, err := k.IsPriceChanged(ctx, primarySpId, internalBucketInfo.PriceTime) if err != nil { - return fmt.Errorf("check whether price changed error: %w", err) + return fmt.Errorf("check whether price changed failed: %s %s %w", bucketInfo.BucketName, objectInfo.ObjectName, err) } if !priceChanged { err := k.ChargeViaObjectChange(ctx, bucketInfo, internalBucketInfo, objectInfo, chargeSize, false) if err != nil { - return fmt.Errorf("apply object store bill error: %w", err) + return fmt.Errorf("apply object store bill failed: %s %s %w", bucketInfo.BucketName, objectInfo.ObjectName, err) } return nil } @@ -223,12 +223,12 @@ func (k Keeper) UnChargeObjectStoreFee(ctx sdk.Context, primarySpId uint32, buck internalBucketInfo *storagetypes.InternalBucketInfo, objectInfo *storagetypes.ObjectInfo) error { chargeSize, err := k.GetObjectChargeSize(ctx, objectInfo.PayloadSize, objectInfo.CreateAt) if err != nil { - return fmt.Errorf("get charge size error: %w", err) + return fmt.Errorf("get charge size failed: %s %s %w", bucketInfo.BucketName, objectInfo.ObjectName, err) } err = k.ChargeViaObjectChange(ctx, bucketInfo, internalBucketInfo, objectInfo, chargeSize, true) if err != nil { - return fmt.Errorf("apply object store bill error: %w", err) + return fmt.Errorf("apply object store bill failed: %s %s %w", bucketInfo.BucketName, objectInfo.ObjectName, err) } blockTime := ctx.BlockTime().Unix() @@ -241,7 +241,7 @@ func (k Keeper) UnChargeObjectStoreFee(ctx sdk.Context, primarySpId uint32, buck err = k.ChargeObjectStoreFeeForEarlyDeletion(ctx, bucketInfo, internalBucketInfo, objectInfo, chargeSize, timeToPay) forced, _ := ctx.Value(types.ForceUpdateStreamRecordKey).(bool) // force update in end block if !forced && err != nil { - return fmt.Errorf("fail to pay for early deletion, error: %w", err) + return fmt.Errorf("pay for early deletion failed: %s %s %w", bucketInfo.BucketName, objectInfo.ObjectName, err) } } return nil @@ -258,7 +258,7 @@ func (k Keeper) ChargeObjectStoreFeeForEarlyDeletion(ctx sdk.Context, bucketInfo paymentAddr := sdk.MustAccAddressFromHex(bucketInfo.PaymentAddress) price, err := k.spKeeper.GetGlobalSpStorePriceByTime(ctx, internalBucketInfo.PriceTime) if err != nil { - return fmt.Errorf("get storage price failed: %w", err) + return fmt.Errorf("get storage price failed: %d %w", internalBucketInfo.PriceTime, err) } // primary sp total rate @@ -270,7 +270,7 @@ func (k Keeper) ChargeObjectStoreFeeForEarlyDeletion(ctx sdk.Context, bucketInfo _, err = k.paymentKeeper.UpdateStreamRecordByAddr(ctx, types.NewDefaultStreamRecordChangeWithAddr(sdk.MustAccAddressFromHex(gvgFamily.VirtualPaymentAddress)). WithStaticBalanceChange(primaryTotalFlowRate.MulRaw(timeToPay))) if err != nil { - return fmt.Errorf("fail to pay GVG family: %s", err) + return fmt.Errorf("pay GVG family failed: %s %s %s", bucketInfo.BucketName, objectInfo.ObjectName, err) } } @@ -297,7 +297,7 @@ func (k Keeper) ChargeObjectStoreFeeForEarlyDeletion(ctx sdk.Context, bucketInfo _, err = k.paymentKeeper.UpdateStreamRecordByAddr(ctx, types.NewDefaultStreamRecordChangeWithAddr(sdk.MustAccAddressFromHex(gvg.VirtualPaymentAddress)). WithStaticBalanceChange(secondaryTotalFlowRate.MulRaw(timeToPay))) if err != nil { - return fmt.Errorf("fail to pay GVG: %s", err) + return fmt.Errorf("pay GVG failed: %s %s %s", bucketInfo.BucketName, objectInfo.ObjectName, err) } } @@ -311,7 +311,7 @@ func (k Keeper) ChargeObjectStoreFeeForEarlyDeletion(ctx sdk.Context, bucketInfo _, err = k.paymentKeeper.UpdateStreamRecordByAddr(ctx, types.NewDefaultStreamRecordChangeWithAddr(types.ValidatorTaxPoolAddress). WithStaticBalanceChange(validatorTaxRate.MulRaw(timeToPay))) if err != nil { - return fmt.Errorf("fail to pay validator: %s", err) + return fmt.Errorf("pay validator tax failed: %s %s %s", bucketInfo.BucketName, objectInfo.ObjectName, err) } } @@ -319,7 +319,7 @@ func (k Keeper) ChargeObjectStoreFeeForEarlyDeletion(ctx sdk.Context, bucketInfo _, err = k.paymentKeeper.UpdateStreamRecordByAddr(ctx, types.NewDefaultStreamRecordChangeWithAddr(paymentAddr). WithStaticBalanceChange(total.Neg())) if err != nil { - return fmt.Errorf("fail to substrct from payment account: %s", err) + return fmt.Errorf("substrct from payment account failed: %s %s %s", bucketInfo.BucketName, objectInfo.ObjectName, err) } return nil @@ -336,19 +336,19 @@ func (k Keeper) ChargeViaBucketChange(ctx sdk.Context, bucketInfo *storagetypes. } // change bucket internal info if err = changeFunc(bucketInfo, internalBucketInfo); err != nil { - return errors.Wrapf(err, "change bucket internal info failed") + return errors.Wrapf(err, "change bucket internal info failed: %s", bucketInfo.BucketName) } // calculate new bill internalBucketInfo.PriceTime = ctx.BlockTime().Unix() newBill, err := k.GetBucketReadStoreBill(ctx, bucketInfo, internalBucketInfo) if err != nil { - return fmt.Errorf("get new bucket bill failed: %w", err) + return fmt.Errorf("get new bucket bill failed: %s %w", bucketInfo.BucketName, err) } // charge according to bill change err = k.ApplyBillChanges(ctx, prevBill, newBill) if err != nil { - ctx.Logger().Error("charge via bucket change failed", "err", err.Error()) + ctx.Logger().Error("charge via bucket change failed", "bucket", bucketInfo.BucketName, "err", err.Error()) return err } return nil @@ -367,7 +367,7 @@ func (k Keeper) ChargeViaObjectChange(ctx sdk.Context, bucketInfo *storagetypes. price, err := k.spKeeper.GetGlobalSpStorePriceByTime(ctx, internalBucketInfo.PriceTime) if err != nil { - return fmt.Errorf("get storage price failed: %w", err) + return fmt.Errorf("get storage price failed: %d %w", internalBucketInfo.PriceTime, err) } var lvg *storagetypes.LocalVirtualGroup @@ -404,7 +404,8 @@ func (k Keeper) ChargeViaObjectChange(ctx sdk.Context, bucketInfo *storagetypes. userFlows.Flows = append(userFlows.Flows, newOutFlows...) err = k.paymentKeeper.ApplyUserFlowsList(ctx, []types.UserFlows{userFlows}) if err != nil { - ctx.Logger().Error("charge object store fee failed", "err", err.Error()) + ctx.Logger().Error("charge object store fee failed", "bucket", bucketInfo.BucketName, + "object", objectInfo.ObjectName, "err", err.Error()) return err } @@ -462,7 +463,7 @@ func (k Keeper) GetBucketReadStoreBill(ctx sdk.Context, bucketInfo *storagetypes price, err := k.spKeeper.GetGlobalSpStorePriceByTime(ctx, internalBucketInfo.PriceTime) if err != nil { - return userFlows, fmt.Errorf("get storage price failed: %w", err) + return userFlows, fmt.Errorf("get storage price failed: %d %w", internalBucketInfo.PriceTime, err) } primaryReadFlowRate := price.ReadPrice.MulInt(sdkmath.NewIntFromUint64(bucketInfo.ChargedReadQuota)).TruncateInt() @@ -475,7 +476,7 @@ func (k Keeper) GetBucketReadStoreBill(ctx sdk.Context, bucketInfo *storagetypes versionedParams, err := k.paymentKeeper.GetVersionedParamsWithTs(ctx, internalBucketInfo.PriceTime) if err != nil { - return userFlows, fmt.Errorf("failed to get validator tax rate: %w, time: %d", err, internalBucketInfo.PriceTime) + return userFlows, fmt.Errorf("failed to get validator tax rate: %d %w", internalBucketInfo.PriceTime, err) } validatorTaxReadFlowRate := versionedParams.ValidatorTaxRate.MulInt(primaryReadFlowRate).TruncateInt() if validatorTaxReadFlowRate.IsPositive() { @@ -505,12 +506,12 @@ func (k Keeper) UnChargeBucketReadStoreFee(ctx sdk.Context, bucketInfo *storaget ctx = ctx.WithValue(types.ForceUpdateStreamRecordKey, true) // used for bucket migration bill, err := k.GetBucketReadStoreBill(ctx, bucketInfo, internalBucketInfo) if err != nil { - return fmt.Errorf("get bucket bill failed, bucket: %s, err: %s", bucketInfo.BucketName, err.Error()) + return fmt.Errorf("get bucket bill failed: %s %s", bucketInfo.BucketName, err.Error()) } bill.Flows = getNegFlows(bill.Flows) err = k.paymentKeeper.ApplyUserFlowsList(ctx, []types.UserFlows{bill}) if err != nil { - return fmt.Errorf("apply user flows list failed: %w", err) + return fmt.Errorf("apply user flows list failed: %s %w", bucketInfo.BucketName, err) } return nil } @@ -521,11 +522,11 @@ func (k Keeper) ChargeBucketReadStoreFee(ctx sdk.Context, bucketInfo *storagetyp internalBucketInfo.PriceTime = ctx.BlockTime().Unix() bill, err := k.GetBucketReadStoreBill(ctx, bucketInfo, internalBucketInfo) if err != nil { - return fmt.Errorf("get bucket bill failed, bucket: %s, err: %s", bucketInfo.BucketName, err.Error()) + return fmt.Errorf("get bucket bill failed: %s %s", bucketInfo.BucketName, err.Error()) } err = k.paymentKeeper.ApplyUserFlowsList(ctx, []types.UserFlows{bill}) if err != nil { - return fmt.Errorf("apply user flows list failed: %w", err) + return fmt.Errorf("apply user flows list failed: %s %w", bucketInfo.BucketName, err) } return nil } @@ -550,11 +551,11 @@ func getNegFlows(flows []types.OutFlow) (negFlows []types.OutFlow) { func (k Keeper) GetObjectLockFee(ctx sdk.Context, primarySpId uint32, priceTime int64, payloadSize uint64) (amount sdkmath.Int, err error) { price, err := k.spKeeper.GetGlobalSpStorePriceByTime(ctx, priceTime) if err != nil { - return amount, fmt.Errorf("get store price failed: %w", err) + return amount, fmt.Errorf("get store price failed: %d %w", priceTime, err) } chargeSize, err := k.GetObjectChargeSize(ctx, payloadSize, priceTime) if err != nil { - return amount, fmt.Errorf("get charge size error: %w", err) + return amount, fmt.Errorf("get charge size failed: %d %w", priceTime, err) } primaryRate := price.PrimaryStorePrice.MulInt(sdkmath.NewIntFromUint64(chargeSize)).TruncateInt() @@ -577,7 +578,7 @@ func (k Keeper) GetObjectLockFee(ctx sdk.Context, primarySpId uint32, priceTime func (k Keeper) GetObjectChargeSize(ctx sdk.Context, payloadSize uint64, ts int64) (size uint64, err error) { params, err := k.GetVersionedParamsWithTs(ctx, ts) if err != nil { - return size, fmt.Errorf("get charge size failed, ts:%d, error: %w", ts, err) + return size, fmt.Errorf("get charge size failed: %d %w", ts, err) } minChargeSize := params.MinChargeSize if payloadSize < minChargeSize { From 533b234a8b41ecbc9faa93901eda31f2c3a70a32 Mon Sep 17 00:00:00 2001 From: forcodedancing Date: Wed, 9 Aug 2023 17:47:37 +0800 Subject: [PATCH 04/13] fix e2e tests --- e2e/tests/payment_test.go | 50 +++++++++------------------------- e2e/tests/storage_bill_test.go | 50 +++++++++++++++++----------------- 2 files changed, 38 insertions(+), 62 deletions(-) diff --git a/e2e/tests/payment_test.go b/e2e/tests/payment_test.go index d009b2520..959b9f4f9 100644 --- a/e2e/tests/payment_test.go +++ b/e2e/tests/payment_test.go @@ -960,7 +960,7 @@ func (s *PaymentTestSuite) TestVirtualGroup_Settle() { family := queryFamilyResponse.GlobalVirtualGroupFamily user := s.GenAndChargeAccounts(1, 1000000)[0] - bucketName := s.createBucket(sp, user, 1024) + bucketName := s.createBucket(sp, gvg, user, 1024) _, _, objectName, objectId, checksums, _ := s.createObject(user, bucketName, false) s.sealObject(sp, gvg, bucketName, objectName, objectId, checksums) @@ -1130,7 +1130,7 @@ func (s *PaymentTestSuite) TestDiscontinue_InOneBlock_WithoutPriceChange() { streamRecordsBefore := s.getStreamRecords(streamAddresses) // create bucket - bucketName := s.createBucket(sp, user, 0) + bucketName := s.createBucket(sp, gvg, user, 0) // create & seal objects _, _, objectName1, objectId1, checksums1, _ := s.createObject(user, bucketName, false) @@ -1224,7 +1224,7 @@ func (s *PaymentTestSuite) TestDiscontinue_InOneBlock_WithPriceChange() { s.T().Log("price", priceRes.GlobalSpStorePrice) // create bucket - bucketName := s.createBucket(sp, user, 1200987) + bucketName := s.createBucket(sp, gvg, user, 1200987) // create & seal objects _, _, objectName1, objectId1, checksums1, _ := s.createObject(user, bucketName, false) @@ -1315,7 +1315,7 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithoutPriceChange() { streamRecordsBefore := s.getStreamRecords(streamAddresses) // create bucket - bucketName := s.createBucket(sp, user, 12780) + bucketName := s.createBucket(sp, gvg, user, 12780) // create & seal objects for i := 0; i < 4; i++ { @@ -1412,7 +1412,7 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChange() { s.T().Log("price", priceRes.GlobalSpStorePrice) // create bucket - bucketName := s.createBucket(sp, user, 0) + bucketName := s.createBucket(sp, gvg, user, 0) // create objects for i := 0; i < 2; i++ { @@ -1537,7 +1537,7 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChangeReserveTimeCh s.T().Log("price", priceRes.GlobalSpStorePrice) // create bucket - bucketName := s.createBucketWithGVG(sp, gvg, user, 10200) + bucketName := s.createBucket(sp, gvg, user, 10200) // create objects for i := 0; i < 2; i++ { @@ -1668,7 +1668,7 @@ func (s *PaymentTestSuite) TestDiscontinue_InBlocks_WithPriceChangeReserveTimeCh s.T().Log("price", priceRes.GlobalSpStorePrice) // create bucket - bucketName := s.createBucketWithGVG(sp, gvg, user, 0) + bucketName := s.createBucket(sp, gvg, user, 0) // create objects for i := 0; i < 2; i++ { @@ -1798,7 +1798,7 @@ func (s *PaymentTestSuite) TestDiscontinue_MultiObjects() { streamRecordsBefore := s.getStreamRecords(streamAddresses) // create bucket - bucketName := s.createBucket(sp, user, 0) + bucketName := s.createBucket(sp, gvg, user, 0) objectIds := []sdkmath.Uint{} // create objects @@ -1909,7 +1909,7 @@ func (s *PaymentTestSuite) TestDiscontinue_MultiBuckets() { bucketNames := []string{} // create bucket - bucketName1 := s.createBucket(sp, user, 1023) + bucketName1 := s.createBucket(sp, gvg, user, 1023) bucketNames = append(bucketNames, bucketName1) // create objects @@ -1940,15 +1940,15 @@ func (s *PaymentTestSuite) TestDiscontinue_MultiBuckets() { } // create bucket - bucketName2 := s.createBucket(sp, user, 21023) + bucketName2 := s.createBucket(sp, gvg, user, 21023) bucketNames = append(bucketNames, bucketName2) // create bucket - bucketName3 := s.createBucket(sp, user, 0) + bucketName3 := s.createBucket(sp, gvg, user, 0) bucketNames = append(bucketNames, bucketName3) // create bucket - bucketName4 := s.createBucket(sp, user, 55) + bucketName4 := s.createBucket(sp, gvg, user, 55) bucketNames = append(bucketNames, bucketName4) queryBalanceRequest := banktypes.QueryBalanceRequest{Denom: s.Config.Denom, Address: user.GetAddr().String()} @@ -2336,31 +2336,7 @@ func (s *PaymentTestSuite) createBucketAndObject(sp *core.StorageProvider) (keys return user, bucketName, objectName, queryHeadObjectResponse.ObjectInfo.Id, expectChecksum } -func (s *PaymentTestSuite) createBucket(sp *core.StorageProvider, user keys.KeyManager, readQuota uint64) string { - var err error - gvg, found := sp.GetFirstGlobalVirtualGroup() - s.Require().True(found) - - // CreateBucket - bucketName := "ch" + storagetestutils.GenRandomBucketName() - msgCreateBucket := storagetypes.NewMsgCreateBucket( - user.GetAddr(), bucketName, storagetypes.VISIBILITY_TYPE_PRIVATE, sp.OperatorKey.GetAddr(), - nil, math.MaxUint, nil, readQuota) - msgCreateBucket.PrimarySpApproval.GlobalVirtualGroupFamilyId = gvg.FamilyId - msgCreateBucket.PrimarySpApproval.Sig, err = sp.ApprovalKey.Sign(msgCreateBucket.GetApprovalBytes()) - s.Require().NoError(err) - s.SendTxBlock(user, msgCreateBucket) - - queryHeadBucketRequest := storagetypes.QueryHeadBucketRequest{ - BucketName: bucketName, - } - _, err = s.Client.HeadBucket(context.Background(), &queryHeadBucketRequest) - s.Require().NoError(err) - - return bucketName -} - -func (s *PaymentTestSuite) createBucketWithGVG(sp *core.StorageProvider, gvg *virtualgrouptypes.GlobalVirtualGroup, user keys.KeyManager, readQuota uint64) string { +func (s *PaymentTestSuite) createBucket(sp *core.StorageProvider, gvg *virtualgrouptypes.GlobalVirtualGroup, user keys.KeyManager, readQuota uint64) string { var err error // CreateBucket bucketName := "ch" + storagetestutils.GenRandomBucketName() diff --git a/e2e/tests/storage_bill_test.go b/e2e/tests/storage_bill_test.go index 8068877fc..ac8f523d1 100644 --- a/e2e/tests/storage_bill_test.go +++ b/e2e/tests/storage_bill_test.go @@ -300,7 +300,7 @@ func (s *PaymentTestSuite) TestStorageBill_DeleteObjectBucket_WithoutPriceChange streamRecordsBefore := s.getStreamRecords(streamAddresses) // create bucket - bucketName := s.createBucket(sp, user, 256) + bucketName := s.createBucket(sp, gvg, user, 256) //simulate delete bucket gas msgDeleteBucket := storagetypes.NewMsgDeleteBucket(user.GetAddr(), bucketName) @@ -387,7 +387,7 @@ func (s *PaymentTestSuite) TestStorageBill_DeleteObjectBucket_WithPriceChange() streamRecordsBefore := s.getStreamRecords(streamAddresses) // create bucket - bucketName := s.createBucket(sp, user, 256) + bucketName := s.createBucket(sp, gvg, user, 256) //simulate delete bucket gas msgDeleteBucket := storagetypes.NewMsgDeleteBucket(user.GetAddr(), bucketName) @@ -487,7 +487,7 @@ func (s *PaymentTestSuite) TestStorageBill_DeleteObjectBucket_WithPriceChangeRes streamRecordsBefore := s.getStreamRecords(streamAddresses) // create bucket - bucketName := s.createBucket(sp, user, 256) + bucketName := s.createBucket(sp, gvg, user, 256) //simulate delete bucket gas msgDeleteBucket := storagetypes.NewMsgDeleteBucket(user.GetAddr(), bucketName) @@ -589,7 +589,7 @@ func (s *PaymentTestSuite) TestStorageBill_DeleteObject_WithStoreLessThanReserve reserveTime := params.VersionedParams.ReserveTime // create bucket - bucketName := s.createBucket(sp, user, 256) + bucketName := s.createBucket(sp, gvg, user, 256) // create & seal objects _, _, objectName1, objectId1, checksums1, payloadSize := s.createObject(user, bucketName, false) @@ -655,7 +655,7 @@ func (s *PaymentTestSuite) TestStorageBill_DeleteObject_WithStoreMoreThanReserve s.updateParams(params) // create bucket - bucketName := s.createBucket(sp, user, 256) + bucketName := s.createBucket(sp, gvg, user, 256) // create & seal objects _, _, objectName1, objectId1, checksums1, payloadSize := s.createObject(user, bucketName, false) @@ -741,7 +741,7 @@ func (s *PaymentTestSuite) TestStorageBill_CreateBucket_WithZeroNoneZeroReadQuot params := s.queryParams() // case: create bucket with zero read quota - bucketName := s.createBucket(sp, user, 0) + bucketName := s.createBucket(sp, gvg, user, 0) // bucket created queryHeadBucketRequest := storagetypes.QueryHeadBucketRequest{ @@ -758,7 +758,7 @@ func (s *PaymentTestSuite) TestStorageBill_CreateBucket_WithZeroNoneZeroReadQuot s.Require().Equal(streamRecordsAfter.Tax.NetflowRate, streamRecordsBefore.Tax.NetflowRate) // case: create bucket with none zero read quota - bucketName = s.createBucket(sp, user, 10240) + bucketName = s.createBucket(sp, gvg, user, 10240) // bucket created queryHeadBucketRequest = storagetypes.QueryHeadBucketRequest{ @@ -822,7 +822,7 @@ func (s *PaymentTestSuite) TestStorageBill_CreateObject_WithZeroNoneZeroPayload( paymenttypes.ValidatorTaxPoolAddress.String(), } - bucketName := s.createBucket(sp, user, 0) + bucketName := s.createBucket(sp, gvg, user, 0) // case: create object with zero payload size streamRecordsBefore := s.getStreamRecords(streamAddresses) @@ -875,7 +875,7 @@ func (s *PaymentTestSuite) TestStorageBill_CreateObject_WithReserveTimeValidator paymenttypes.ValidatorTaxPoolAddress.String(), } - bucketName := s.createBucket(sp, user, 0) + bucketName := s.createBucket(sp, gvg, user, 0) // create object with none zero payload size streamRecordsBefore := s.getStreamRecords(streamAddresses) @@ -937,7 +937,7 @@ func (s *PaymentTestSuite) TestStorageBill_CancelCreateObject() { paymenttypes.ValidatorTaxPoolAddress.String(), } - bucketName := s.createBucket(sp, user, 0) + bucketName := s.createBucket(sp, gvg, user, 0) // create object with none zero payload size streamRecordsBefore := s.getStreamRecords(streamAddresses) @@ -986,7 +986,7 @@ func (s *PaymentTestSuite) TestStorageBill_SealObject_WithoutPriceChange() { paymenttypes.ValidatorTaxPoolAddress.String(), } - bucketName := s.createBucket(sp, user, 0) + bucketName := s.createBucket(sp, gvg, user, 0) // create object with none zero payload size streamRecordsBefore := s.getStreamRecords(streamAddresses) @@ -1036,7 +1036,7 @@ func (s *PaymentTestSuite) TestStorageBill_SealObject_WithPriceChange() { paymenttypes.ValidatorTaxPoolAddress.String(), } - bucketName := s.createBucket(sp, user, 102400) + bucketName := s.createBucket(sp, gvg, user, 102400) // case: seal object with read price change and storage price change _, _, objectName, objectId, checksums, payloadSize := s.createObject(user, bucketName, false) @@ -1093,7 +1093,7 @@ func (s *PaymentTestSuite) TestStorageBill_SealObject_WithPriceChangeValidatorTa paymenttypes.ValidatorTaxPoolAddress.String(), } - bucketName := s.createBucket(sp, user, 102400) + bucketName := s.createBucket(sp, gvg, user, 102400) // case: seal object with read price change and storage price change _, _, objectName, objectId, checksums, payloadSize := s.createObject(user, bucketName, false) @@ -1172,7 +1172,7 @@ func (s *PaymentTestSuite) TestStorageBill_RejectSealObject_WithPriceChange() { paymenttypes.ValidatorTaxPoolAddress.String(), } - bucketName := s.createBucket(sp, user, 102400) + bucketName := s.createBucket(sp, gvg, user, 102400) // case: seal object with read price change and storage price change _, _, objectName, _, _, _ := s.createObject(user, bucketName, false) @@ -1235,12 +1235,12 @@ func (s *PaymentTestSuite) TestStorageBill_FullLifecycle() { streamRecordsBefore := s.getStreamRecords(streamAddresses) // full lifecycle - bucketName1 := s.createBucket(sp, user, 0) + bucketName1 := s.createBucket(sp, gvg, user, 0) _, _, objectName1, _, _, _ := s.createObject(user, bucketName1, true) _, _, objectName2, objectId2, checksums2, _ := s.createObject(user, bucketName1, false) s.sealObject(sp, gvg, bucketName1, objectName2, objectId2, checksums2) - bucketName2 := s.createBucket(sp, user, 1024) + bucketName2 := s.createBucket(sp, gvg, user, 1024) _, _, objectName3, objectId3, checksums3, _ := s.createObject(user, bucketName2, false) s.sealObject(sp, gvg, bucketName2, objectName3, objectId3, checksums3) @@ -1253,7 +1253,7 @@ func (s *PaymentTestSuite) TestStorageBill_FullLifecycle() { _, _, objectName4, objectId4, checksums4, _ := s.createObject(user, bucketName2, false) s.sealObject(sp, gvg, bucketName2, objectName4, objectId4, checksums4) - bucketName3 := s.createBucket(sp, user, 1024) + bucketName3 := s.createBucket(sp, gvg, user, 1024) _, _, objectName5, objectId5, checksums5, _ := s.createObject(user, bucketName3, false) s.sealObject(sp, gvg, bucketName3, objectName5, objectId5, checksums5) @@ -1270,7 +1270,7 @@ func (s *PaymentTestSuite) TestStorageBill_FullLifecycle() { _, _, objectName6, objectId6, checksums6, _ := s.createObject(user, bucketName3, false) s.sealObject(sp, gvg, bucketName3, objectName6, objectId6, checksums6) - bucketName4 := s.createBucket(sp, user, 1024) + bucketName4 := s.createBucket(sp, gvg, user, 1024) _, _, objectName7, objectId7, checksums7, _ := s.createObject(user, bucketName4, false) s.sealObject(sp, gvg, bucketName4, objectName7, objectId7, checksums7) @@ -1342,7 +1342,7 @@ func (s *PaymentTestSuite) TestStorageBill_CopyObject_WithoutPriceChange() { s.T().Logf("paymentParams %s, err: %v", paymentParams, err) s.Require().NoError(err) - bucketName := s.createBucket(sp, user, 0) + bucketName := s.createBucket(sp, gvg, user, 0) // create object with none zero payload size streamRecordsBefore := s.getStreamRecords(streamAddresses) @@ -1413,7 +1413,7 @@ func (s *PaymentTestSuite) TestStorageBill_CopyObject_WithPriceChange() { s.T().Logf("paymentParams %s, err: %v", paymentParams, err) s.Require().NoError(err) - bucketName := s.createBucket(sp, user, 0) + bucketName := s.createBucket(sp, gvg, user, 0) // create object with none zero payload size streamRecordsBefore := s.getStreamRecords(streamAddresses) @@ -1452,7 +1452,7 @@ func (s *PaymentTestSuite) TestStorageBill_CopyObject_WithPriceChange() { s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(1000)) defer s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice) - distBucketName := s.createBucket(sp, user, 0) + distBucketName := s.createBucket(sp, gvg, user, 0) distObjectName := storagetestutils.GenRandomObjectName() objectIfo, err := s.copyObject(user, sp, bucketName, objectName, distBucketName, distObjectName) s.Require().NoError(err) @@ -1497,7 +1497,7 @@ func (s *PaymentTestSuite) TestStorageBill_UpdateBucketQuota() { s.Require().NoError(err) // case: create bucket with zero read quota - bucketName := s.createBucket(sp, user, 0) + bucketName := s.createBucket(sp, gvg, user, 0) // bucket created queryHeadBucketRequest := storagetypes.QueryHeadBucketRequest{ @@ -1633,7 +1633,7 @@ func (s *PaymentTestSuite) TestStorageBill_UpdatePaymentAddress() { s.Require().NoError(err) // case: create bucket with zero read quota - bucketName := s.createBucket(sp, user, 0) + bucketName := s.createBucket(sp, gvg, user, 0) // bucket created queryHeadBucketRequest := storagetypes.QueryHeadBucketRequest{ @@ -1771,7 +1771,7 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket() { s.T().Logf("paymentParams %s, err: %v", paymentParams, err) s.Require().NoError(err) - bucketName := s.createBucket(primarySP, user, 0) + bucketName := s.createBucket(primarySP, gvg, user, 0) bucketInfo, err := s.Client.HeadBucket(context.Background(), &storagetypes.QueryHeadBucketRequest{ BucketName: bucketName, }) @@ -1943,7 +1943,7 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_LockedFee_ThenDiscontin s.T().Logf("paymentParams %s, err: %v", paymentParams, err) s.Require().NoError(err) - bucketName := s.createBucket(primarySP, user, 0) + bucketName := s.createBucket(primarySP, gvg, user, 0) bucketInfo, err := s.Client.HeadBucket(context.Background(), &storagetypes.QueryHeadBucketRequest{ BucketName: bucketName, }) From 3a0ab6318873bed7f74460aebe13e219b7781930 Mon Sep 17 00:00:00 2001 From: forcodedancing Date: Thu, 10 Aug 2023 09:04:41 +0800 Subject: [PATCH 05/13] add sp id in events --- x/challenge/abci.go | 1 + x/challenge/keeper/msg_server_submit.go | 1 + 2 files changed, 2 insertions(+) diff --git a/x/challenge/abci.go b/x/challenge/abci.go index 0334c4121..7c9edc5df 100644 --- a/x/challenge/abci.go +++ b/x/challenge/abci.go @@ -118,6 +118,7 @@ func EndBlocker(ctx sdk.Context, keeper k.Keeper) { ChallengeId: challengeId, ObjectId: objectInfo.Id, SegmentIndex: segmentIndex, + SpId: sp.Id, SpOperatorAddress: sp.OperatorAddress, RedundancyIndex: redundancyIndex, ChallengerAddress: "", diff --git a/x/challenge/keeper/msg_server_submit.go b/x/challenge/keeper/msg_server_submit.go index 49f92c669..d42b723f2 100644 --- a/x/challenge/keeper/msg_server_submit.go +++ b/x/challenge/keeper/msg_server_submit.go @@ -96,6 +96,7 @@ func (k msgServer) Submit(goCtx context.Context, msg *types.MsgSubmit) (*types.M ChallengeId: challengeId, ObjectId: objectInfo.Id, SegmentIndex: segmentIndex, + SpId: sp.Id, SpOperatorAddress: spOperator.String(), RedundancyIndex: redundancyIndex, ChallengerAddress: challenger.String(), From 9f6459502a192c2deea31f28013bbc43a4590e9e Mon Sep 17 00:00:00 2001 From: forcodedancing Date: Thu, 10 Aug 2023 09:43:18 +0800 Subject: [PATCH 06/13] fix e2e test --- e2e/tests/sp_test.go | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/e2e/tests/sp_test.go b/e2e/tests/sp_test.go index a28b0f7c3..87afec11b 100644 --- a/e2e/tests/sp_test.go +++ b/e2e/tests/sp_test.go @@ -266,13 +266,15 @@ func (s *StorageProviderTestSuite) CheckGlobalSpStorePrice() { storePrices := make([]sdk.Dec, 0) readPrices := make([]sdk.Dec, 0) for _, sp := range sps.Sps { - spStoragePrice, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ - SpAddr: sp.OperatorAddress, - }) - s.Require().NoError(err) - s.T().Logf("sp: %s, storage price: %s", sp.OperatorAddress, core.YamlString(spStoragePrice.SpStoragePrice)) - storePrices = append(storePrices, spStoragePrice.SpStoragePrice.StorePrice) - readPrices = append(readPrices, spStoragePrice.SpStoragePrice.ReadPrice) + if sp.Status == sptypes.STATUS_IN_SERVICE { + spStoragePrice, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ + SpAddr: sp.OperatorAddress, + }) + s.Require().NoError(err) + s.T().Logf("sp: %s, storage price: %s", sp.OperatorAddress, core.YamlString(spStoragePrice.SpStoragePrice)) + storePrices = append(storePrices, spStoragePrice.SpStoragePrice.StorePrice) + readPrices = append(readPrices, spStoragePrice.SpStoragePrice.ReadPrice) + } } sort.Slice(storePrices, func(i, j int) bool { return storePrices[i].LT(storePrices[j]) }) From 0be796dadc22485370ede537b3fc924362c41396 Mon Sep 17 00:00:00 2001 From: forcodedancing Date: Thu, 10 Aug 2023 09:51:20 +0800 Subject: [PATCH 07/13] include price if sp in maintenance --- e2e/tests/sp_test.go | 2 +- x/sp/keeper/sp_storage_price.go | 15 +++++++-------- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/e2e/tests/sp_test.go b/e2e/tests/sp_test.go index 87afec11b..6640e4e37 100644 --- a/e2e/tests/sp_test.go +++ b/e2e/tests/sp_test.go @@ -266,7 +266,7 @@ func (s *StorageProviderTestSuite) CheckGlobalSpStorePrice() { storePrices := make([]sdk.Dec, 0) readPrices := make([]sdk.Dec, 0) for _, sp := range sps.Sps { - if sp.Status == sptypes.STATUS_IN_SERVICE { + if sp.Status == sptypes.STATUS_IN_SERVICE || sp.Status == sptypes.STATUS_IN_MAINTENANCE { spStoragePrice, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ SpAddr: sp.OperatorAddress, }) diff --git a/x/sp/keeper/sp_storage_price.go b/x/sp/keeper/sp_storage_price.go index 500cb55f3..8bc4b36f2 100644 --- a/x/sp/keeper/sp_storage_price.go +++ b/x/sp/keeper/sp_storage_price.go @@ -88,15 +88,14 @@ func (k Keeper) UpdateGlobalSpStorePrice(ctx sdk.Context) error { storePrices := make([]sdk.Dec, 0) readPrices := make([]sdk.Dec, 0) for _, sp := range sps { - if sp.Status != types.STATUS_IN_SERVICE { - continue + if sp.Status == types.STATUS_IN_SERVICE || sp.Status == types.STATUS_IN_MAINTENANCE { + price, found := k.GetSpStoragePrice(ctx, sp.Id) + if !found { + return fmt.Errorf("cannot find price for storage provider %d", sp.Id) + } + storePrices = append(storePrices, price.StorePrice) + readPrices = append(readPrices, price.ReadPrice) } - price, found := k.GetSpStoragePrice(ctx, sp.Id) - if !found { - return fmt.Errorf("cannot find price for storage provider %d", sp.Id) - } - storePrices = append(storePrices, price.StorePrice) - readPrices = append(readPrices, price.ReadPrice) } l := len(storePrices) if l == 0 { From 2e40403917fdeb91320f02827569a7937cb807bb Mon Sep 17 00:00:00 2001 From: forcodedancing Date: Thu, 10 Aug 2023 15:13:55 -0600 Subject: [PATCH 08/13] refactor codes to update global price in each month --- app/app.go | 3 + deployment/localup/localup.sh | 2 +- e2e/tests/storage_bill_test.go | 153 +++------------- proto/greenfield/sp/params.proto | 2 +- swagger/static/swagger.yaml | 15 +- x/payment/types/price.go | 49 ----- x/payment/types/types.go | 44 +++++ x/sp/abci.go | 31 +++- x/sp/abci_test.go | 212 ++++++++++++++++++++++ x/sp/keeper/msg_server.go | 31 +++- x/sp/keeper/msg_server_test.go | 10 + x/sp/types/params.go | 7 +- x/sp/types/params.pb.go | 2 +- x/storage/keeper/keeper.go | 12 ++ x/storage/keeper/payment.go | 2 - x/storage/types/expected_keepers.go | 1 + x/storage/types/expected_keepers_mocks.go | 15 ++ 17 files changed, 394 insertions(+), 197 deletions(-) delete mode 100644 x/payment/types/price.go create mode 100644 x/sp/abci_test.go diff --git a/app/app.go b/app/app.go index ad3b6d2b4..5649b208e 100644 --- a/app/app.go +++ b/app/app.go @@ -759,6 +759,9 @@ func (app *App) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.R // EndBlocker application updates every end block func (app *App) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { + lastBlockTime := app.GetCheckState().Context().BlockHeader().Time.Unix() + ctx = ctx.WithValue(spmodule.LastBlockTimeKey, lastBlockTime) + resp := app.mm.EndBlock(ctx, req) bankIavl, _ := app.CommitMultiStore().GetCommitStore(sdk.NewKVStoreKey(banktypes.StoreKey)).(*iavl.Store) paymentIavl, _ := app.CommitMultiStore().GetCommitStore(sdk.NewKVStoreKey(paymentmoduletypes.StoreKey)).(*iavl.Store) diff --git a/deployment/localup/localup.sh b/deployment/localup/localup.sh index 88606177c..251be926f 100644 --- a/deployment/localup/localup.sh +++ b/deployment/localup/localup.sh @@ -153,7 +153,7 @@ function generate_genesis() { sed -i -e "s/\"discontinue_confirm_period\": \"604800\"/\"discontinue_confirm_period\": \"5\"/g" ${workspace}/.local/validator${i}/config/genesis.json sed -i -e "s/\"discontinue_deletion_max\": \"100\"/\"discontinue_deletion_max\": \"2\"/g" ${workspace}/.local/validator${i}/config/genesis.json sed -i -e "s/\"voting_period\": \"30s\"/\"voting_period\": \"5s\"/g" ${workspace}/.local/validator${i}/config/genesis.json - sed -i -e "s/\"update_global_price_interval\": \"2592000\"/\"update_global_price_interval\": \"1\"/g" ${workspace}/.local/validator${i}/config/genesis.json + sed -i -e "s/\"update_global_price_interval\": \"0\"/\"update_global_price_interval\": \"1\"/g" ${workspace}/.local/validator${i}/config/genesis.json sed -i -e "s/\"max_update_price_times\": 3/\"max_update_price_times\": 1000000/g" ${workspace}/.local/validator${i}/config/genesis.json #sed -i -e "s/\"community_tax\": \"0.020000000000000000\"/\"community_tax\": \"0\"/g" ${workspace}/.local/validator${i}/config/genesis.json sed -i -e "s/log_level = \"info\"/\log_level= \"debug\"/g" ${workspace}/.local/validator${i}/config/config.toml diff --git a/e2e/tests/storage_bill_test.go b/e2e/tests/storage_bill_test.go index ac8f523d1..3222e98b9 100644 --- a/e2e/tests/storage_bill_test.go +++ b/e2e/tests/storage_bill_test.go @@ -1760,13 +1760,14 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket() { family := queryFamilyResponse.GlobalVirtualGroupFamily user := s.GenAndChargeAccounts(1, 10)[0] - streamAddresses0 := []string{ + streamAddresses := []string{ user.GetAddr().String(), family.VirtualPaymentAddress, gvg.VirtualPaymentAddress, paymenttypes.ValidatorTaxPoolAddress.String(), } + streamAddresses0 := streamAddresses paymentParams, err := s.Client.PaymentQueryClient.Params(ctx, &paymenttypes.QueryParamsRequest{}) s.T().Logf("paymentParams %s, err: %v", paymentParams, err) s.Require().NoError(err) @@ -1778,11 +1779,11 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket() { s.Require().NoError(err) // create object with none zero payload size - streamRecordsBefore := s.getStreamRecords(streamAddresses0) + streamRecordsBefore := s.getStreamRecords(streamAddresses) _, _, objectName, objectId, checksums, payloadSize := s.createObject(user, bucketName, false) // assertions - streamRecordsAfter := s.getStreamRecords(streamAddresses0) + streamRecordsAfter := s.getStreamRecords(streamAddresses) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) lockFee := s.calculateLockFee(bucketName, objectName, payloadSize) s.Require().Equal(streamRecordsAfter.User.LockBalance.Sub(streamRecordsBefore.User.LockBalance), lockFee) @@ -1795,7 +1796,7 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket() { s.sealObject(primarySP, gvg, bucketName, objectName, objectId, checksums) // assertions - streamRecordsAfter = s.getStreamRecords(streamAddresses0) + streamRecordsAfter = s.getStreamRecords(streamAddresses) gvgFamilyRate, gvgRate, taxRate, userTotalRate := s.calculateStorageRates(bucketName, objectName, payloadSize, 0) s.T().Logf("gvgFamilyRate: %v, gvgRate: %v, taxRate: %v, userTotalRate: %v", gvgFamilyRate, gvgRate, taxRate, userTotalRate) s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) @@ -1831,30 +1832,28 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket() { FamilyId: dstGVG.FamilyId, }) s.Require().NoError(err) - dstFamily := queryFamilyResponse.GlobalVirtualGroupFamily - - streamAddresses1 := []string{ + family = queryFamilyResponse.GlobalVirtualGroupFamily + streamAddresses = []string{ user.GetAddr().String(), - dstFamily.VirtualPaymentAddress, + family.VirtualPaymentAddress, dstGVG.VirtualPaymentAddress, paymenttypes.ValidatorTaxPoolAddress.String(), } - streamRecordsBefore = s.getStreamRecords(streamAddresses1) - fundAddress := primarySP.FundingKey.GetAddr() + streamRecordsBefore = s.getStreamRecords(streamAddresses) + queryBalanceRequest := banktypes.QueryBalanceRequest{Denom: s.Config.Denom, Address: fundAddress.String()} fundBalanceBefore, err := s.Client.BankQueryClient.Balance(context.Background(), &queryBalanceRequest) s.Require().NoError(err) - // MigrateBucket + // MigrationBucket msgMigrationBucket, msgCompleteMigrationBucket := s.NewMigrateBucket(primarySP, dstPrimarySP, user, bucketName, gvg.FamilyId, dstGVG.FamilyId, bucketInfo.BucketInfo.Id) s.SendTxBlock(user, msgMigrationBucket) s.Require().NoError(err) - // complete MigrateBucket + // complete MigrationBucket s.SendTxBlock(dstPrimarySP.OperatorKey, msgCompleteMigrationBucket) - - streamRecordsAfter = s.getStreamRecords(streamAddresses1) + streamRecordsAfter = s.getStreamRecords(streamAddresses) fundBalanceAfter, err := s.Client.BankQueryClient.Balance(context.Background(), &queryBalanceRequest) s.Require().NoError(err) s.T().Logf("fundBalanceBefore: %v, fundBalanceAfter: %v, diff: %v", fundBalanceBefore, fundBalanceAfter, fundBalanceAfter.Balance.Amount.Sub(fundBalanceBefore.Balance.Amount)) @@ -1871,36 +1870,29 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket() { s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate), taxRate.Sub(taxRate0)) s.Require().Equal(streamRecordsAfter.User.NetflowRate.Neg(), userTotalRate.Abs()) - // try to migrate again + // set price s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice.MulInt64(120), priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(5000)) queryBalanceRequest.Address = dstPrimarySP.FundingKey.GetAddr().String() fundBalanceBefore, err = s.Client.BankQueryClient.Balance(context.Background(), &queryBalanceRequest) s.Require().NoError(err) streamRecordsBefore = s.getStreamRecords(streamAddresses0) - - // send msgMigrateBucket + // send msgMigrationBucket msgMigrationBucket, msgCompleteMigrationBucket = s.NewMigrateBucket(dstPrimarySP, primarySP, user, bucketName, dstGVG.FamilyId, gvg.FamilyId, bucketInfo.BucketInfo.Id) - s.SendTxBlock(user, msgMigrationBucket) + s.SendTxBlock(user, msgMigrationBucket) + s.Require().NoError(err) s.reduceBNBBalance(user, s.Validator, sdkmath.NewIntWithDecimal(1, 1)) - s.SendTxBlock(primarySP.OperatorKey, msgCompleteMigrationBucket) - // account will be frozen - streamRecordsAfter = s.getStreamRecords(streamAddresses0) - s.Require().Equal(streamRecordsAfter.User.Status, paymenttypes.STREAM_ACCOUNT_STATUS_FROZEN) + s.SendTxBlockWithExpectErrorString(msgCompleteMigrationBucket, primarySP.OperatorKey, "apply stream record changes for user failed") + + s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice.MulInt64(10), priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(10)) + readPrice, primaryPrice, secondaryPrice := s.getPrices(time.Now().Unix()) + s.T().Logf("readPrice: %v, primaryPrice: %v,secondaryPrice: %v", readPrice, primaryPrice, secondaryPrice) - // deposit to the account s.transferBNB(s.Validator, user, sdkmath.NewIntWithDecimal(10000, 18)) - msgDeposit := &paymenttypes.MsgDeposit{ - Creator: user.GetAddr().String(), - To: user.GetAddr().String(), - Amount: sdkmath.NewIntWithDecimal(1000, 18), - } - _ = s.SendTxBlock(user, msgDeposit) - streamRecordsAfter = s.getStreamRecords(streamAddresses0) - s.Require().Equal(streamRecordsAfter.User.Status, paymenttypes.STREAM_ACCOUNT_STATUS_ACTIVE) + s.SendTxBlock(primarySP.OperatorKey, msgCompleteMigrationBucket) streamRecordsAfter = s.getStreamRecords(streamAddresses0) fundBalanceAfter, err = s.Client.BankQueryClient.Balance(context.Background(), &queryBalanceRequest) s.Require().NoError(err) @@ -1911,6 +1903,7 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket() { s.T().Logf("gvgFamilyRate: %v, gvgRate: %v, taxRate: %v, userTotalRate: %v", gvgFamilyRate, gvgRate, taxRate, userTotalRate) s.T().Logf("NetflowRate: %v, userTotalRate: %v, actual taxRate diff: %v, expect taxRate diff: %v", streamRecordsAfter.User.NetflowRate.Neg(), userTotalRate.Neg(), streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate), taxRate.Sub(taxRate0)) + s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) s.Require().Equal(streamRecordsAfter.User.LockBalance, sdkmath.ZeroInt()) s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate), gvgFamilyRate) s.Require().Equal(streamRecordsAfter.GVG.NetflowRate.Sub(streamRecordsBefore.GVG.NetflowRate), gvgRate) @@ -2066,7 +2059,7 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_LockedFee_ThenDiscontin s.Require().ErrorContains(err, "No such bucket") } -func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_FrozenAccount_ThenDiscontinueBucket() { +func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_FrozenAccount_NotAllowed() { var err error ctx := context.Background() primarySP := s.PickStorageProvider() @@ -2157,16 +2150,6 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_FrozenAccount_ThenDisco s.Require().Equal(paymentAccountStreamRecordAfterAutoSettle.FrozenNetflowRate.Int64(), readTotalRate.Neg().Int64()) dstPrimarySP := s.CreateNewStorageProvider() - // update price - priceRes, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ - Timestamp: 0, - }) - s.Require().NoError(err) - s.T().Log("price", priceRes.GlobalSpStorePrice) - - s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice.MulInt64(10), priceRes.GlobalSpStorePrice.PrimaryStorePrice.MulInt64(10000)) - defer s.updateGlobalSpPrice(priceRes.GlobalSpStorePrice.ReadPrice, priceRes.GlobalSpStorePrice.PrimaryStorePrice) - _, secondarySPIDs := s.GetSecondarySP(dstPrimarySP, primarySP) gvgID, _ := s.BaseSuite.CreateGlobalVirtualGroup(dstPrimarySP, 0, secondarySPIDs, 1) gvgResp, err := s.Client.VirtualGroupQueryClient.GlobalVirtualGroup(context.Background(), &virtualgrouptypes.QueryGlobalVirtualGroupRequest{ @@ -2176,91 +2159,9 @@ func (s *PaymentTestSuite) TestStorageBill_MigrateBucket_FrozenAccount_ThenDisco dstGVG := gvgResp.GlobalVirtualGroup s.Require().True(found) - queryFamilyResponse, err = s.Client.GlobalVirtualGroupFamily(ctx, &virtualgrouptypes.QueryGlobalVirtualGroupFamilyRequest{ - FamilyId: dstGVG.FamilyId, - }) - s.Require().NoError(err) - family := queryFamilyResponse.GlobalVirtualGroupFamily - - streamAddresses := []string{ - paymentAddr, - family.VirtualPaymentAddress, - dstGVG.VirtualPaymentAddress, - paymenttypes.ValidatorTaxPoolAddress.String(), - } - streamRecordsBefore := s.getStreamRecords(streamAddresses) - - fundAddress := primarySP.FundingKey.GetAddr() - queryBalanceRequest := banktypes.QueryBalanceRequest{Denom: s.Config.Denom, Address: fundAddress.String()} - fundBalanceBefore, err := s.Client.BankQueryClient.Balance(context.Background(), &queryBalanceRequest) - s.Require().NoError(err) - // MigrateBucket - msgMigrateBucket, msgCompleteMigrateBucket := s.NewMigrateBucket(primarySP, dstPrimarySP, user, bucketName, gvg.FamilyId, dstGVG.FamilyId, bucketInfo.BucketInfo.Id) - s.SendTxBlock(user, msgMigrateBucket) - s.Require().NoError(err) - - // complete MigrateBucket - s.SendTxBlock(dstPrimarySP.OperatorKey, msgCompleteMigrateBucket) - - time.Sleep(1 * time.Second) - streamRecordsAfter := s.getStreamRecords(streamAddresses) - fundBalanceAfter, err := s.Client.BankQueryClient.Balance(context.Background(), &queryBalanceRequest) - s.Require().NoError(err) - - s.T().Logf("fundBalanceBefore: %v, fundBalanceAfter: %v, diff: %v", fundBalanceBefore, fundBalanceAfter, fundBalanceAfter.Balance.Amount.Sub(fundBalanceBefore.Balance.Amount)) - s.Require().True(fundBalanceAfter.Balance.Amount.Sub(fundBalanceBefore.Balance.Amount).GT(sdkmath.NewInt(0)), "migrate sp fund address need settle") - - gvgFamilyRate, taxRate, userTotalRate := s.calculateReadRatesCurrentTimestamp(bucketName) - s.T().Logf("gvgFamilyRate: %v, taxRate: %v, userTotalRate: %v", gvgFamilyRate, taxRate, userTotalRate) - - expectedOutFlows := []paymenttypes.OutFlow{ - {ToAddress: family.VirtualPaymentAddress, Rate: gvgFamilyRate, Status: paymenttypes.OUT_FLOW_STATUS_FROZEN}, - {ToAddress: paymenttypes.ValidatorTaxPoolAddress.String(), Rate: taxRate, Status: paymenttypes.OUT_FLOW_STATUS_FROZEN}, - } - userOutFlowsResponse, err := s.Client.OutFlows(ctx, &paymenttypes.QueryOutFlowsRequest{Account: paymentAddr}) - s.Require().NoError(err) - sort.Slice(userOutFlowsResponse.OutFlows, func(i, j int) bool { - return userOutFlowsResponse.OutFlows[i].ToAddress < userOutFlowsResponse.OutFlows[j].ToAddress - }) - sort.Slice(expectedOutFlows, func(i, j int) bool { - return expectedOutFlows[i].ToAddress < expectedOutFlows[j].ToAddress - }) - s.Require().Equal(expectedOutFlows, userOutFlowsResponse.OutFlows) - - s.Require().Equal(streamRecordsAfter.User.StaticBalance, sdkmath.ZeroInt()) - s.Require().Equal(streamRecordsAfter.User.LockBalance, sdkmath.ZeroInt()) - s.Require().Equal(streamRecordsAfter.GVGFamily.NetflowRate.Sub(streamRecordsBefore.GVGFamily.NetflowRate).Int64(), int64(0)) - s.Require().Equal(streamRecordsAfter.Tax.NetflowRate.Sub(streamRecordsBefore.Tax.NetflowRate).Int64(), int64(0)) - s.Require().Equal(streamRecordsAfter.User.FrozenNetflowRate.Neg(), userTotalRate.Abs()) - s.Require().Equal(streamRecordsAfter.User.NetflowRate.Neg(), sdkmath.ZeroInt()) - - // force delete bucket - msgDiscontinueBucket := storagetypes.NewMsgDiscontinueBucket(dstPrimarySP.GcKey.GetAddr(), bucketName, "test") - txRes := s.SendTxBlock(dstPrimarySP.GcKey, msgDiscontinueBucket) - deleteAt := filterDiscontinueBucketEventFromTx(txRes).DeleteAt - - for { - time.Sleep(200 * time.Millisecond) - statusRes, err := s.TmClient.TmClient.Status(context.Background()) - s.Require().NoError(err) - blockTime := statusRes.SyncInfo.LatestBlockTime.Unix() - - s.T().Logf("current blockTime: %d, delete blockTime: %d", blockTime, deleteAt) - - if blockTime > deleteAt { - break - } - } - - _, err = s.Client.HeadBucket(ctx, &storagetypes.QueryHeadBucketRequest{BucketName: bucketName}) - s.Require().ErrorContains(err, "No such bucket") - - // check streams after delete - streamRecordsAfter = s.getStreamRecords(streamAddresses) - s.Require().Equal(streamRecordsAfter.User.FrozenNetflowRate.Neg(), sdkmath.ZeroInt()) - s.Require().Equal(streamRecordsAfter.User.NetflowRate.Neg(), sdkmath.ZeroInt()) - s.Require().Equal(streamRecordsAfter.User.OutFlowCount, uint64(0)) + msgMigrateBucket, _ := s.NewMigrateBucket(primarySP, dstPrimarySP, user, bucketName, gvg.FamilyId, dstGVG.FamilyId, bucketInfo.BucketInfo.Id) + s.SendTxBlockWithExpectErrorString(msgMigrateBucket, user, "frozen") } func (s *PaymentTestSuite) GetSecondarySP(sps ...*core.StorageProvider) ([]*core.StorageProvider, []uint32) { diff --git a/proto/greenfield/sp/params.proto b/proto/greenfield/sp/params.proto index 491492011..2581ccabe 100644 --- a/proto/greenfield/sp/params.proto +++ b/proto/greenfield/sp/params.proto @@ -31,7 +31,7 @@ message Params { int64 maintenance_duration_quota = 5 [(gogoproto.moretags) = "yaml:\"maintenance_duration_quota\""]; // the number of blocks to be wait for sp to be in maintenance mode again if already requested int64 num_of_lockup_blocks_for_maintenance = 6 [(gogoproto.moretags) = "yaml:\"num_of_lockup_blocks_for_maintenance\""]; - // the time interval to update global storage price + // the time interval to update global storage price, if it is not set then the price will be updated at the first block of each natural month uint64 update_global_price_interval = 7 [(gogoproto.moretags) = "yaml:\"update_global_price_interval\""]; // the max times allowed to update price during an interval uint32 max_update_price_times = 8 [(gogoproto.moretags) = "yaml:\"max_update_price_times\""]; diff --git a/swagger/static/swagger.yaml b/swagger/static/swagger.yaml index 41710c4e9..71fde0f24 100644 --- a/swagger/static/swagger.yaml +++ b/swagger/static/swagger.yaml @@ -1659,7 +1659,10 @@ paths: update_global_price_interval: type: string format: uint64 - title: the time interval to update global storage price + title: >- + the time interval to update global storage price, if it is + not set then the price will be updated at the first block + of each natural month max_update_price_times: type: integer format: int64 @@ -32854,7 +32857,10 @@ definitions: update_global_price_interval: type: string format: uint64 - title: the time interval to update global storage price + title: >- + the time interval to update global storage price, if it is not set + then the price will be updated at the first block of each natural + month max_update_price_times: type: integer format: int64 @@ -32919,7 +32925,10 @@ definitions: update_global_price_interval: type: string format: uint64 - title: the time interval to update global storage price + title: >- + the time interval to update global storage price, if it is not set + then the price will be updated at the first block of each natural + month max_update_price_times: type: integer format: int64 diff --git a/x/payment/types/price.go b/x/payment/types/price.go deleted file mode 100644 index fe2d3b9a2..000000000 --- a/x/payment/types/price.go +++ /dev/null @@ -1,49 +0,0 @@ -package types - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type StreamRecordChange struct { - Addr sdk.AccAddress - RateChange sdkmath.Int - StaticBalanceChange sdkmath.Int - LockBalanceChange sdkmath.Int - FrozenRateChange sdkmath.Int -} - -func NewDefaultStreamRecordChangeWithAddr(addr sdk.AccAddress) *StreamRecordChange { - return &StreamRecordChange{ - Addr: addr, - RateChange: sdkmath.ZeroInt(), - StaticBalanceChange: sdkmath.ZeroInt(), - LockBalanceChange: sdkmath.ZeroInt(), - FrozenRateChange: sdkmath.ZeroInt(), - } -} - -func (change *StreamRecordChange) WithRateChange(rateChange sdkmath.Int) *StreamRecordChange { - change.RateChange = rateChange - return change -} - -func (change *StreamRecordChange) WithStaticBalanceChange(staticBalanceChange sdkmath.Int) *StreamRecordChange { - change.StaticBalanceChange = staticBalanceChange - return change -} - -func (change *StreamRecordChange) WithLockBalanceChange(lockBalanceChange sdkmath.Int) *StreamRecordChange { - change.LockBalanceChange = lockBalanceChange - return change -} - -func (change *StreamRecordChange) WithFrozenRateChange(frozenRateChange sdkmath.Int) *StreamRecordChange { - change.FrozenRateChange = frozenRateChange - return change -} - -type UserFlows struct { - From sdk.AccAddress - Flows []OutFlow -} diff --git a/x/payment/types/types.go b/x/payment/types/types.go index 64bbfa295..92155f4a8 100644 --- a/x/payment/types/types.go +++ b/x/payment/types/types.go @@ -1,6 +1,7 @@ package types import ( + sdkmath "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/address" ) @@ -19,3 +20,46 @@ const ( // GovernanceAddressLackBalanceLabel is the metrics label to notify that the governance account has no enough balance GovernanceAddressLackBalanceLabel = "governance_address_lack_balance" ) + +type StreamRecordChange struct { + Addr sdk.AccAddress + RateChange sdkmath.Int + StaticBalanceChange sdkmath.Int + LockBalanceChange sdkmath.Int + FrozenRateChange sdkmath.Int +} + +func NewDefaultStreamRecordChangeWithAddr(addr sdk.AccAddress) *StreamRecordChange { + return &StreamRecordChange{ + Addr: addr, + RateChange: sdkmath.ZeroInt(), + StaticBalanceChange: sdkmath.ZeroInt(), + LockBalanceChange: sdkmath.ZeroInt(), + FrozenRateChange: sdkmath.ZeroInt(), + } +} + +func (change *StreamRecordChange) WithRateChange(rateChange sdkmath.Int) *StreamRecordChange { + change.RateChange = rateChange + return change +} + +func (change *StreamRecordChange) WithStaticBalanceChange(staticBalanceChange sdkmath.Int) *StreamRecordChange { + change.StaticBalanceChange = staticBalanceChange + return change +} + +func (change *StreamRecordChange) WithLockBalanceChange(lockBalanceChange sdkmath.Int) *StreamRecordChange { + change.LockBalanceChange = lockBalanceChange + return change +} + +func (change *StreamRecordChange) WithFrozenRateChange(frozenRateChange sdkmath.Int) *StreamRecordChange { + change.FrozenRateChange = frozenRateChange + return change +} + +type UserFlows struct { + From sdk.AccAddress + Flows []OutFlow +} diff --git a/x/sp/abci.go b/x/sp/abci.go index a7cda816d..ce38208d8 100644 --- a/x/sp/abci.go +++ b/x/sp/abci.go @@ -1,21 +1,44 @@ package sp import ( + "time" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/bnb-chain/greenfield/x/sp/keeper" "github.com/bnb-chain/greenfield/x/sp/types" ) +// LastBlockTimeKey is the key to record last block's time, which will be set by app +const LastBlockTimeKey = "last_block_time" + func EndBlocker(ctx sdk.Context, k keeper.Keeper) { if ctx.BlockHeight()%types.MaintenanceRecordsGCFrequencyInBlocks == 0 { k.ForceUpdateMaintenanceRecords(ctx) } - blockTime := ctx.BlockTime().Unix() - params := k.GetParams(ctx) - price, err := k.GetGlobalSpStorePriceByTime(ctx, blockTime+1) - if err != nil || blockTime-price.UpdateTimeSec > int64(params.UpdateGlobalPriceInterval) { // no global price yet or need to update + needUpdate := false + price, err := k.GetGlobalSpStorePriceByTime(ctx, ctx.BlockTime().Unix()+1) + if err != nil { // no global price yet + needUpdate = true + } else { + params := k.GetParams(ctx) + if params.UpdateGlobalPriceInterval > 0 { // update based on interval + if ctx.BlockTime().Unix()-price.UpdateTimeSec > int64(params.UpdateGlobalPriceInterval) { + needUpdate = true + } + } else { // update every month + lastBlockTimeUnix := ctx.Value(LastBlockTimeKey).(int64) + if lastBlockTimeUnix != 0 { + lastBlockTime := time.Unix(lastBlockTimeUnix, 0).UTC() + currentBlockTime := ctx.BlockTime().UTC() + if lastBlockTime.Month() != currentBlockTime.Month() { + needUpdate = true + } + } + } + } + if needUpdate { // no global price yet or need to update err = k.UpdateGlobalSpStorePrice(ctx) if err != nil { ctx.Logger().Error("fail to update global sp store price", "err", err) diff --git a/x/sp/abci_test.go b/x/sp/abci_test.go new file mode 100644 index 000000000..a3a5ab529 --- /dev/null +++ b/x/sp/abci_test.go @@ -0,0 +1,212 @@ +package sp_test + +import ( + "testing" + "time" + + "github.com/bnb-chain/greenfield/testutil/sample" + + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec" + storetypes "github.com/cosmos/cosmos-sdk/store/types" + "github.com/cosmos/cosmos-sdk/testutil" + sdk "github.com/cosmos/cosmos-sdk/types" + moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/golang/mock/gomock" + "github.com/stretchr/testify/suite" + + spmodule "github.com/bnb-chain/greenfield/x/sp" + "github.com/bnb-chain/greenfield/x/sp/keeper" + "github.com/bnb-chain/greenfield/x/sp/types" +) + +type TestSuite struct { + suite.Suite + + cdc codec.Codec + spKeeper *keeper.Keeper + + bankKeeper *types.MockBankKeeper + accountKeeper *types.MockAccountKeeper + authzKeeper *types.MockAuthzKeeper + + ctx sdk.Context + queryClient types.QueryClient + msgServer types.MsgServer +} + +func (s *TestSuite) SetupTest() { + encCfg := moduletestutil.MakeTestEncodingConfig(mint.AppModuleBasic{}) + key := storetypes.NewKVStoreKey(types.StoreKey) + testCtx := testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")) + s.ctx = testCtx.Ctx + + ctrl := gomock.NewController(s.T()) + + bankKeeper := types.NewMockBankKeeper(ctrl) + accountKeeper := types.NewMockAccountKeeper(ctrl) + authzKeeper := types.NewMockAuthzKeeper(ctrl) + + s.spKeeper = keeper.NewKeeper( + encCfg.Codec, + key, + accountKeeper, + bankKeeper, + authzKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + + s.cdc = encCfg.Codec + + s.bankKeeper = bankKeeper + s.accountKeeper = accountKeeper + s.authzKeeper = authzKeeper + + err := s.spKeeper.SetParams(s.ctx, types.DefaultParams()) + s.Require().NoError(err) + + queryHelper := baseapp.NewQueryServerTestHelper(testCtx.Ctx, encCfg.InterfaceRegistry) + types.RegisterQueryServer(queryHelper, s.spKeeper) + + s.queryClient = types.NewQueryClient(queryHelper) + s.msgServer = keeper.NewMsgServerImpl(*s.spKeeper) +} + +func TestKeeperTestSuite(t *testing.T) { + suite.Run(t, new(TestSuite)) +} + +func (s *TestSuite) TestEndBlocker_NoGlobalPrice() { + s.ctx = s.ctx.WithBlockTime(time.Now()) + sp := &types.StorageProvider{ + Id: 1, + Status: types.STATUS_IN_SERVICE, + OperatorAddress: sample.RandAccAddress().String(), + } + s.spKeeper.SetStorageProvider(s.ctx, sp) + spPrice := types.SpStoragePrice{ + SpId: 1, + UpdateTimeSec: 1024, + ReadPrice: sdk.NewDecWithPrec(100, 0), + FreeReadQuota: 0, + StorePrice: sdk.NewDecWithPrec(200, 0), + } + s.spKeeper.SetSpStoragePrice(s.ctx, spPrice) + + spmodule.EndBlocker(s.ctx, *s.spKeeper) + + // new global price + globalPrice, err := s.spKeeper.GetGlobalSpStorePriceByTime(s.ctx, s.ctx.BlockTime().Unix()+1) + s.Require().NoError(err) + s.Require().Equal(globalPrice.PrimaryStorePrice, spPrice.StorePrice) + s.Require().Equal(globalPrice.ReadPrice, spPrice.ReadPrice) +} + +func (s *TestSuite) TestEndBlocker_WithUpdateInterval() { + preTime := int64(1691648908) + s.ctx = s.ctx.WithBlockTime(time.Unix(preTime, 0)) + globalPrice := types.GlobalSpStorePrice{ + UpdateTimeSec: 0, + ReadPrice: sdk.NewDecWithPrec(1, 0), + PrimaryStorePrice: sdk.NewDecWithPrec(1, 0), + SecondaryStorePrice: sdk.NewDecWithPrec(12, 2), + } + s.spKeeper.SetGlobalSpStorePrice(s.ctx, globalPrice) + + params := s.spKeeper.GetParams(s.ctx) + params.UpdateGlobalPriceInterval = 100 + _ = s.spKeeper.SetParams(s.ctx, params) + + newTime := preTime + 3 + s.ctx = s.ctx.WithBlockTime(time.Unix(newTime, 0)) + sp := &types.StorageProvider{ + Id: 1, + Status: types.STATUS_IN_SERVICE, + OperatorAddress: sample.RandAccAddress().String(), + } + s.spKeeper.SetStorageProvider(s.ctx, sp) + spPrice := types.SpStoragePrice{ + SpId: 1, + UpdateTimeSec: 1024, + ReadPrice: sdk.NewDecWithPrec(100, 0), + FreeReadQuota: 0, + StorePrice: sdk.NewDecWithPrec(200, 0), + } + s.spKeeper.SetSpStoragePrice(s.ctx, spPrice) + + spmodule.EndBlocker(s.ctx, *s.spKeeper) + // global price will not be updated for not reaching the interval + globalPriceAfter, err := s.spKeeper.GetGlobalSpStorePriceByTime(s.ctx, s.ctx.BlockTime().Unix()) + s.Require().NoError(err) + s.Require().Equal(globalPrice.PrimaryStorePrice, globalPriceAfter.PrimaryStorePrice) + s.Require().Equal(globalPrice.ReadPrice, globalPriceAfter.ReadPrice) + + newTime = preTime + 11 + s.ctx = s.ctx.WithBlockTime(time.Unix(newTime, 0)) + spmodule.EndBlocker(s.ctx, *s.spKeeper) + // new global price + globalPriceAfter, err = s.spKeeper.GetGlobalSpStorePriceByTime(s.ctx, s.ctx.BlockTime().Unix()+1) + s.Require().NoError(err) + s.Require().Equal(globalPriceAfter.PrimaryStorePrice, spPrice.StorePrice) + s.Require().Equal(globalPriceAfter.ReadPrice, spPrice.ReadPrice) +} + +func (s *TestSuite) TestEndBlocker_WithoutUpdateInterval() { + preTime := int64(1691648908) + s.ctx = s.ctx.WithBlockTime(time.Unix(preTime, 0)) + globalPrice := types.GlobalSpStorePrice{ + UpdateTimeSec: 0, + ReadPrice: sdk.NewDecWithPrec(1, 0), + PrimaryStorePrice: sdk.NewDecWithPrec(1, 0), + SecondaryStorePrice: sdk.NewDecWithPrec(12, 2), + } + s.spKeeper.SetGlobalSpStorePrice(s.ctx, globalPrice) + + params := s.spKeeper.GetParams(s.ctx) + params.UpdateGlobalPriceInterval = 0 + _ = s.spKeeper.SetParams(s.ctx, params) + + newTime := preTime + 3 + s.ctx = s.ctx.WithBlockTime(time.Unix(newTime, 0)) + sp := &types.StorageProvider{ + Id: 1, + Status: types.STATUS_IN_SERVICE, + OperatorAddress: sample.RandAccAddress().String(), + } + s.spKeeper.SetStorageProvider(s.ctx, sp) + spPrice := types.SpStoragePrice{ + SpId: 1, + UpdateTimeSec: 1024, + ReadPrice: sdk.NewDecWithPrec(100, 0), + FreeReadQuota: 0, + StorePrice: sdk.NewDecWithPrec(200, 0), + } + s.spKeeper.SetSpStoragePrice(s.ctx, spPrice) + + // in the same month + s.ctx = s.ctx.WithValue(spmodule.LastBlockTimeKey, newTime+1) + s.ctx = s.ctx.WithBlockTime(time.Unix(newTime+2, 0)) + spmodule.EndBlocker(s.ctx, *s.spKeeper) + // global price will not be updated + globalPriceAfter, err := s.spKeeper.GetGlobalSpStorePriceByTime(s.ctx, s.ctx.BlockTime().Unix()) + s.Require().NoError(err) + s.Require().Equal(globalPrice.PrimaryStorePrice, globalPriceAfter.PrimaryStorePrice) + s.Require().Equal(globalPrice.ReadPrice, globalPriceAfter.ReadPrice) + + // a new month + s.ctx = s.ctx.WithValue(spmodule.LastBlockTimeKey, newTime+10) + t := time.Unix(newTime+10, 0).UTC() + year, month, _ := t.Date() + location := t.Location() + nextMonth := time.Date(year, month+1, 1, 0, 0, 0, 0, location) + s.ctx = s.ctx.WithBlockTime(nextMonth) + spmodule.EndBlocker(s.ctx, *s.spKeeper) + // new global price + globalPriceAfter, err = s.spKeeper.GetGlobalSpStorePriceByTime(s.ctx, s.ctx.BlockTime().Unix()+1) + s.Require().NoError(err) + s.Require().Equal(globalPriceAfter.PrimaryStorePrice, spPrice.StorePrice) + s.Require().Equal(globalPriceAfter.ReadPrice, spPrice.ReadPrice) +} diff --git a/x/sp/keeper/msg_server.go b/x/sp/keeper/msg_server.go index e6081f3db..2f46baadc 100644 --- a/x/sp/keeper/msg_server.go +++ b/x/sp/keeper/msg_server.go @@ -3,6 +3,7 @@ package keeper import ( "context" "encoding/hex" + "time" "cosmossdk.io/errors" errorsmod "cosmossdk.io/errors" @@ -152,7 +153,7 @@ func (k msgServer) CreateStorageProvider(goCtx context.Context, msg *types.MsgCr FreeReadQuota: msg.FreeReadQuota, } k.SetSpStoragePrice(ctx, spStoragePrice) - k.SetSpUpdatePriceTimes(ctx, sp.Id, k.GetSpUpdatePriceTimes(ctx, sp.Id)+1) + k.SetSpUpdatePriceTimes(ctx, sp.Id, 1) if err = ctx.EventManager().EmitTypedEvents(&types.EventCreateStorageProvider{ SpId: sp.Id, @@ -315,10 +316,20 @@ func (k msgServer) UpdateSpStoragePrice(goCtx context.Context, msg *types.MsgUpd return nil, types.ErrStorageProviderNotInService } - updateTimes := k.GetSpUpdatePriceTimes(ctx, sp.Id) params := k.GetParams(ctx) - if updateTimes+1 > params.MaxUpdatePriceTimes { - return nil, types.ErrStorageProviderPriceUpdateNotAllow + updateTimes := uint32(0) + if params.UpdateGlobalPriceInterval > 0 { // update price by interval + updateTimes = k.GetSpUpdatePriceTimes(ctx, sp.Id) + if updateTimes+1 > params.MaxUpdatePriceTimes { + return nil, errors.Wrapf(types.ErrStorageProviderPriceUpdateNotAllow, "exceeds the limit %d", params.MaxUpdatePriceTimes) + } + updateTimes++ + } else { // update price by month + blockTime := ctx.BlockTime().UTC() + days := 2 + if IsLastDaysOfTheMonth(blockTime, days) { + return nil, errors.Wrapf(types.ErrStorageProviderPriceUpdateNotAllow, "price cannot be updated in the last %d days of the month", days) + } } current := ctx.BlockTime().Unix() @@ -330,11 +341,21 @@ func (k msgServer) UpdateSpStoragePrice(goCtx context.Context, msg *types.MsgUpd FreeReadQuota: msg.FreeReadQuota, } k.SetSpStoragePrice(ctx, spStorePrice) - k.SetSpUpdatePriceTimes(ctx, sp.Id, updateTimes+1) + if updateTimes > 0 { + k.SetSpUpdatePriceTimes(ctx, sp.Id, updateTimes) + } return &types.MsgUpdateSpStoragePriceResponse{}, nil } +func IsLastDaysOfTheMonth(now time.Time, days int) bool { + year, month, _ := now.Date() + location := now.Location() + nextMonth := time.Date(year, month+1, 1, 0, 0, 0, 0, location) + daysBack := nextMonth.AddDate(0, 0, -1*days) + return now.After(daysBack) +} + func (k msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { if k.GetAuthority() != req.Authority { return nil, errorsmod.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.GetAuthority(), req.Authority) diff --git a/x/sp/keeper/msg_server_test.go b/x/sp/keeper/msg_server_test.go index 05b5c07d6..d854462f1 100644 --- a/x/sp/keeper/msg_server_test.go +++ b/x/sp/keeper/msg_server_test.go @@ -2,6 +2,9 @@ package keeper_test import ( "testing" + "time" + + "github.com/bnb-chain/greenfield/x/sp/keeper" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/testutil" @@ -148,3 +151,10 @@ func (s *KeeperTestSuite) TestMsgCreateStorageProvider() { } } + +func (s *KeeperTestSuite) TestIsLastDaysOfTheMonth() { + s.Require().True(keeper.IsLastDaysOfTheMonth(time.Unix(1693328461, 0), 2)) // 2023-08-30 + s.Require().True(keeper.IsLastDaysOfTheMonth(time.Unix(1693414861, 0), 2)) // 2023-08-31 + s.Require().True(!keeper.IsLastDaysOfTheMonth(time.Unix(1693242061, 0), 2)) // 2023-08-29 + s.Require().True(!keeper.IsLastDaysOfTheMonth(time.Unix(1693587661, 0), 2)) // 2023-09-02 +} diff --git a/x/sp/types/params.go b/x/sp/types/params.go index bdf8ff2e9..059153e0f 100644 --- a/x/sp/types/params.go +++ b/x/sp/types/params.go @@ -23,7 +23,7 @@ const ( // DefaultNumOfLockUpBlocksForMaintenance defines blocks difference which Sp update itself to Maintenance mode is allowed DefaultNumOfLockUpBlocksForMaintenance = 21600 // DefaultUpdateGlobalPriceInterval defines the default time duration for updating global storage price - DefaultUpdateGlobalPriceInterval uint64 = 30 * 24 * 60 * 60 // 30 days + DefaultUpdateGlobalPriceInterval uint64 = 0 // 0 means the global price will be updated at the first day of each month // DefaultMaxUpdatePriceTimes defines the max allowed times to update price for each sp in one interval DefaultMaxUpdatePriceTimes uint32 = 3 ) @@ -207,13 +207,10 @@ func validateLockUpBlocksForMaintenance(i interface{}) error { } func validateUpdateGlobalPriceInterval(i interface{}) error { - v, ok := i.(uint64) + _, ok := i.(uint64) if !ok { return fmt.Errorf("invalid parameter type: %T", i) } - if v == 0 { - return errors.New("UpdateGlobalPriceInterval cannot be zero") - } return nil } diff --git a/x/sp/types/params.pb.go b/x/sp/types/params.pb.go index 409be5ac5..aadf039b1 100644 --- a/x/sp/types/params.pb.go +++ b/x/sp/types/params.pb.go @@ -39,7 +39,7 @@ type Params struct { MaintenanceDurationQuota int64 `protobuf:"varint,5,opt,name=maintenance_duration_quota,json=maintenanceDurationQuota,proto3" json:"maintenance_duration_quota,omitempty" yaml:"maintenance_duration_quota"` // the number of blocks to be wait for sp to be in maintenance mode again if already requested NumOfLockupBlocksForMaintenance int64 `protobuf:"varint,6,opt,name=num_of_lockup_blocks_for_maintenance,json=numOfLockupBlocksForMaintenance,proto3" json:"num_of_lockup_blocks_for_maintenance,omitempty" yaml:"num_of_lockup_blocks_for_maintenance"` - // the time interval to update global storage price + // the time interval to update global storage price, if it is not set then the price will be updated at the first block of each natural month UpdateGlobalPriceInterval uint64 `protobuf:"varint,7,opt,name=update_global_price_interval,json=updateGlobalPriceInterval,proto3" json:"update_global_price_interval,omitempty" yaml:"update_global_price_interval"` // the max times allowed to update price during an interval MaxUpdatePriceTimes uint32 `protobuf:"varint,8,opt,name=max_update_price_times,json=maxUpdatePriceTimes,proto3" json:"max_update_price_times,omitempty" yaml:"max_update_price_times"` diff --git a/x/storage/keeper/keeper.go b/x/storage/keeper/keeper.go index 06dafa83f..5601a2fe5 100644 --- a/x/storage/keeper/keeper.go +++ b/x/storage/keeper/keeper.go @@ -4,6 +4,8 @@ import ( "encoding/binary" "fmt" + paymenttypes "github.com/bnb-chain/greenfield/x/payment/types" + "cosmossdk.io/errors" sdkmath "cosmossdk.io/math" "github.com/cometbft/cometbft/libs/log" @@ -1901,6 +1903,11 @@ func (k Keeper) MigrateBucket(ctx sdk.Context, operator sdk.AccAddress, bucketNa "origin SP status: %s, dst SP status: %s", srcSP.Status.String(), dstSP.Status.String()) } + streamRecord, found := k.paymentKeeper.GetStreamRecord(ctx, sdk.MustAccAddressFromHex(bucketInfo.PaymentAddress)) + if !found || streamRecord.Status == paymenttypes.STREAM_ACCOUNT_STATUS_FROZEN { + return paymenttypes.ErrInvalidStreamAccountStatus.Wrap("stream account is frozen") + } + // check approval if dstPrimarySPApproval.ExpiredHeight < (uint64)(ctx.BlockHeight()) { return types.ErrInvalidApproval.Wrap("dst primary sp approval timeout") @@ -1973,6 +1980,11 @@ func (k Keeper) CompleteMigrateBucket(ctx sdk.Context, operator sdk.AccAddress, return virtualgroupmoduletypes.ErrGVGFamilyNotExist } + streamRecord, found := k.paymentKeeper.GetStreamRecord(ctx, sdk.MustAccAddressFromHex(bucketInfo.PaymentAddress)) + if !found || streamRecord.Status == paymenttypes.STREAM_ACCOUNT_STATUS_FROZEN { + return paymenttypes.ErrInvalidStreamAccountStatus.Wrap("stream account is frozen") + } + sp := k.MustGetPrimarySPForBucket(ctx, bucketInfo) err := k.virtualGroupKeeper.SettleAndDistributeGVGFamily(ctx, sp, srcGvgFamily) diff --git a/x/storage/keeper/payment.go b/x/storage/keeper/payment.go index fc7c01410..b8dd85f81 100644 --- a/x/storage/keeper/payment.go +++ b/x/storage/keeper/payment.go @@ -503,7 +503,6 @@ func (k Keeper) GetBucketReadStoreBill(ctx sdk.Context, bucketInfo *storagetypes func (k Keeper) UnChargeBucketReadStoreFee(ctx sdk.Context, bucketInfo *storagetypes.BucketInfo, internalBucketInfo *storagetypes.InternalBucketInfo) error { - ctx = ctx.WithValue(types.ForceUpdateStreamRecordKey, true) // used for bucket migration bill, err := k.GetBucketReadStoreBill(ctx, bucketInfo, internalBucketInfo) if err != nil { return fmt.Errorf("get bucket bill failed: %s %s", bucketInfo.BucketName, err.Error()) @@ -518,7 +517,6 @@ func (k Keeper) UnChargeBucketReadStoreFee(ctx sdk.Context, bucketInfo *storaget func (k Keeper) ChargeBucketReadStoreFee(ctx sdk.Context, bucketInfo *storagetypes.BucketInfo, internalBucketInfo *storagetypes.InternalBucketInfo) error { - ctx = ctx.WithValue(types.ForceUpdateStreamRecordKey, true) // used for bucket migration internalBucketInfo.PriceTime = ctx.BlockTime().Unix() bill, err := k.GetBucketReadStoreBill(ctx, bucketInfo, internalBucketInfo) if err != nil { diff --git a/x/storage/types/expected_keepers.go b/x/storage/types/expected_keepers.go index 90f2ac6d0..07db69444 100644 --- a/x/storage/types/expected_keepers.go +++ b/x/storage/types/expected_keepers.go @@ -47,6 +47,7 @@ type PaymentKeeper interface { IsPaymentAccountOwner(ctx sdk.Context, addr, owner sdk.AccAddress) bool ApplyUserFlowsList(ctx sdk.Context, userFlows []paymenttypes.UserFlows) (err error) UpdateStreamRecordByAddr(ctx sdk.Context, change *paymenttypes.StreamRecordChange) (ret *paymenttypes.StreamRecord, err error) + GetStreamRecord(ctx sdk.Context, account sdk.AccAddress) (ret *paymenttypes.StreamRecord, found bool) } type PermissionKeeper interface { diff --git a/x/storage/types/expected_keepers_mocks.go b/x/storage/types/expected_keepers_mocks.go index 0232c9816..0ae019313 100644 --- a/x/storage/types/expected_keepers_mocks.go +++ b/x/storage/types/expected_keepers_mocks.go @@ -300,6 +300,21 @@ func (mr *MockPaymentKeeperMockRecorder) ApplyUserFlowsList(ctx, userFlows inter return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ApplyUserFlowsList", reflect.TypeOf((*MockPaymentKeeper)(nil).ApplyUserFlowsList), ctx, userFlows) } +// GetStreamRecord mocks base method. +func (m *MockPaymentKeeper) GetStreamRecord(ctx types3.Context, account types3.AccAddress) (*types.StreamRecord, bool) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetStreamRecord", ctx, account) + ret0, _ := ret[0].(*types.StreamRecord) + ret1, _ := ret[1].(bool) + return ret0, ret1 +} + +// GetStreamRecord indicates an expected call of GetStreamRecord. +func (mr *MockPaymentKeeperMockRecorder) GetStreamRecord(ctx, account interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStreamRecord", reflect.TypeOf((*MockPaymentKeeper)(nil).GetStreamRecord), ctx, account) +} + // GetVersionedParamsWithTs mocks base method. func (m *MockPaymentKeeper) GetVersionedParamsWithTs(ctx types3.Context, time int64) (types.VersionedParams, error) { m.ctrl.T.Helper() From 4bbf20a7a58b0c609c587483b5f99a31a4a69c60 Mon Sep 17 00:00:00 2001 From: forcodedancing Date: Thu, 10 Aug 2023 16:39:48 -0600 Subject: [PATCH 09/13] refine sp parameters --- deployment/localup/localup.sh | 2 +- e2e/tests/sp_test.go | 57 +++++++++---------- proto/greenfield/sp/params.proto | 4 +- swagger/static/swagger.yaml | 18 ++++-- x/sp/abci.go | 1 - x/sp/keeper/msg_server.go | 17 +----- x/sp/keeper/msg_server_test.go | 8 +-- x/sp/keeper/sp_storage_price.go | 33 ----------- x/sp/types/errors.go | 2 +- x/sp/types/keys.go | 21 ++++--- x/sp/types/params.go | 23 ++++---- x/sp/types/params.pb.go | 98 ++++++++++++++++---------------- 12 files changed, 119 insertions(+), 165 deletions(-) diff --git a/deployment/localup/localup.sh b/deployment/localup/localup.sh index 251be926f..ddf2d2006 100644 --- a/deployment/localup/localup.sh +++ b/deployment/localup/localup.sh @@ -154,7 +154,7 @@ function generate_genesis() { sed -i -e "s/\"discontinue_deletion_max\": \"100\"/\"discontinue_deletion_max\": \"2\"/g" ${workspace}/.local/validator${i}/config/genesis.json sed -i -e "s/\"voting_period\": \"30s\"/\"voting_period\": \"5s\"/g" ${workspace}/.local/validator${i}/config/genesis.json sed -i -e "s/\"update_global_price_interval\": \"0\"/\"update_global_price_interval\": \"1\"/g" ${workspace}/.local/validator${i}/config/genesis.json - sed -i -e "s/\"max_update_price_times\": 3/\"max_update_price_times\": 1000000/g" ${workspace}/.local/validator${i}/config/genesis.json + sed -i -e "s/\"update_price_disallowed_days\": 2/\"update_price_disallowed_days\": 0/g" ${workspace}/.local/validator${i}/config/genesis.json #sed -i -e "s/\"community_tax\": \"0.020000000000000000\"/\"community_tax\": \"0\"/g" ${workspace}/.local/validator${i}/config/genesis.json sed -i -e "s/log_level = \"info\"/\log_level= \"debug\"/g" ${workspace}/.local/validator${i}/config/config.toml done diff --git a/e2e/tests/sp_test.go b/e2e/tests/sp_test.go index 6640e4e37..4703cfeb4 100644 --- a/e2e/tests/sp_test.go +++ b/e2e/tests/sp_test.go @@ -161,19 +161,17 @@ func (s *StorageProviderTestSuite) TestUpdateSpStoragePrice() { ctx := context.Background() defer s.revertParams() - // update params - params := s.queryParams() - params.UpdateGlobalPriceInterval = 10 - params.MaxUpdatePriceTimes = 2 - s.updateParams(params) - // query sp storage price by time before it exists, expect error _, err := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{ Timestamp: 1, }) s.Require().Error(err) - // check update price + // update params + params := s.queryParams() + params.UpdateGlobalPriceInterval = 5 + s.updateParams(params) + sp := s.BaseSuite.PickStorageProvider() spAddr := sp.OperatorKey.GetAddr().String() spStoragePrice, err := s.Client.QuerySpStoragePrice(ctx, &sptypes.QuerySpStoragePriceRequest{ @@ -182,7 +180,7 @@ func (s *StorageProviderTestSuite) TestUpdateSpStoragePrice() { s.Require().NoError(err) s.T().Log(spStoragePrice) - // update storage price - first update is ok + // update storage price - update is ok msgUpdateSpStoragePrice := &sptypes.MsgUpdateSpStoragePrice{ SpAddress: spAddr, ReadPrice: spStoragePrice.SpStoragePrice.ReadPrice, @@ -191,25 +189,7 @@ func (s *StorageProviderTestSuite) TestUpdateSpStoragePrice() { } _ = s.SendTxBlock(sp.OperatorKey, msgUpdateSpStoragePrice) - // update storage price - secondary update is ok - msgUpdateSpStoragePrice = &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: spAddr, - ReadPrice: spStoragePrice.SpStoragePrice.ReadPrice, - StorePrice: spStoragePrice.SpStoragePrice.StorePrice, - FreeReadQuota: spStoragePrice.SpStoragePrice.FreeReadQuota, - } - _ = s.SendTxBlock(sp.OperatorKey, msgUpdateSpStoragePrice) - - // update storage price - third update is not ok - msgUpdateSpStoragePrice = &sptypes.MsgUpdateSpStoragePrice{ - SpAddress: spAddr, - ReadPrice: spStoragePrice.SpStoragePrice.ReadPrice, - StorePrice: spStoragePrice.SpStoragePrice.StorePrice, - FreeReadQuota: spStoragePrice.SpStoragePrice.FreeReadQuota, - } - s.SendTxBlockWithExpectErrorString(msgUpdateSpStoragePrice, sp.OperatorKey, "cannot update price due to frequency limited") - - time.Sleep(12 * time.Second) + time.Sleep(6 * time.Second) // verify price is updated after interval globalPriceResBefore, _ := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{Timestamp: 0}) @@ -235,20 +215,37 @@ func (s *StorageProviderTestSuite) TestUpdateSpStoragePrice() { } } - time.Sleep(12 * time.Second) + time.Sleep(6 * time.Second) globalPriceResAfter2, _ := s.Client.QueryGlobalSpStorePriceByTime(ctx, &sptypes.QueryGlobalSpStorePriceByTimeRequest{Timestamp: 0}) s.T().Log("globalPriceResAfter2", core.YamlString(globalPriceResAfter2)) s.CheckGlobalSpStorePrice() - if !priceChanged { //if price not changed, then after 10 seconds, it should change + if !priceChanged { //if price not changed, then after 6 seconds, it should change s.Require().NotEqual(globalPriceResAfter2.GlobalSpStorePrice.PrimaryStorePrice, globalPriceResBefore.GlobalSpStorePrice.PrimaryStorePrice) s.Require().NotEqual(globalPriceResAfter2.GlobalSpStorePrice.SecondaryStorePrice, globalPriceResBefore.GlobalSpStorePrice.SecondaryStorePrice) s.Require().NotEqual(globalPriceResAfter2.GlobalSpStorePrice.ReadPrice, globalPriceResBefore.GlobalSpStorePrice.ReadPrice) - } else { //if price not changed already, then after 10 seconds, it should not change + } else { //if price not changed already, then after 6 seconds, it should not change s.Require().Equal(globalPriceResAfter2.GlobalSpStorePrice.PrimaryStorePrice, globalPriceResAfter1.GlobalSpStorePrice.PrimaryStorePrice) s.Require().Equal(globalPriceResAfter2.GlobalSpStorePrice.SecondaryStorePrice, globalPriceResAfter1.GlobalSpStorePrice.SecondaryStorePrice) s.Require().Equal(globalPriceResAfter2.GlobalSpStorePrice.ReadPrice, globalPriceResAfter1.GlobalSpStorePrice.ReadPrice) } + + // update params + now := time.Now().UTC() + _, _, day := now.Date() + params = s.queryParams() + params.UpdateGlobalPriceInterval = 0 // update by month + params.UpdatePriceDisallowedDays = uint32(31 - day + 1) + s.updateParams(params) + + // update storage price - third update is not ok + msgUpdateSpStoragePrice = &sptypes.MsgUpdateSpStoragePrice{ + SpAddress: spAddr, + ReadPrice: spStoragePrice.SpStoragePrice.ReadPrice, + StorePrice: spStoragePrice.SpStoragePrice.StorePrice, + FreeReadQuota: spStoragePrice.SpStoragePrice.FreeReadQuota, + } + s.SendTxBlockWithExpectErrorString(msgUpdateSpStoragePrice, sp.OperatorKey, "update price is disallowed") } func (s *StorageProviderTestSuite) CheckGlobalSpStorePrice() { diff --git a/proto/greenfield/sp/params.proto b/proto/greenfield/sp/params.proto index 2581ccabe..2d6f5c3a3 100644 --- a/proto/greenfield/sp/params.proto +++ b/proto/greenfield/sp/params.proto @@ -33,6 +33,6 @@ message Params { int64 num_of_lockup_blocks_for_maintenance = 6 [(gogoproto.moretags) = "yaml:\"num_of_lockup_blocks_for_maintenance\""]; // the time interval to update global storage price, if it is not set then the price will be updated at the first block of each natural month uint64 update_global_price_interval = 7 [(gogoproto.moretags) = "yaml:\"update_global_price_interval\""]; - // the max times allowed to update price during an interval - uint32 max_update_price_times = 8 [(gogoproto.moretags) = "yaml:\"max_update_price_times\""]; + // the days counting backwards from end of a month in which a sp cannot update its price + uint32 update_price_disallowed_days = 8 [(gogoproto.moretags) = "yaml:\"update_price_disallowed_days\""]; } diff --git a/swagger/static/swagger.yaml b/swagger/static/swagger.yaml index 71fde0f24..0d0b5348f 100644 --- a/swagger/static/swagger.yaml +++ b/swagger/static/swagger.yaml @@ -1663,10 +1663,12 @@ paths: the time interval to update global storage price, if it is not set then the price will be updated at the first block of each natural month - max_update_price_times: + update_price_disallowed_days: type: integer format: int64 - title: the max times allowed to update price during an interval + title: >- + the days counting backwards from end of a month in which a + sp cannot update its price description: >- QueryParamsResponse is response type for the Query/Params RPC method. @@ -32861,10 +32863,12 @@ definitions: the time interval to update global storage price, if it is not set then the price will be updated at the first block of each natural month - max_update_price_times: + update_price_disallowed_days: type: integer format: int64 - title: the max times allowed to update price during an interval + title: >- + the days counting backwards from end of a month in which a sp cannot + update its price description: Params defines the parameters for the module. greenfield.sp.QueryGlobalSpStorePriceByTimeResponse: type: object @@ -32929,10 +32933,12 @@ definitions: the time interval to update global storage price, if it is not set then the price will be updated at the first block of each natural month - max_update_price_times: + update_price_disallowed_days: type: integer format: int64 - title: the max times allowed to update price during an interval + title: >- + the days counting backwards from end of a month in which a sp + cannot update its price description: QueryParamsResponse is response type for the Query/Params RPC method. greenfield.sp.QuerySpStoragePriceResponse: type: object diff --git a/x/sp/abci.go b/x/sp/abci.go index ce38208d8..98db68567 100644 --- a/x/sp/abci.go +++ b/x/sp/abci.go @@ -43,6 +43,5 @@ func EndBlocker(ctx sdk.Context, k keeper.Keeper) { if err != nil { ctx.Logger().Error("fail to update global sp store price", "err", err) } - k.ClearSpUpdatePriceTimes(ctx) } } diff --git a/x/sp/keeper/msg_server.go b/x/sp/keeper/msg_server.go index 2f46baadc..d8bf58637 100644 --- a/x/sp/keeper/msg_server.go +++ b/x/sp/keeper/msg_server.go @@ -153,7 +153,6 @@ func (k msgServer) CreateStorageProvider(goCtx context.Context, msg *types.MsgCr FreeReadQuota: msg.FreeReadQuota, } k.SetSpStoragePrice(ctx, spStoragePrice) - k.SetSpUpdatePriceTimes(ctx, sp.Id, 1) if err = ctx.EventManager().EmitTypedEvents(&types.EventCreateStorageProvider{ SpId: sp.Id, @@ -317,17 +316,10 @@ func (k msgServer) UpdateSpStoragePrice(goCtx context.Context, msg *types.MsgUpd } params := k.GetParams(ctx) - updateTimes := uint32(0) - if params.UpdateGlobalPriceInterval > 0 { // update price by interval - updateTimes = k.GetSpUpdatePriceTimes(ctx, sp.Id) - if updateTimes+1 > params.MaxUpdatePriceTimes { - return nil, errors.Wrapf(types.ErrStorageProviderPriceUpdateNotAllow, "exceeds the limit %d", params.MaxUpdatePriceTimes) - } - updateTimes++ - } else { // update price by month + if params.UpdateGlobalPriceInterval == 0 { // update price by month blockTime := ctx.BlockTime().UTC() - days := 2 - if IsLastDaysOfTheMonth(blockTime, days) { + days := params.UpdatePriceDisallowedDays + if IsLastDaysOfTheMonth(blockTime, int(days)) { return nil, errors.Wrapf(types.ErrStorageProviderPriceUpdateNotAllow, "price cannot be updated in the last %d days of the month", days) } } @@ -341,9 +333,6 @@ func (k msgServer) UpdateSpStoragePrice(goCtx context.Context, msg *types.MsgUpd FreeReadQuota: msg.FreeReadQuota, } k.SetSpStoragePrice(ctx, spStorePrice) - if updateTimes > 0 { - k.SetSpUpdatePriceTimes(ctx, sp.Id, updateTimes) - } return &types.MsgUpdateSpStoragePriceResponse{}, nil } diff --git a/x/sp/keeper/msg_server_test.go b/x/sp/keeper/msg_server_test.go index d854462f1..30ca1666c 100644 --- a/x/sp/keeper/msg_server_test.go +++ b/x/sp/keeper/msg_server_test.go @@ -153,8 +153,8 @@ func (s *KeeperTestSuite) TestMsgCreateStorageProvider() { } func (s *KeeperTestSuite) TestIsLastDaysOfTheMonth() { - s.Require().True(keeper.IsLastDaysOfTheMonth(time.Unix(1693328461, 0), 2)) // 2023-08-30 - s.Require().True(keeper.IsLastDaysOfTheMonth(time.Unix(1693414861, 0), 2)) // 2023-08-31 - s.Require().True(!keeper.IsLastDaysOfTheMonth(time.Unix(1693242061, 0), 2)) // 2023-08-29 - s.Require().True(!keeper.IsLastDaysOfTheMonth(time.Unix(1693587661, 0), 2)) // 2023-09-02 + s.Require().True(!keeper.IsLastDaysOfTheMonth(time.Unix(1693242061, 0).UTC(), 2)) // 2023-08-28 UTC + s.Require().True(!keeper.IsLastDaysOfTheMonth(time.Unix(1693328461, 0).UTC(), 2)) // 2023-08-29 UTC + s.Require().True(keeper.IsLastDaysOfTheMonth(time.Unix(1693414861, 0).UTC(), 2)) // 2023-08-30 UTC + s.Require().True(!keeper.IsLastDaysOfTheMonth(time.Unix(1693587661, 0).UTC(), 2)) // 2023-09-01 UTC } diff --git a/x/sp/keeper/sp_storage_price.go b/x/sp/keeper/sp_storage_price.go index 8bc4b36f2..76e89d245 100644 --- a/x/sp/keeper/sp_storage_price.go +++ b/x/sp/keeper/sp_storage_price.go @@ -1,7 +1,6 @@ package keeper import ( - "encoding/binary" "fmt" "sort" @@ -145,35 +144,3 @@ func (k Keeper) GetGlobalSpStorePriceByTime(ctx sdk.Context, time int64) (val ty val.UpdateTimeSec = updateTimeSec return val, nil } - -func (k Keeper) SetSpUpdatePriceTimes(ctx sdk.Context, spId uint32, times uint32) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.SpStoragePriceUpdateTimesKeyPrefix) - idBz := make([]byte, 4) - binary.BigEndian.PutUint32(idBz, spId) - timesBz := make([]byte, 4) - binary.BigEndian.PutUint32(timesBz, times) - store.Set(idBz, timesBz) -} - -func (k Keeper) GetSpUpdatePriceTimes(ctx sdk.Context, spId uint32) uint32 { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.SpStoragePriceUpdateTimesKeyPrefix) - idBz := make([]byte, 4) - binary.BigEndian.PutUint32(idBz, spId) - timesBz := store.Get(idBz) - if timesBz == nil { - return 0 - } - times := binary.BigEndian.Uint32(timesBz) - return times -} - -func (k Keeper) ClearSpUpdatePriceTimes(ctx sdk.Context) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.SpStoragePriceUpdateTimesKeyPrefix) - - iterator := storetypes.KVStorePrefixIterator(store, []byte{}) - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - store.Delete(iterator.Key()) - } -} diff --git a/x/sp/types/errors.go b/x/sp/types/errors.go index ed55ff5c4..3b6594550 100644 --- a/x/sp/types/errors.go +++ b/x/sp/types/errors.go @@ -23,7 +23,7 @@ var ( ErrStorageProviderBlsKeyExists = errors.Register(ModuleName, 15, "StorageProvider already exist for this bls pubkey; must use new bls pubkey") ErrStorageProviderStatusUpdateNotAllow = errors.Register(ModuleName, 16, "StorageProvider status is not allow to change") ErrStorageProviderMaintenanceAddrExists = errors.Register(ModuleName, 17, "StorageProvider already exist for this maintenance address; must use new StorageProvider maintenance address.") - ErrStorageProviderPriceUpdateNotAllow = errors.Register(ModuleName, 18, "StorageProvider cannot update price due to frequency limited.") + ErrStorageProviderPriceUpdateNotAllow = errors.Register(ModuleName, 18, "StorageProvider update price is disallowed") ErrSignerNotGovModule = errors.Register(ModuleName, 40, "signer is not gov module account") ErrSignerEmpty = errors.Register(ModuleName, 41, "signer is empty") diff --git a/x/sp/types/keys.go b/x/sp/types/keys.go index d0d3d464e..717f7d8af 100644 --- a/x/sp/types/keys.go +++ b/x/sp/types/keys.go @@ -24,17 +24,16 @@ const ( var ( ParamsKey = []byte{0x01} - StorageProviderKey = []byte{0x21} // prefix for each key to a storage provider - StorageProviderByOperatorAddrKey = []byte{0x23} // prefix for each key to a storage provider index, by operator address - StorageProviderByFundingAddrKey = []byte{0x24} // prefix for each key to a storage provider index, by funding address - StorageProviderBySealAddrKey = []byte{0x25} // prefix for each key to a storage provider index, by seal address - StorageProviderByApprovalAddrKey = []byte{0x26} // prefix for each key to a storage provider index, by approval address - StorageProviderByGcAddrKey = []byte{0x27} // prefix for each key to a storage provider index, by gc address - SpStoragePriceKeyPrefix = []byte{0x28} - GlobalSpStorePriceKeyPrefix = []byte{0x29} - StorageProviderByBlsPubKeyKey = []byte{0x30} // prefix for each key to a storage provider index, by bls pub key - StorageProviderSequenceKey = []byte{0x31} - SpStoragePriceUpdateTimesKeyPrefix = []byte{0x32} + StorageProviderKey = []byte{0x21} // prefix for each key to a storage provider + StorageProviderByOperatorAddrKey = []byte{0x23} // prefix for each key to a storage provider index, by operator address + StorageProviderByFundingAddrKey = []byte{0x24} // prefix for each key to a storage provider index, by funding address + StorageProviderBySealAddrKey = []byte{0x25} // prefix for each key to a storage provider index, by seal address + StorageProviderByApprovalAddrKey = []byte{0x26} // prefix for each key to a storage provider index, by approval address + StorageProviderByGcAddrKey = []byte{0x27} // prefix for each key to a storage provider index, by gc address + SpStoragePriceKeyPrefix = []byte{0x28} + GlobalSpStorePriceKeyPrefix = []byte{0x29} + StorageProviderByBlsPubKeyKey = []byte{0x30} // prefix for each key to a storage provider index, by bls pub key + StorageProviderSequenceKey = []byte{0x31} StorageProviderMaintenanceRecordPrefix = []byte{0x41} ) diff --git a/x/sp/types/params.go b/x/sp/types/params.go index 059153e0f..83f9502dc 100644 --- a/x/sp/types/params.go +++ b/x/sp/types/params.go @@ -24,8 +24,8 @@ const ( DefaultNumOfLockUpBlocksForMaintenance = 21600 // DefaultUpdateGlobalPriceInterval defines the default time duration for updating global storage price DefaultUpdateGlobalPriceInterval uint64 = 0 // 0 means the global price will be updated at the first day of each month - // DefaultMaxUpdatePriceTimes defines the max allowed times to update price for each sp in one interval - DefaultMaxUpdatePriceTimes uint32 = 3 + // UpdatePriceDisallowedDays defines the days, counting backward from the end of a month, in which sp is not allowed to update its price + DefaultUpdatePriceDisallowedDays uint32 = 2 ) var ( @@ -43,7 +43,7 @@ var ( KeyMaintenanceDurationQuota = []byte("MaintenanceDurationQuota") KeyNumOfLockUpBlocksForMaintenance = []byte("NumOfLockUpBlocksForMaintenance") KeyUpdateGlobalPriceInterval = []byte("UpdateGlobalPriceInterval") - KeyMaxUpdatePriceTimes = []byte("MaxUpdatePriceTimes") + KeyUpdatePriceDisallowedDays = []byte("UpdatePriceDisallowedDays") ) var _ paramtypes.ParamSet = (*Params)(nil) @@ -56,7 +56,7 @@ func ParamKeyTable() paramtypes.KeyTable { // NewParams creates a new Params instance func NewParams(depositDenom string, minDeposit math.Int, secondarySpStorePriceRatio sdk.Dec, historicalBlocksForMaintenanceRecords, maintenanceDurationQuota, lockUpBlocksForMaintenance int64, - updateGlobalPriceInterval uint64, maxUpdatePriceTimes uint32) Params { + updateGlobalPriceInterval uint64, updatePriceDisallowedDays uint32) Params { return Params{ DepositDenom: depositDenom, MinDeposit: minDeposit, @@ -65,7 +65,7 @@ func NewParams(depositDenom string, minDeposit math.Int, secondarySpStorePriceRa MaintenanceDurationQuota: maintenanceDurationQuota, NumOfLockupBlocksForMaintenance: lockUpBlocksForMaintenance, UpdateGlobalPriceInterval: updateGlobalPriceInterval, - MaxUpdatePriceTimes: maxUpdatePriceTimes, + UpdatePriceDisallowedDays: updatePriceDisallowedDays, } } @@ -73,7 +73,7 @@ func NewParams(depositDenom string, minDeposit math.Int, secondarySpStorePriceRa func DefaultParams() Params { return NewParams(DefaultDepositDenom, DefaultMinDeposit, DefaultSecondarySpStorePriceRatio, DefaultNumOfHistoricalBlocksForMaintenanceRecords, DefaultMaintenanceDurationQuota, DefaultNumOfLockUpBlocksForMaintenance, - DefaultUpdateGlobalPriceInterval, DefaultMaxUpdatePriceTimes) + DefaultUpdateGlobalPriceInterval, DefaultUpdatePriceDisallowedDays) } // ParamSetPairs get the params.ParamSet @@ -86,7 +86,7 @@ func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { paramtypes.NewParamSetPair(KeyMaintenanceDurationQuota, &p.MaintenanceDurationQuota, validateMaintenanceDurationQuota), paramtypes.NewParamSetPair(KeyNumOfLockUpBlocksForMaintenance, &p.NumOfLockupBlocksForMaintenance, validateLockUpBlocksForMaintenance), paramtypes.NewParamSetPair(KeyUpdateGlobalPriceInterval, &p.UpdateGlobalPriceInterval, validateUpdateGlobalPriceInterval), - paramtypes.NewParamSetPair(KeyMaxUpdatePriceTimes, &p.MaxUpdatePriceTimes, validateMaxUpdatePriceTimes), + paramtypes.NewParamSetPair(KeyUpdatePriceDisallowedDays, &p.UpdatePriceDisallowedDays, validateUpdatePriceDisallowedDays), } } @@ -115,7 +115,7 @@ func (p Params) Validate() error { if err := validateUpdateGlobalPriceInterval(p.UpdateGlobalPriceInterval); err != nil { return err } - if err := validateMaxUpdatePriceTimes(p.MaxUpdatePriceTimes); err != nil { + if err := validateUpdatePriceDisallowedDays(p.UpdatePriceDisallowedDays); err != nil { return err } @@ -214,13 +214,10 @@ func validateUpdateGlobalPriceInterval(i interface{}) error { return nil } -func validateMaxUpdatePriceTimes(i interface{}) error { - v, ok := i.(uint32) +func validateUpdatePriceDisallowedDays(i interface{}) error { + _, ok := i.(uint32) if !ok { return fmt.Errorf("invalid parameter type: %T", i) } - if v == 0 { - return errors.New("MaxUpdatePriceTimes cannot be zero") - } return nil } diff --git a/x/sp/types/params.pb.go b/x/sp/types/params.pb.go index aadf039b1..bb4bd5d10 100644 --- a/x/sp/types/params.pb.go +++ b/x/sp/types/params.pb.go @@ -41,8 +41,8 @@ type Params struct { NumOfLockupBlocksForMaintenance int64 `protobuf:"varint,6,opt,name=num_of_lockup_blocks_for_maintenance,json=numOfLockupBlocksForMaintenance,proto3" json:"num_of_lockup_blocks_for_maintenance,omitempty" yaml:"num_of_lockup_blocks_for_maintenance"` // the time interval to update global storage price, if it is not set then the price will be updated at the first block of each natural month UpdateGlobalPriceInterval uint64 `protobuf:"varint,7,opt,name=update_global_price_interval,json=updateGlobalPriceInterval,proto3" json:"update_global_price_interval,omitempty" yaml:"update_global_price_interval"` - // the max times allowed to update price during an interval - MaxUpdatePriceTimes uint32 `protobuf:"varint,8,opt,name=max_update_price_times,json=maxUpdatePriceTimes,proto3" json:"max_update_price_times,omitempty" yaml:"max_update_price_times"` + // the days counting backwards from end of a month in which a sp cannot update its price + UpdatePriceDisallowedDays uint32 `protobuf:"varint,8,opt,name=update_price_disallowed_days,json=updatePriceDisallowedDays,proto3" json:"update_price_disallowed_days,omitempty" yaml:"update_price_disallowed_days"` } func (m *Params) Reset() { *m = Params{} } @@ -112,9 +112,9 @@ func (m *Params) GetUpdateGlobalPriceInterval() uint64 { return 0 } -func (m *Params) GetMaxUpdatePriceTimes() uint32 { +func (m *Params) GetUpdatePriceDisallowedDays() uint32 { if m != nil { - return m.MaxUpdatePriceTimes + return m.UpdatePriceDisallowedDays } return 0 } @@ -126,43 +126,43 @@ func init() { func init() { proto.RegisterFile("greenfield/sp/params.proto", fileDescriptor_a5353d8e6e407d7e) } var fileDescriptor_a5353d8e6e407d7e = []byte{ - // 569 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x53, 0x4f, 0x6f, 0xd3, 0x30, - 0x1c, 0x6d, 0xd8, 0x28, 0xc3, 0xb0, 0x4b, 0x40, 0x28, 0xab, 0x20, 0xe9, 0x32, 0xfe, 0x54, 0x43, - 0x6d, 0x90, 0x38, 0x20, 0x0d, 0x4e, 0x51, 0x04, 0x54, 0x02, 0x31, 0x32, 0xe0, 0x80, 0x84, 0x2c, - 0x27, 0x71, 0x5b, 0x6b, 0xb1, 0x1d, 0x62, 0x07, 0xb5, 0x17, 0xc4, 0x47, 0xe0, 0xc8, 0x71, 0x7c, - 0x07, 0x3e, 0xc4, 0x8e, 0x13, 0x27, 0xc4, 0x21, 0x42, 0x2d, 0x07, 0xce, 0xfd, 0x04, 0xc8, 0x4e, - 0xd8, 0x8a, 0xb4, 0x4d, 0xda, 0x29, 0xc9, 0x7b, 0xef, 0xf7, 0xde, 0xef, 0xe7, 0xf8, 0x07, 0x5a, - 0xc3, 0x1c, 0x63, 0x36, 0x20, 0x38, 0x4d, 0x3c, 0x91, 0x79, 0x19, 0xca, 0x11, 0x15, 0xbd, 0x2c, - 0xe7, 0x92, 0x9b, 0xab, 0x47, 0x5c, 0x4f, 0x64, 0xad, 0xb5, 0x98, 0x0b, 0xca, 0x05, 0xd4, 0xa4, - 0x57, 0x7d, 0x54, 0xca, 0xd6, 0xd5, 0x21, 0x1f, 0xf2, 0x0a, 0x57, 0x6f, 0x15, 0xea, 0xfe, 0x6e, - 0x82, 0xe6, 0xb6, 0x36, 0x34, 0x37, 0xc0, 0x6a, 0x82, 0x33, 0x2e, 0x88, 0x84, 0x09, 0x66, 0x9c, - 0x5a, 0x46, 0xdb, 0xe8, 0x5c, 0x0c, 0x2f, 0xd7, 0x60, 0xa0, 0x30, 0xf3, 0x1d, 0xb8, 0x44, 0x09, - 0x83, 0x35, 0x66, 0x9d, 0x53, 0x12, 0xff, 0xd1, 0x7e, 0xe9, 0x34, 0x7e, 0x96, 0xce, 0xed, 0x21, - 0x91, 0xa3, 0x22, 0xea, 0xc5, 0x9c, 0xd6, 0xd9, 0xf5, 0xa3, 0x2b, 0x92, 0x5d, 0x4f, 0x4e, 0x32, - 0x2c, 0x7a, 0x7d, 0x26, 0xbf, 0x7f, 0xeb, 0x82, 0xba, 0xb5, 0x3e, 0x93, 0x21, 0xa0, 0x84, 0x05, - 0x95, 0x9f, 0xf9, 0xc9, 0x00, 0xb6, 0xc0, 0x31, 0x67, 0x09, 0xca, 0x27, 0x50, 0x64, 0x50, 0x48, - 0x9e, 0x63, 0x98, 0xe5, 0x24, 0xc6, 0x30, 0x47, 0x92, 0x70, 0x6b, 0xe9, 0xcc, 0x91, 0x01, 0x8e, - 0x17, 0x22, 0x03, 0x1c, 0x87, 0xad, 0xc3, 0x8c, 0x9d, 0x6c, 0x47, 0x25, 0x6c, 0xab, 0x80, 0x50, - 0xf9, 0x9b, 0x5f, 0x0d, 0x70, 0x8f, 0x15, 0x14, 0xf2, 0x01, 0x1c, 0x11, 0x15, 0x4f, 0x62, 0x94, - 0xc2, 0x28, 0xe5, 0xf1, 0xae, 0x80, 0x03, 0x9e, 0x43, 0x8a, 0x08, 0x93, 0x98, 0x21, 0xa6, 0x5a, - 0xc2, 0x31, 0xcf, 0x13, 0x61, 0x2d, 0xb7, 0x8d, 0xce, 0x92, 0xff, 0x70, 0x5e, 0x3a, 0x0f, 0x26, - 0x88, 0xa6, 0x5b, 0xee, 0x59, 0x1d, 0xdc, 0x70, 0x93, 0x15, 0xf4, 0xc5, 0xe0, 0xe9, 0x61, 0x81, - 0xaf, 0xf5, 0x8f, 0x79, 0xfe, 0xfc, 0x48, 0x1d, 0x56, 0x62, 0x33, 0x06, 0xad, 0x45, 0x8f, 0xa4, - 0xd0, 0x47, 0xc3, 0xe0, 0xfb, 0x82, 0x4b, 0x64, 0x9d, 0xd7, 0xcd, 0xdc, 0x9a, 0x97, 0xce, 0x7a, - 0xd5, 0xcc, 0xc9, 0x5a, 0x37, 0xb4, 0x16, 0xc8, 0xa0, 0xe6, 0x5e, 0x2a, 0xca, 0xfc, 0x08, 0x6e, - 0xd6, 0x53, 0xa8, 0x4e, 0x8a, 0xec, 0x84, 0x09, 0xac, 0xa6, 0x8e, 0xf3, 0xe6, 0xa5, 0x73, 0xf7, - 0xbf, 0xd9, 0x4f, 0xad, 0x72, 0x43, 0x47, 0xcf, 0xfb, 0x4c, 0x8b, 0x8e, 0x9b, 0xd5, 0x1c, 0x81, - 0xeb, 0x45, 0x96, 0x20, 0x89, 0xe1, 0x30, 0xe5, 0x11, 0x4a, 0xeb, 0x5b, 0xa0, 0x04, 0xf9, 0x07, - 0x94, 0x5a, 0x17, 0xda, 0x46, 0x67, 0xd9, 0xbf, 0x33, 0x2f, 0x9d, 0x8d, 0x2a, 0xf7, 0x34, 0xb5, - 0x1b, 0xae, 0x55, 0xf4, 0x13, 0xcd, 0xea, 0xff, 0xdd, 0xaf, 0x39, 0xf3, 0x0d, 0xb8, 0x46, 0xd1, - 0x18, 0xd6, 0xf5, 0x55, 0xa1, 0x24, 0x14, 0x0b, 0x6b, 0xa5, 0x6d, 0x74, 0x56, 0xfd, 0xf5, 0x79, - 0xe9, 0xdc, 0xf8, 0x77, 0x94, 0xc7, 0xe9, 0xdc, 0xf0, 0x0a, 0x45, 0xe3, 0xd7, 0x1a, 0xd7, 0xd6, - 0xaf, 0x14, 0xba, 0xb5, 0xf2, 0x65, 0xcf, 0x69, 0xfc, 0xd9, 0x73, 0x0c, 0x3f, 0xd8, 0x9f, 0xda, - 0xc6, 0xc1, 0xd4, 0x36, 0x7e, 0x4d, 0x6d, 0xe3, 0xf3, 0xcc, 0x6e, 0x1c, 0xcc, 0xec, 0xc6, 0x8f, - 0x99, 0xdd, 0x78, 0xbb, 0xb9, 0x70, 0x81, 0x23, 0x16, 0x75, 0xe3, 0x11, 0x22, 0xcc, 0x5b, 0xd8, - 0xf8, 0xb1, 0xda, 0x79, 0x7d, 0x91, 0xa3, 0xa6, 0xde, 0xd9, 0xfb, 0x7f, 0x03, 0x00, 0x00, 0xff, - 0xff, 0xc5, 0xe6, 0x36, 0x68, 0x11, 0x04, 0x00, 0x00, + // 561 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0xbf, 0x6f, 0xd3, 0x40, + 0x14, 0xc7, 0x63, 0x5a, 0x42, 0x31, 0x74, 0xb1, 0x18, 0xdc, 0x08, 0xd9, 0xc1, 0xe5, 0x47, 0x54, + 0xd4, 0x18, 0x89, 0x01, 0xa9, 0x30, 0x45, 0x16, 0x10, 0x09, 0x44, 0x71, 0x37, 0x24, 0x74, 0x3a, + 0xfb, 0x2e, 0xc9, 0xa9, 0xf6, 0xdd, 0x71, 0x77, 0x06, 0xb2, 0x20, 0xfe, 0x04, 0x46, 0xc6, 0xf2, + 0x3f, 0xf0, 0x47, 0x74, 0xac, 0x98, 0x10, 0x83, 0x85, 0x92, 0x85, 0x39, 0x03, 0x33, 0xba, 0xb3, + 0x95, 0x1a, 0x29, 0xad, 0xd4, 0xc9, 0xf6, 0xfb, 0x7e, 0xdf, 0xfb, 0xbc, 0x67, 0x3f, 0x9f, 0xdd, + 0x19, 0x0b, 0x8c, 0xe9, 0x88, 0xe0, 0x0c, 0x85, 0x92, 0x87, 0x1c, 0x0a, 0x98, 0xcb, 0x3e, 0x17, + 0x4c, 0x31, 0x67, 0xf3, 0x54, 0xeb, 0x4b, 0xde, 0xd9, 0x4a, 0x99, 0xcc, 0x99, 0x04, 0x46, 0x0c, + 0xab, 0x87, 0xca, 0xd9, 0xb9, 0x31, 0x66, 0x63, 0x56, 0xc5, 0xf5, 0x5d, 0x15, 0x0d, 0xfe, 0xb6, + 0xed, 0xf6, 0xbe, 0x29, 0xe8, 0x6c, 0xdb, 0x9b, 0x08, 0x73, 0x26, 0x89, 0x02, 0x08, 0x53, 0x96, + 0xbb, 0x56, 0xd7, 0xea, 0x5d, 0x8d, 0xaf, 0xd7, 0xc1, 0x48, 0xc7, 0x9c, 0xb7, 0xf6, 0xb5, 0x9c, + 0x50, 0x50, 0xc7, 0xdc, 0x4b, 0xda, 0x32, 0x78, 0x72, 0x5c, 0xfa, 0xad, 0x5f, 0xa5, 0x7f, 0x77, + 0x4c, 0xd4, 0xa4, 0x48, 0xfa, 0x29, 0xcb, 0x6b, 0x76, 0x7d, 0xd9, 0x95, 0xe8, 0x30, 0x54, 0x53, + 0x8e, 0x65, 0x7f, 0x48, 0xd5, 0x8f, 0xef, 0xbb, 0x76, 0xdd, 0xda, 0x90, 0xaa, 0xd8, 0xce, 0x09, + 0x8d, 0xaa, 0x7a, 0xce, 0x67, 0xcb, 0xf6, 0x24, 0x4e, 0x19, 0x45, 0x50, 0x4c, 0x81, 0xe4, 0x40, + 0x2a, 0x26, 0x30, 0xe0, 0x82, 0xa4, 0x18, 0x08, 0xa8, 0x08, 0x73, 0xd7, 0x2e, 0x8c, 0x8c, 0x70, + 0xda, 0x40, 0x46, 0x38, 0x8d, 0x3b, 0x4b, 0xc6, 0x01, 0x3f, 0xd0, 0x84, 0x7d, 0x0d, 0x88, 0x75, + 0x7d, 0xe7, 0x9b, 0x65, 0x3f, 0xa0, 0x45, 0x0e, 0xd8, 0x08, 0x4c, 0x88, 0xc6, 0x93, 0x14, 0x66, + 0x20, 0xc9, 0x58, 0x7a, 0x28, 0xc1, 0x88, 0x09, 0x90, 0x43, 0x42, 0x15, 0xa6, 0x90, 0xea, 0x96, + 0x70, 0xca, 0x04, 0x92, 0xee, 0x7a, 0xd7, 0xea, 0xad, 0x0d, 0x1e, 0x2f, 0x4a, 0xff, 0xd1, 0x14, + 0xe6, 0xd9, 0x5e, 0x70, 0xd1, 0x0a, 0x41, 0xbc, 0x43, 0x8b, 0xfc, 0xd5, 0xe8, 0xf9, 0x32, 0x61, + 0x60, 0xfc, 0x4f, 0x99, 0x78, 0x79, 0xea, 0x8e, 0x2b, 0xb3, 0x93, 0xda, 0x9d, 0x66, 0x0d, 0x54, + 0x98, 0x57, 0x43, 0xc1, 0xbb, 0x82, 0x29, 0xe8, 0x5e, 0x36, 0xcd, 0xdc, 0x59, 0x94, 0xfe, 0xad, + 0xaa, 0x99, 0xb3, 0xbd, 0x41, 0xec, 0x36, 0xc4, 0xa8, 0xd6, 0x5e, 0x6b, 0xc9, 0xf9, 0x64, 0xdf, + 0xae, 0xa7, 0xd0, 0x9d, 0x14, 0xfc, 0x8c, 0x09, 0xdc, 0xb6, 0xc1, 0x85, 0x8b, 0xd2, 0xbf, 0xff, + 0xdf, 0xec, 0xe7, 0x66, 0x05, 0xb1, 0x6f, 0xe6, 0x7d, 0x61, 0x4c, 0xab, 0x66, 0x75, 0x26, 0xf6, + 0xcd, 0x82, 0x23, 0xa8, 0x30, 0x18, 0x67, 0x2c, 0x81, 0x59, 0xbd, 0x05, 0xda, 0x20, 0xde, 0xc3, + 0xcc, 0xbd, 0xd2, 0xb5, 0x7a, 0xeb, 0x83, 0x7b, 0x8b, 0xd2, 0xdf, 0xae, 0xb8, 0xe7, 0xb9, 0x83, + 0x78, 0xab, 0x92, 0x9f, 0x19, 0xd5, 0x7c, 0xef, 0x61, 0xad, 0x35, 0x48, 0x55, 0x12, 0x22, 0x12, + 0x66, 0x19, 0xfb, 0x80, 0x11, 0x40, 0x70, 0x2a, 0xdd, 0x8d, 0xae, 0xd5, 0xdb, 0x5c, 0x41, 0x5a, + 0xe9, 0x5e, 0x92, 0x0c, 0x23, 0x5a, 0x8a, 0x11, 0x9c, 0xca, 0xbd, 0x8d, 0xaf, 0x47, 0x7e, 0xeb, + 0xcf, 0x91, 0x6f, 0x0d, 0xa2, 0xe3, 0x99, 0x67, 0x9d, 0xcc, 0x3c, 0xeb, 0xf7, 0xcc, 0xb3, 0xbe, + 0xcc, 0xbd, 0xd6, 0xc9, 0xdc, 0x6b, 0xfd, 0x9c, 0x7b, 0xad, 0x37, 0x3b, 0x8d, 0x95, 0x4e, 0x68, + 0xb2, 0x9b, 0x4e, 0x20, 0xa1, 0x61, 0xe3, 0x0c, 0xf8, 0xa8, 0x4f, 0x01, 0xb3, 0xda, 0x49, 0xdb, + 0xfc, 0xc5, 0x0f, 0xff, 0x05, 0x00, 0x00, 0xff, 0xff, 0x2f, 0xd4, 0x74, 0x7e, 0x23, 0x04, 0x00, + 0x00, } func (this *Params) Equal(that interface{}) bool { @@ -205,7 +205,7 @@ func (this *Params) Equal(that interface{}) bool { if this.UpdateGlobalPriceInterval != that1.UpdateGlobalPriceInterval { return false } - if this.MaxUpdatePriceTimes != that1.MaxUpdatePriceTimes { + if this.UpdatePriceDisallowedDays != that1.UpdatePriceDisallowedDays { return false } return true @@ -230,8 +230,8 @@ func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if m.MaxUpdatePriceTimes != 0 { - i = encodeVarintParams(dAtA, i, uint64(m.MaxUpdatePriceTimes)) + if m.UpdatePriceDisallowedDays != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.UpdatePriceDisallowedDays)) i-- dAtA[i] = 0x40 } @@ -322,8 +322,8 @@ func (m *Params) Size() (n int) { if m.UpdateGlobalPriceInterval != 0 { n += 1 + sovParams(uint64(m.UpdateGlobalPriceInterval)) } - if m.MaxUpdatePriceTimes != 0 { - n += 1 + sovParams(uint64(m.MaxUpdatePriceTimes)) + if m.UpdatePriceDisallowedDays != 0 { + n += 1 + sovParams(uint64(m.UpdatePriceDisallowedDays)) } return n } @@ -541,9 +541,9 @@ func (m *Params) Unmarshal(dAtA []byte) error { } case 8: if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field MaxUpdatePriceTimes", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field UpdatePriceDisallowedDays", wireType) } - m.MaxUpdatePriceTimes = 0 + m.UpdatePriceDisallowedDays = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowParams @@ -553,7 +553,7 @@ func (m *Params) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.MaxUpdatePriceTimes |= uint32(b&0x7F) << shift + m.UpdatePriceDisallowedDays |= uint32(b&0x7F) << shift if b < 0x80 { break } From 33f046a0697afdc67aebd5b47ad8c0cc2f863369 Mon Sep 17 00:00:00 2001 From: forcodedancing Date: Mon, 14 Aug 2023 10:58:46 +0800 Subject: [PATCH 10/13] format code --- x/payment/keeper/storage_fee_charge.go | 2 +- x/sp/keeper/sp_storage_price.go | 8 ++++---- x/sp/types/keys.go | 2 +- x/storage/keeper/keeper.go | 3 +-- 4 files changed, 7 insertions(+), 8 deletions(-) diff --git a/x/payment/keeper/storage_fee_charge.go b/x/payment/keeper/storage_fee_charge.go index 07c22d5cd..67c9a0f6b 100644 --- a/x/payment/keeper/storage_fee_charge.go +++ b/x/payment/keeper/storage_fee_charge.go @@ -64,7 +64,7 @@ func (k Keeper) ApplyUserFlowsList(ctx sdk.Context, userFlowsList []types.UserFl if err != nil { return err } - } else { // frozen status, should be called in end block for stop serving (uncharge fee) or for bucket migration (charge fee) + } else { // frozen status, should be called in end block for stop serving (uncharge fee) err = k.applyFrozenUserFlows(ctx, userFlows, from, streamRecord) if err != nil { return err diff --git a/x/sp/keeper/sp_storage_price.go b/x/sp/keeper/sp_storage_price.go index 76e89d245..7d0464a6f 100644 --- a/x/sp/keeper/sp_storage_price.go +++ b/x/sp/keeper/sp_storage_price.go @@ -118,13 +118,13 @@ func (k Keeper) UpdateGlobalSpStorePrice(ctx sdk.Context) error { func (k Keeper) calculateMedian(prices []sdk.Dec) sdk.Dec { l := len(prices) sort.Slice(prices, func(i, j int) bool { return prices[i].LT(prices[j]) }) - var storeMedian sdk.Dec + var median sdk.Dec if l%2 == 0 { - storeMedian = prices[l/2-1].Add(prices[l/2]).QuoInt64(2) + median = prices[l/2-1].Add(prices[l/2]).QuoInt64(2) } else { - storeMedian = prices[l/2] + median = prices[l/2] } - return storeMedian + return median } func (k Keeper) GetGlobalSpStorePriceByTime(ctx sdk.Context, time int64) (val types.GlobalSpStorePrice, err error) { diff --git a/x/sp/types/keys.go b/x/sp/types/keys.go index 717f7d8af..2803cf3fc 100644 --- a/x/sp/types/keys.go +++ b/x/sp/types/keys.go @@ -105,7 +105,7 @@ func SpStoragePriceKey(spId uint32) []byte { } func ParseSpStoragePriceKey(key []byte) (spId uint32) { - spId = binary.BigEndian.Uint32(key[0:4]) + spId = binary.BigEndian.Uint32(key) return } diff --git a/x/storage/keeper/keeper.go b/x/storage/keeper/keeper.go index 5601a2fe5..b67604433 100644 --- a/x/storage/keeper/keeper.go +++ b/x/storage/keeper/keeper.go @@ -4,8 +4,6 @@ import ( "encoding/binary" "fmt" - paymenttypes "github.com/bnb-chain/greenfield/x/payment/types" - "cosmossdk.io/errors" sdkmath "cosmossdk.io/math" "github.com/cometbft/cometbft/libs/log" @@ -19,6 +17,7 @@ import ( gnfdtypes "github.com/bnb-chain/greenfield/types" "github.com/bnb-chain/greenfield/types/common" "github.com/bnb-chain/greenfield/types/resource" + paymenttypes "github.com/bnb-chain/greenfield/x/payment/types" permtypes "github.com/bnb-chain/greenfield/x/permission/types" sptypes "github.com/bnb-chain/greenfield/x/sp/types" "github.com/bnb-chain/greenfield/x/storage/types" From 590046d44a7bf54e12ac3fa2bc63183d8cf18048 Mon Sep 17 00:00:00 2001 From: forcodedancing Date: Mon, 14 Aug 2023 14:03:32 +0800 Subject: [PATCH 11/13] fix some review comments --- x/sp/keeper/msg_server.go | 4 ++-- x/sp/keeper/msg_server_test.go | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/x/sp/keeper/msg_server.go b/x/sp/keeper/msg_server.go index d8bf58637..d41fed6b5 100644 --- a/x/sp/keeper/msg_server.go +++ b/x/sp/keeper/msg_server.go @@ -338,9 +338,9 @@ func (k msgServer) UpdateSpStoragePrice(goCtx context.Context, msg *types.MsgUpd } func IsLastDaysOfTheMonth(now time.Time, days int) bool { + now = now.UTC() year, month, _ := now.Date() - location := now.Location() - nextMonth := time.Date(year, month+1, 1, 0, 0, 0, 0, location) + nextMonth := time.Date(year, month+1, 1, 0, 0, 0, 0, time.FixedZone("UTC", 0)) daysBack := nextMonth.AddDate(0, 0, -1*days) return now.After(daysBack) } diff --git a/x/sp/keeper/msg_server_test.go b/x/sp/keeper/msg_server_test.go index 30ca1666c..6515000f0 100644 --- a/x/sp/keeper/msg_server_test.go +++ b/x/sp/keeper/msg_server_test.go @@ -153,8 +153,8 @@ func (s *KeeperTestSuite) TestMsgCreateStorageProvider() { } func (s *KeeperTestSuite) TestIsLastDaysOfTheMonth() { - s.Require().True(!keeper.IsLastDaysOfTheMonth(time.Unix(1693242061, 0).UTC(), 2)) // 2023-08-28 UTC - s.Require().True(!keeper.IsLastDaysOfTheMonth(time.Unix(1693328461, 0).UTC(), 2)) // 2023-08-29 UTC - s.Require().True(keeper.IsLastDaysOfTheMonth(time.Unix(1693414861, 0).UTC(), 2)) // 2023-08-30 UTC - s.Require().True(!keeper.IsLastDaysOfTheMonth(time.Unix(1693587661, 0).UTC(), 2)) // 2023-09-01 UTC + s.Require().True(!keeper.IsLastDaysOfTheMonth(time.Unix(1693242061, 0), 2)) // 2023-08-28 UTC + s.Require().True(!keeper.IsLastDaysOfTheMonth(time.Unix(1693328461, 0), 2)) // 2023-08-29 UTC + s.Require().True(keeper.IsLastDaysOfTheMonth(time.Unix(1693414861, 0), 2)) // 2023-08-30 UTC + s.Require().True(!keeper.IsLastDaysOfTheMonth(time.Unix(1693587661, 0), 2)) // 2023-09-01 UTC } From b2504b607840547967bd55c0f89af61d8dc3d9f9 Mon Sep 17 00:00:00 2001 From: forcodedancing Date: Mon, 14 Aug 2023 18:34:13 +0800 Subject: [PATCH 12/13] update dependency --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index a010d7d63..4a9c8f3d6 100644 --- a/go.mod +++ b/go.mod @@ -177,7 +177,7 @@ replace ( github.com/cometbft/cometbft => github.com/bnb-chain/greenfield-cometbft v0.0.0-20230810120916-f5f3421ab490 github.com/cometbft/cometbft-db => github.com/bnb-chain/greenfield-cometbft-db v0.8.1-alpha.1 github.com/confio/ics23/go => github.com/cosmos/cosmos-sdk/ics23/go v0.8.0 - github.com/cosmos/cosmos-sdk => github.com/bnb-chain/greenfield-cosmos-sdk v0.2.3-alpha.3.0.20230814021346-db9421ad0fa2 + github.com/cosmos/cosmos-sdk => github.com/bnb-chain/greenfield-cosmos-sdk v0.2.3-alpha.3.0.20230814031115-591476ad95c9 github.com/cosmos/iavl => github.com/bnb-chain/greenfield-iavl v0.20.1 github.com/syndtr/goleveldb => github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 ) diff --git a/go.sum b/go.sum index 7dcd794f8..aff8ad714 100644 --- a/go.sum +++ b/go.sum @@ -163,8 +163,8 @@ github.com/bnb-chain/greenfield-cometbft v0.0.0-20230810120916-f5f3421ab490 h1:s github.com/bnb-chain/greenfield-cometbft v0.0.0-20230810120916-f5f3421ab490/go.mod h1:3nGT4Z9fHwgRlBY/rofn0rSarnIcNbuhz/eq0XlLlkg= github.com/bnb-chain/greenfield-cometbft-db v0.8.1-alpha.1 h1:XcWulGacHVRiSCx90Q8Y//ajOrLNBQWR/KDB89dy3cU= github.com/bnb-chain/greenfield-cometbft-db v0.8.1-alpha.1/go.mod h1:ey1CiK4bYo1RBNJLRiVbYr5CMdSxci9S/AZRINLtppI= -github.com/bnb-chain/greenfield-cosmos-sdk v0.2.3-alpha.3.0.20230814021346-db9421ad0fa2 h1:2jLRWwnqwOS2foqCJaH+z7cStfxo6H9jMTEsRlbjW+4= -github.com/bnb-chain/greenfield-cosmos-sdk v0.2.3-alpha.3.0.20230814021346-db9421ad0fa2/go.mod h1:C4iDO5NuIlmlyFsIqhItF1A6ouAwsZmn20LQ0YhE0Mg= +github.com/bnb-chain/greenfield-cosmos-sdk v0.2.3-alpha.3.0.20230814031115-591476ad95c9 h1:BfTh1+AYz83B9OviXtXQ4+RwEXk7XAypRwjzO049EzU= +github.com/bnb-chain/greenfield-cosmos-sdk v0.2.3-alpha.3.0.20230814031115-591476ad95c9/go.mod h1:C4iDO5NuIlmlyFsIqhItF1A6ouAwsZmn20LQ0YhE0Mg= github.com/bnb-chain/greenfield-cosmos-sdk/api v0.0.0-20230425074444-eb5869b05fe9 h1:6fLpmmI0EZvDTfPvI0zy5dBaaTUboHnEkoC5/p/w8TQ= github.com/bnb-chain/greenfield-cosmos-sdk/api v0.0.0-20230425074444-eb5869b05fe9/go.mod h1:rbc4o84RSEvhf09o2+4Qiazsv0snRJLiEZdk17HeIDw= github.com/bnb-chain/greenfield-cosmos-sdk/math v0.0.0-20230425074444-eb5869b05fe9 h1:1ZdK+iR1Up02bOa2YTZCml7PBpP//kcdamOcK6aWO/s= From fcdaa25bd6f896b4535d4d505b10923d9f309fcb Mon Sep 17 00:00:00 2001 From: forcodedancing Date: Mon, 14 Aug 2023 20:35:35 +0800 Subject: [PATCH 13/13] fix some ut --- x/storage/types/genesis_test.go | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/x/storage/types/genesis_test.go b/x/storage/types/genesis_test.go index 01ed4b2be..58abb5fd0 100644 --- a/x/storage/types/genesis_test.go +++ b/x/storage/types/genesis_test.go @@ -31,12 +31,18 @@ func TestGenesisState_Validate(t *testing.T) { }, MaxPayloadSize: 2000, MaxBucketsPerAccount: 100, - BscMirrorBucketRelayerFee: "10", - BscMirrorBucketAckRelayerFee: "10", - BscMirrorGroupRelayerFee: "10", - BscMirrorGroupAckRelayerFee: "10", - BscMirrorObjectRelayerFee: "10", - BscMirrorObjectAckRelayerFee: "10", + BscMirrorBucketRelayerFee: "1", + BscMirrorBucketAckRelayerFee: "2", + BscMirrorGroupRelayerFee: "3", + BscMirrorGroupAckRelayerFee: "4", + BscMirrorObjectRelayerFee: "5", + BscMirrorObjectAckRelayerFee: "6", + OpMirrorBucketRelayerFee: "7", + OpMirrorBucketAckRelayerFee: "8", + OpMirrorGroupRelayerFee: "9", + OpMirrorGroupAckRelayerFee: "10", + OpMirrorObjectRelayerFee: "11", + OpMirrorObjectAckRelayerFee: "12", DiscontinueCountingWindow: 1000, DiscontinueObjectMax: 10000, DiscontinueBucketMax: 10000,