-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
keeper.go
335 lines (274 loc) · 9.38 KB
/
keeper.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
package keeper
import (
"fmt"
"time"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
"github.com/tendermint/tendermint/libs/log"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/auth/ante"
"github.com/cosmos/cosmos-sdk/x/feegrant"
)
// Keeper manages state of all fee grants, as well as calculating approval.
// It must have a codec with all available allowances registered.
type Keeper struct {
cdc codec.BinaryCodec
storeKey storetypes.StoreKey
authKeeper feegrant.AccountKeeper
}
var _ ante.FeegrantKeeper = &Keeper{}
// NewKeeper creates a fee grant Keeper
func NewKeeper(cdc codec.BinaryCodec, storeKey storetypes.StoreKey, ak feegrant.AccountKeeper) Keeper {
return Keeper{
cdc: cdc,
storeKey: storeKey,
authKeeper: ak,
}
}
// Logger returns a module-specific logger.
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", fmt.Sprintf("x/%s", feegrant.ModuleName))
}
// GrantAllowance creates a new grant
func (k Keeper) GrantAllowance(ctx sdk.Context, granter, grantee sdk.AccAddress, feeAllowance feegrant.FeeAllowanceI) error {
// create the account if it is not in account state
granteeAcc := k.authKeeper.GetAccount(ctx, grantee)
if granteeAcc == nil {
granteeAcc = k.authKeeper.NewAccountWithAddress(ctx, grantee)
k.authKeeper.SetAccount(ctx, granteeAcc)
}
store := ctx.KVStore(k.storeKey)
key := feegrant.FeeAllowanceKey(granter, grantee)
var oldExp *time.Time
existingGrant, err := k.getGrant(ctx, granter, grantee)
// If we didn't find any grant, we don't return any error.
// All other kinds of errors are returned.
if err != nil && !sdkerrors.IsOf(err, sdkerrors.ErrNotFound) {
return err
}
if existingGrant != nil && existingGrant.GetAllowance() != nil {
grantInfo, err := existingGrant.GetGrant()
if err != nil {
return err
}
oldExp, err = grantInfo.ExpiresAt()
if err != nil {
return err
}
}
newExp, err := feeAllowance.ExpiresAt()
if err != nil { //nolint:gocritic // should be rewritten to a switch statement
return err
} else if newExp != nil && newExp.Before(ctx.BlockTime()) {
return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "expiration is before current block time")
} else if oldExp == nil && newExp != nil {
// when old oldExp is nil there won't be any key added before to queue.
// add the new key to queue directly.
k.addToFeeAllowanceQueue(ctx, key[1:], newExp)
} else if oldExp != nil && newExp == nil {
// when newExp is nil no need of adding the key to the pruning queue
// remove the old key from queue.
k.removeFromGrantQueue(ctx, oldExp, key[1:])
} else if oldExp != nil && newExp != nil && !oldExp.Equal(*newExp) {
// `key` formed here with the prefix of `FeeAllowanceKeyPrefix` (which is `0x00`)
// remove the 1st byte and reuse the remaining key as it is.
// remove the old key from queue.
k.removeFromGrantQueue(ctx, oldExp, key[1:])
// add the new key to queue.
k.addToFeeAllowanceQueue(ctx, key[1:], newExp)
}
grant, err := feegrant.NewGrant(granter, grantee, feeAllowance)
if err != nil {
return err
}
bz, err := k.cdc.Marshal(&grant)
if err != nil {
return err
}
store.Set(key, bz)
ctx.EventManager().EmitEvent(
sdk.NewEvent(
feegrant.EventTypeSetFeeGrant,
sdk.NewAttribute(feegrant.AttributeKeyGranter, grant.Granter),
sdk.NewAttribute(feegrant.AttributeKeyGrantee, grant.Grantee),
),
)
return nil
}
// UpdateAllowance updates the existing grant.
func (k Keeper) UpdateAllowance(ctx sdk.Context, granter, grantee sdk.AccAddress, feeAllowance feegrant.FeeAllowanceI) error {
store := ctx.KVStore(k.storeKey)
key := feegrant.FeeAllowanceKey(granter, grantee)
_, err := k.getGrant(ctx, granter, grantee)
if err != nil {
return err
}
grant, err := feegrant.NewGrant(granter, grantee, feeAllowance)
if err != nil {
return err
}
bz, err := k.cdc.Marshal(&grant)
if err != nil {
return err
}
store.Set(key, bz)
ctx.EventManager().EmitEvent(
sdk.NewEvent(
feegrant.EventTypeUpdateFeeGrant,
sdk.NewAttribute(feegrant.AttributeKeyGranter, grant.Granter),
sdk.NewAttribute(feegrant.AttributeKeyGrantee, grant.Grantee),
),
)
return nil
}
// revokeAllowance removes an existing grant
func (k Keeper) revokeAllowance(ctx sdk.Context, granter, grantee sdk.AccAddress) error {
_, err := k.getGrant(ctx, granter, grantee)
if err != nil {
return err
}
store := ctx.KVStore(k.storeKey)
key := feegrant.FeeAllowanceKey(granter, grantee)
store.Delete(key)
ctx.EventManager().EmitEvent(
sdk.NewEvent(
feegrant.EventTypeRevokeFeeGrant,
sdk.NewAttribute(feegrant.AttributeKeyGranter, granter.String()),
sdk.NewAttribute(feegrant.AttributeKeyGrantee, grantee.String()),
),
)
return nil
}
// GetAllowance returns the allowance between the granter and grantee.
// If there is none, it returns nil, nil.
// Returns an error on parsing issues
func (k Keeper) GetAllowance(ctx sdk.Context, granter, grantee sdk.AccAddress) (feegrant.FeeAllowanceI, error) {
grant, err := k.getGrant(ctx, granter, grantee)
if err != nil {
return nil, err
}
return grant.GetGrant()
}
// getGrant returns entire grant between both accounts
func (k Keeper) getGrant(ctx sdk.Context, granter sdk.AccAddress, grantee sdk.AccAddress) (*feegrant.Grant, error) {
store := ctx.KVStore(k.storeKey)
key := feegrant.FeeAllowanceKey(granter, grantee)
bz := store.Get(key)
if len(bz) == 0 {
return nil, sdkerrors.ErrNotFound.Wrap("fee-grant not found")
}
var feegrant feegrant.Grant
if err := k.cdc.Unmarshal(bz, &feegrant); err != nil {
return nil, err
}
return &feegrant, nil
}
// IterateAllFeeAllowances iterates over all the grants in the store.
// Callback to get all data, returns true to stop, false to keep reading
// Calling this without pagination is very expensive and only designed for export genesis
func (k Keeper) IterateAllFeeAllowances(ctx sdk.Context, cb func(grant feegrant.Grant) bool) error {
store := ctx.KVStore(k.storeKey)
iter := sdk.KVStorePrefixIterator(store, feegrant.FeeAllowanceKeyPrefix)
defer iter.Close()
stop := false
for ; iter.Valid() && !stop; iter.Next() {
bz := iter.Value()
var feeGrant feegrant.Grant
if err := k.cdc.Unmarshal(bz, &feeGrant); err != nil {
return err
}
stop = cb(feeGrant)
}
return nil
}
// UseGrantedFees will try to pay the given fee from the granter's account as requested by the grantee
func (k Keeper) UseGrantedFees(ctx sdk.Context, granter, grantee sdk.AccAddress, fee sdk.Coins, msgs []sdk.Msg) error {
f, err := k.getGrant(ctx, granter, grantee)
if err != nil {
return err
}
grant, err := f.GetGrant()
if err != nil {
return err
}
remove, err := grant.Accept(ctx, fee, msgs)
if remove {
// Ignoring the `revokeFeeAllowance` error, because the user has enough grants to perform this transaction.
k.revokeAllowance(ctx, granter, grantee)
if err != nil {
return err
}
emitUseGrantEvent(ctx, granter.String(), grantee.String())
return nil
}
if err != nil {
return err
}
emitUseGrantEvent(ctx, granter.String(), grantee.String())
// if fee allowance is accepted, store the updated state of the allowance
return k.UpdateAllowance(ctx, granter, grantee, grant)
}
func emitUseGrantEvent(ctx sdk.Context, granter, grantee string) {
ctx.EventManager().EmitEvent(
sdk.NewEvent(
feegrant.EventTypeUseFeeGrant,
sdk.NewAttribute(feegrant.AttributeKeyGranter, granter),
sdk.NewAttribute(feegrant.AttributeKeyGrantee, grantee),
),
)
}
// InitGenesis will initialize the keeper from a *previously validated* GenesisState
func (k Keeper) InitGenesis(ctx sdk.Context, data *feegrant.GenesisState) error {
for _, f := range data.Allowances {
granter, err := sdk.AccAddressFromBech32(f.Granter)
if err != nil {
return err
}
grantee, err := sdk.AccAddressFromBech32(f.Grantee)
if err != nil {
return err
}
grant, err := f.GetGrant()
if err != nil {
return err
}
err = k.GrantAllowance(ctx, granter, grantee, grant)
if err != nil {
return err
}
}
return nil
}
// ExportGenesis will dump the contents of the keeper into a serializable GenesisState.
func (k Keeper) ExportGenesis(ctx sdk.Context) (*feegrant.GenesisState, error) {
var grants []feegrant.Grant
err := k.IterateAllFeeAllowances(ctx, func(grant feegrant.Grant) bool {
grants = append(grants, grant)
return false
})
return &feegrant.GenesisState{
Allowances: grants,
}, err
}
func (k Keeper) removeFromGrantQueue(ctx sdk.Context, exp *time.Time, allowanceKey []byte) {
key := feegrant.FeeAllowancePrefixQueue(exp, allowanceKey)
store := ctx.KVStore(k.storeKey)
store.Delete(key)
}
func (k Keeper) addToFeeAllowanceQueue(ctx sdk.Context, grantKey []byte, exp *time.Time) {
store := ctx.KVStore(k.storeKey)
store.Set(feegrant.FeeAllowancePrefixQueue(exp, grantKey), []byte{})
}
// RemoveExpiredAllowances iterates grantsByExpiryQueue and deletes the expired grants.
func (k Keeper) RemoveExpiredAllowances(ctx sdk.Context) {
exp := ctx.BlockTime()
store := ctx.KVStore(k.storeKey)
iterator := store.Iterator(feegrant.FeeAllowanceQueueKeyPrefix, sdk.InclusiveEndBytes(feegrant.AllowanceByExpTimeKey(&exp)))
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
store.Delete(iterator.Key())
granter, grantee := feegrant.ParseAddressesFromFeeAllowanceQueueKey(iterator.Key())
store.Delete(feegrant.FeeAllowanceKey(granter, grantee))
}
}