/
store.go
103 lines (91 loc) · 2.61 KB
/
store.go
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package keeper
import (
"encoding/binary"
"encoding/json"
"fmt"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/osmosis-labs/osmosis/x/lockup/types"
)
// GetLastLockID returns ID used last time
func (k Keeper) GetLastLockID(ctx sdk.Context) uint64 {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.KeyLastLockID)
if bz == nil {
return 0
}
return sdk.BigEndianToUint64(bz)
}
// SetLastLockID save ID used by last lock
func (k Keeper) SetLastLockID(ctx sdk.Context, ID uint64) {
store := ctx.KVStore(k.storeKey)
store.Set(types.KeyLastLockID, sdk.Uint64ToBigEndian(ID))
}
// lockStoreKey returns action store key from ID
func lockStoreKey(ID uint64) []byte {
return combineKeys(types.KeyPrefixPeriodLock, sdk.Uint64ToBigEndian(ID))
}
// getLockRefs get lock IDs specified on the prefix and timestamp key
func (k Keeper) getLockRefs(ctx sdk.Context, key []byte) []uint64 {
store := ctx.KVStore(k.storeKey)
lockIDs := []uint64{}
if store.Has(key) {
bz := store.Get(key)
err := json.Unmarshal(bz, &lockIDs)
if err != nil {
panic(err)
}
}
return lockIDs
}
// addLockRefByKey append lock ID into an array associated to provided key
func (k Keeper) addLockRefByKey(ctx sdk.Context, key []byte, lockID uint64) error {
store := ctx.KVStore(k.storeKey)
lockIDs := k.getLockRefs(ctx, key)
if findIndex(lockIDs, lockID) > -1 {
return fmt.Errorf("lock with same ID exist: %d", lockID)
}
lockIDs = append(lockIDs, lockID)
bz, err := json.Marshal(lockIDs)
if err != nil {
return err
}
store.Set(key, bz)
return nil
}
// deleteLockRefByKey removes lock ID from an array associated to provided key
func (k Keeper) deleteLockRefByKey(ctx sdk.Context, key []byte, lockID uint64) error {
var index = -1
store := ctx.KVStore(k.storeKey)
lockIDs := k.getLockRefs(ctx, key)
lockIDs, index = removeValue(lockIDs, lockID)
if index < 0 {
return fmt.Errorf("specific lock with ID %d not found", lockID)
}
if len(lockIDs) == 0 {
if store.Has(key) {
store.Delete(key)
}
} else {
bz, err := json.Marshal(lockIDs)
if err != nil {
return err
}
store.Set(key, bz)
}
return nil
}
func accumulationStorePrefix(denom string) (res []byte) {
res = make([]byte, len(types.KeyPrefixLockAccumulation))
copy(res, types.KeyPrefixLockAccumulation)
res = append(res, []byte(denom+"/")...)
return
}
// accumulationKey should return sort key upon duration.
// lockID is for preventing key duplication.
func accumulationKey(duration time.Duration, lockID uint64) (res []byte) {
res = make([]byte, 16)
binary.BigEndian.PutUint64(res[:8], uint64(duration))
binary.BigEndian.PutUint64(res[8:], lockID)
return
}