-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
keeper.go
468 lines (374 loc) · 14.9 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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
package keeper
import (
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/store/prefix"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
vestexported "github.com/cosmos/cosmos-sdk/x/auth/vesting/exported"
"github.com/cosmos/cosmos-sdk/x/bank/types"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
)
var _ Keeper = (*BaseKeeper)(nil)
// Keeper defines a module interface that facilitates the transfer of coins
// between accounts.
type Keeper interface {
SendKeeper
InitGenesis(sdk.Context, *types.GenesisState)
ExportGenesis(sdk.Context) *types.GenesisState
GetSupply(ctx sdk.Context, denom string) sdk.Coin
GetTotalSupply(ctx sdk.Context) sdk.Coins
IterateTotalSupply(ctx sdk.Context, cb func(sdk.Coin) bool)
GetDenomMetaData(ctx sdk.Context, denom string) (types.Metadata, bool)
SetDenomMetaData(ctx sdk.Context, denomMetaData types.Metadata)
IterateAllDenomMetaData(ctx sdk.Context, cb func(types.Metadata) bool)
SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error
SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error
SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error
DelegateCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error
UndelegateCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error
MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error
BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error
DelegateCoins(ctx sdk.Context, delegatorAddr, moduleAccAddr sdk.AccAddress, amt sdk.Coins) error
UndelegateCoins(ctx sdk.Context, moduleAccAddr, delegatorAddr sdk.AccAddress, amt sdk.Coins) error
types.QueryServer
}
// BaseKeeper manages transfers between accounts. It implements the Keeper interface.
type BaseKeeper struct {
BaseSendKeeper
ak types.AccountKeeper
cdc codec.BinaryMarshaler
storeKey sdk.StoreKey
paramSpace paramtypes.Subspace
}
func (k BaseKeeper) GetTotalSupply(ctx sdk.Context) sdk.Coins {
balances := sdk.NewCoins()
k.IterateTotalSupply(ctx, func(balance sdk.Coin) bool {
balances = balances.Add(balance)
return false
})
return balances.Sort()
}
func NewBaseKeeper(
cdc codec.BinaryMarshaler, storeKey sdk.StoreKey, ak types.AccountKeeper, paramSpace paramtypes.Subspace,
blockedAddrs map[string]bool,
) BaseKeeper {
// set KeyTable if it has not already been set
if !paramSpace.HasKeyTable() {
paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable())
}
return BaseKeeper{
BaseSendKeeper: NewBaseSendKeeper(cdc, storeKey, ak, paramSpace, blockedAddrs),
ak: ak,
cdc: cdc,
storeKey: storeKey,
paramSpace: paramSpace,
}
}
// DelegateCoins performs delegation by deducting amt coins from an account with
// address addr. For vesting accounts, delegations amounts are tracked for both
// vesting and vested coins. The coins are then transferred from the delegator
// address to a ModuleAccount address. If any of the delegation amounts are negative,
// an error is returned.
func (k BaseKeeper) DelegateCoins(ctx sdk.Context, delegatorAddr, moduleAccAddr sdk.AccAddress, amt sdk.Coins) error {
moduleAcc := k.ak.GetAccount(ctx, moduleAccAddr)
if moduleAcc == nil {
return sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", moduleAccAddr)
}
if !amt.IsValid() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, amt.String())
}
balances := sdk.NewCoins()
for _, coin := range amt {
balance := k.GetBalance(ctx, delegatorAddr, coin.Denom)
if balance.IsLT(coin) {
return sdkerrors.Wrapf(
sdkerrors.ErrInsufficientFunds, "failed to delegate; %s is smaller than %s", balance, amt,
)
}
balances = balances.Add(balance)
err := k.setBalance(ctx, delegatorAddr, balance.Sub(coin))
if err != nil {
return err
}
}
if err := k.trackDelegation(ctx, delegatorAddr, balances, amt); err != nil {
return sdkerrors.Wrap(err, "failed to track delegation")
}
// emit coin spent event
ctx.EventManager().EmitEvent(
types.NewCoinSpentEvent(delegatorAddr, amt),
)
err := k.addCoins(ctx, moduleAccAddr, amt)
if err != nil {
return err
}
return nil
}
// UndelegateCoins performs undelegation by crediting amt coins to an account with
// address addr. For vesting accounts, undelegation amounts are tracked for both
// vesting and vested coins. The coins are then transferred from a ModuleAccount
// address to the delegator address. If any of the undelegation amounts are
// negative, an error is returned.
func (k BaseKeeper) UndelegateCoins(ctx sdk.Context, moduleAccAddr, delegatorAddr sdk.AccAddress, amt sdk.Coins) error {
moduleAcc := k.ak.GetAccount(ctx, moduleAccAddr)
if moduleAcc == nil {
return sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", moduleAccAddr)
}
if !amt.IsValid() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, amt.String())
}
err := k.subUnlockedCoins(ctx, moduleAccAddr, amt)
if err != nil {
return err
}
if err := k.trackUndelegation(ctx, delegatorAddr, amt); err != nil {
return sdkerrors.Wrap(err, "failed to track undelegation")
}
err = k.addCoins(ctx, delegatorAddr, amt)
if err != nil {
return err
}
return nil
}
// GetSupply retrieves the Supply from store
func (k BaseKeeper) GetSupply(ctx sdk.Context, denom string) sdk.Coin {
store := ctx.KVStore(k.storeKey)
supplyStore := prefix.NewStore(store, types.SupplyKey)
bz := supplyStore.Get([]byte(denom))
if bz == nil {
return sdk.Coin{
Denom: denom,
Amount: sdk.NewInt(0),
}
}
var coin sdk.Coin
err := k.cdc.UnmarshalBinaryBare(bz, &coin)
if err != nil {
panic(err)
}
return coin
}
// SetSupply sets the Supply to store
func (k BaseKeeper) setSupply(ctx sdk.Context, supply sdk.Coins) {
store := ctx.KVStore(k.storeKey)
supplyStore := prefix.NewStore(store, types.SupplyKey)
var newSupply []sdk.Coin
storeSupply := k.GetTotalSupply(ctx)
// update supply for coins which have non zero amount
for _, coin := range storeSupply {
if supply.AmountOf(coin.Denom).IsZero() {
zeroCoin := &sdk.Coin{
Denom: coin.Denom,
Amount: sdk.NewInt(0),
}
bz := k.cdc.MustMarshalBinaryBare(zeroCoin)
supplyStore.Set([]byte(coin.Denom), bz)
}
}
newSupply = append(newSupply, supply...)
for i := range newSupply {
bz := k.cdc.MustMarshalBinaryBare(&supply[i])
supplyStore.Set([]byte(supply[i].Denom), bz)
}
}
// GetDenomMetaData retrieves the denomination metadata
func (k BaseKeeper) GetDenomMetaData(ctx sdk.Context, denom string) (types.Metadata, bool) {
store := ctx.KVStore(k.storeKey)
store = prefix.NewStore(store, types.DenomMetadataKey(denom))
bz := store.Get([]byte(denom))
if bz == nil {
return types.Metadata{}, false
}
var metadata types.Metadata
k.cdc.MustUnmarshalBinaryBare(bz, &metadata)
return metadata, true
}
// GetAllDenomMetaData retrieves all denominations metadata
func (k BaseKeeper) GetAllDenomMetaData(ctx sdk.Context) []types.Metadata {
denomMetaData := make([]types.Metadata, 0)
k.IterateAllDenomMetaData(ctx, func(metadata types.Metadata) bool {
denomMetaData = append(denomMetaData, metadata)
return false
})
return denomMetaData
}
// IterateAllDenomMetaData iterates over all the denominations metadata and
// provides the metadata to a callback. If true is returned from the
// callback, iteration is halted.
func (k BaseKeeper) IterateAllDenomMetaData(ctx sdk.Context, cb func(types.Metadata) bool) {
store := ctx.KVStore(k.storeKey)
denomMetaDataStore := prefix.NewStore(store, types.DenomMetadataPrefix)
iterator := denomMetaDataStore.Iterator(nil, nil)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var metadata types.Metadata
k.cdc.MustUnmarshalBinaryBare(iterator.Value(), &metadata)
if cb(metadata) {
break
}
}
}
// SetDenomMetaData sets the denominations metadata
func (k BaseKeeper) SetDenomMetaData(ctx sdk.Context, denomMetaData types.Metadata) {
store := ctx.KVStore(k.storeKey)
denomMetaDataStore := prefix.NewStore(store, types.DenomMetadataKey(denomMetaData.Base))
m := k.cdc.MustMarshalBinaryBare(&denomMetaData)
denomMetaDataStore.Set([]byte(denomMetaData.Base), m)
}
// SendCoinsFromModuleToAccount transfers coins from a ModuleAccount to an AccAddress.
// It will panic if the module account does not exist.
func (k BaseKeeper) SendCoinsFromModuleToAccount(
ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins,
) error {
senderAddr := k.ak.GetModuleAddress(senderModule)
if senderAddr == nil {
panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", senderModule))
}
return k.SendCoins(ctx, senderAddr, recipientAddr, amt)
}
// SendCoinsFromModuleToModule transfers coins from a ModuleAccount to another.
// It will panic if either module account does not exist.
func (k BaseKeeper) SendCoinsFromModuleToModule(
ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins,
) error {
senderAddr := k.ak.GetModuleAddress(senderModule)
if senderAddr == nil {
panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", senderModule))
}
recipientAcc := k.ak.GetModuleAccount(ctx, recipientModule)
if recipientAcc == nil {
panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", recipientModule))
}
return k.SendCoins(ctx, senderAddr, recipientAcc.GetAddress(), amt)
}
// SendCoinsFromAccountToModule transfers coins from an AccAddress to a ModuleAccount.
// It will panic if the module account does not exist.
func (k BaseKeeper) SendCoinsFromAccountToModule(
ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins,
) error {
recipientAcc := k.ak.GetModuleAccount(ctx, recipientModule)
if recipientAcc == nil {
panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", recipientModule))
}
return k.SendCoins(ctx, senderAddr, recipientAcc.GetAddress(), amt)
}
// DelegateCoinsFromAccountToModule delegates coins and transfers them from a
// delegator account to a module account. It will panic if the module account
// does not exist or is unauthorized.
func (k BaseKeeper) DelegateCoinsFromAccountToModule(
ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins,
) error {
recipientAcc := k.ak.GetModuleAccount(ctx, recipientModule)
if recipientAcc == nil {
panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", recipientModule))
}
if !recipientAcc.HasPermission(authtypes.Staking) {
panic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "module account %s does not have permissions to receive delegated coins", recipientModule))
}
return k.DelegateCoins(ctx, senderAddr, recipientAcc.GetAddress(), amt)
}
// UndelegateCoinsFromModuleToAccount undelegates the unbonding coins and transfers
// them from a module account to the delegator account. It will panic if the
// module account does not exist or is unauthorized.
func (k BaseKeeper) UndelegateCoinsFromModuleToAccount(
ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins,
) error {
acc := k.ak.GetModuleAccount(ctx, senderModule)
if acc == nil {
panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", senderModule))
}
if !acc.HasPermission(authtypes.Staking) {
panic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "module account %s does not have permissions to undelegate coins", senderModule))
}
return k.UndelegateCoins(ctx, acc.GetAddress(), recipientAddr, amt)
}
// MintCoins creates new coins from thin air and adds it to the module account.
// It will panic if the module account does not exist or is unauthorized.
func (k BaseKeeper) MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error {
acc := k.ak.GetModuleAccount(ctx, moduleName)
if acc == nil {
panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", moduleName))
}
if !acc.HasPermission(authtypes.Minter) {
panic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "module account %s does not have permissions to mint tokens", moduleName))
}
err := k.addCoins(ctx, acc.GetAddress(), amt)
if err != nil {
return err
}
// update total supply
supply := k.GetTotalSupply(ctx)
supply = supply.Add(amt...)
k.setSupply(ctx, supply)
logger := k.Logger(ctx)
logger.Info("minted coins from module account", "amount", amt.String(), "from", moduleName)
// emit mint event
ctx.EventManager().EmitEvent(
types.NewCoinMintEvent(acc.GetAddress(), amt),
)
return nil
}
// BurnCoins burns coins deletes coins from the balance of the module account.
// It will panic if the module account does not exist or is unauthorized.
func (k BaseKeeper) BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error {
acc := k.ak.GetModuleAccount(ctx, moduleName)
if acc == nil {
panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", moduleName))
}
if !acc.HasPermission(authtypes.Burner) {
panic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "module account %s does not have permissions to burn tokens", moduleName))
}
err := k.subUnlockedCoins(ctx, acc.GetAddress(), amt)
if err != nil {
return err
}
// update total supply
supply := k.GetTotalSupply(ctx)
supply = supply.Sub(amt)
k.setSupply(ctx, supply)
logger := k.Logger(ctx)
logger.Info("burned tokens from module account", "amount", amt.String(), "from", moduleName)
// emit burn event
ctx.EventManager().EmitEvent(
types.NewCoinBurnEvent(acc.GetAddress(), amt),
)
return nil
}
func (k BaseKeeper) trackDelegation(ctx sdk.Context, addr sdk.AccAddress, balance, amt sdk.Coins) error {
acc := k.ak.GetAccount(ctx, addr)
if acc == nil {
return sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "account %s does not exist", addr)
}
vacc, ok := acc.(vestexported.VestingAccount)
if ok {
// TODO: return error on account.TrackDelegation
vacc.TrackDelegation(ctx.BlockHeader().Time, balance, amt)
}
return nil
}
func (k BaseKeeper) trackUndelegation(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) error {
acc := k.ak.GetAccount(ctx, addr)
if acc == nil {
return sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "account %s does not exist", addr)
}
vacc, ok := acc.(vestexported.VestingAccount)
if ok {
// TODO: return error on account.TrackUndelegation
vacc.TrackUndelegation(amt)
}
return nil
}
func (k BaseViewKeeper) IterateTotalSupply(ctx sdk.Context, cb func(sdk.Coin) bool) {
store := ctx.KVStore(k.storeKey)
supplyStore := prefix.NewStore(store, types.SupplyKey)
iterator := supplyStore.Iterator(nil, nil)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var balance sdk.Coin
k.cdc.MustUnmarshalBinaryBare(iterator.Value(), &balance)
if cb(balance) {
break
}
}
}