-
Notifications
You must be signed in to change notification settings - Fork 0
/
sequence.go
64 lines (51 loc) · 1.79 KB
/
sequence.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
package keeper
import (
"math/big"
"github.com/cosmos/cosmos-sdk/store/prefix"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/fury-labs/fury-bridge/x/bridge/types"
)
// GetNextWithdrawSequence reads the next available global withdraw sequence
// from store.
func (k Keeper) GetNextWithdrawSequence(ctx sdk.Context) (sdk.Int, error) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.NextWithdrawSequenceKeyPrefix)
bz := store.Get(types.NextWithdrawSequenceKeyPrefix)
if bz == nil {
return sdk.Int{}, types.ErrInvalidInitialWithdrawSequence
}
var seq sdk.Int
if err := seq.Unmarshal(bz); err != nil {
panic(err)
}
return seq, nil
}
// IncrementNextWithdrawSequence increments the next withdraw sequence in the
// store by 1.
func (k Keeper) IncrementNextWithdrawSequence(ctx sdk.Context) error {
seq, err := k.GetNextWithdrawSequence(ctx)
if err != nil {
return err
}
k.SetNextWithdrawSequence(ctx, WrappingAddInt(seq, sdk.OneInt()))
return nil
}
// SetNextWithdrawSequence stores a sequence to be used for the next withdraw.
func (k Keeper) SetNextWithdrawSequence(ctx sdk.Context, sequence sdk.Int) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.NextWithdrawSequenceKeyPrefix)
bz, err := sequence.Marshal()
if err != nil {
panic(err)
}
store.Set(types.NextWithdrawSequenceKeyPrefix, bz)
}
// WrappingAddInt adds two sdk.Int values with intentional wrapping.
func WrappingAddInt(i1 sdk.Int, i2 sdk.Int) sdk.Int {
sum := new(big.Int).Add(i1.BigInt(), i2.BigInt())
// Total is less than max, safe to convert to sdk.Int
if sum.Cmp(types.MaxWithdrawSequenceBigInt) <= 0 {
return sdk.NewIntFromBigInt(sum)
}
// Only keep the lower 256 bits to wrap
wrappedSum := new(big.Int).And(sum, types.MaxWithdrawSequenceBigInt)
return sdk.NewIntFromBigInt(wrappedSum)
}