-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstorage_fee.go
More file actions
67 lines (59 loc) · 2.37 KB
/
storage_fee.go
File metadata and controls
67 lines (59 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package utils
import (
sdk "github.com/cosmos/cosmos-sdk/types"
storagetypes "github.com/gitopia/gitopia/v6/x/storage/types"
)
// StorageCostInfo contains information about storage costs and usage
type StorageCostInfo struct {
StorageCharge sdk.Coin
CurrentUsage uint64
NewUsage uint64
FreeLimit uint64
}
// calculateStorageCost calculates the storage cost based on current usage, new usage, and storage parameters
// Updated to match the logic from msg_server.go calculateStorageCharge method
func CalculateStorageCost(currentUsage, newUsage uint64, storageParams storagetypes.Params) (*StorageCostInfo, error) {
freeStorageBytes := storageParams.FreeStorageMb * 1024 * 1024 // Convert MB to bytes
// If current usage is already above free limit, charge for the entire diff
if currentUsage > freeStorageBytes {
diff := newUsage - currentUsage
if diff <= 0 {
return &StorageCostInfo{
StorageCharge: sdk.NewCoin(storageParams.StoragePricePerGb.Denom, sdk.ZeroInt()),
CurrentUsage: currentUsage,
NewUsage: newUsage,
FreeLimit: freeStorageBytes,
}, nil
}
// Calculate charge in GB and multiply by price per GB
diffGb := float64(diff) / (1024 * 1024 * 1024)
chargeAmount := sdk.NewDec(int64(diffGb)).Mul(sdk.NewDecFromInt(storageParams.StoragePricePerGb.Amount))
storageCharge := sdk.NewCoin(storageParams.StoragePricePerGb.Denom, chargeAmount.TruncateInt())
return &StorageCostInfo{
StorageCharge: storageCharge,
CurrentUsage: currentUsage,
NewUsage: newUsage,
FreeLimit: freeStorageBytes,
}, nil
}
// If new usage is below free limit, no charge
if newUsage <= freeStorageBytes {
return &StorageCostInfo{
StorageCharge: sdk.NewCoin(storageParams.StoragePricePerGb.Denom, sdk.ZeroInt()),
CurrentUsage: currentUsage,
NewUsage: newUsage,
FreeLimit: freeStorageBytes,
}, nil
}
// Calculate charge for the portion that exceeds free limit
excessBytes := newUsage - freeStorageBytes
excessGb := float64(excessBytes) / (1024 * 1024 * 1024)
chargeAmount := sdk.NewDec(int64(excessGb)).Mul(sdk.NewDecFromInt(storageParams.StoragePricePerGb.Amount))
storageCharge := sdk.NewCoin(storageParams.StoragePricePerGb.Denom, chargeAmount.TruncateInt())
return &StorageCostInfo{
StorageCharge: storageCharge,
CurrentUsage: currentUsage,
NewUsage: newUsage,
FreeLimit: freeStorageBytes,
}, nil
}