diff --git a/proto/cosmos/accesscontrol/constants.proto b/proto/cosmos/accesscontrol/constants.proto index 020848e9b..80e91a891 100644 --- a/proto/cosmos/accesscontrol/constants.proto +++ b/proto/cosmos/accesscontrol/constants.proto @@ -21,5 +21,6 @@ enum ResourceType { KV_ORACLE = 7; // child of KV KV_DEX = 8; // child of KV KV_EPOCH = 9; // child of KV + KV_TOKENFACTORY = 11; // child of KV } diff --git a/types/accesscontrol/constants.pb.go b/types/accesscontrol/constants.pb.go index 63688d25a..cc9f55239 100644 --- a/types/accesscontrol/constants.pb.go +++ b/types/accesscontrol/constants.pb.go @@ -54,42 +54,45 @@ func (AccessType) EnumDescriptor() ([]byte, []int) { type ResourceType int32 const ( - ResourceType_ANY ResourceType = 0 - ResourceType_KV ResourceType = 1 - ResourceType_Mem ResourceType = 2 - ResourceType_DexMem ResourceType = 3 - ResourceType_KV_BANK ResourceType = 4 - ResourceType_KV_STAKING ResourceType = 5 - ResourceType_KV_WASM ResourceType = 6 - ResourceType_KV_ORACLE ResourceType = 7 - ResourceType_KV_DEX ResourceType = 8 - ResourceType_KV_EPOCH ResourceType = 9 + ResourceType_ANY ResourceType = 0 + ResourceType_KV ResourceType = 1 + ResourceType_Mem ResourceType = 2 + ResourceType_DexMem ResourceType = 3 + ResourceType_KV_BANK ResourceType = 4 + ResourceType_KV_STAKING ResourceType = 5 + ResourceType_KV_WASM ResourceType = 6 + ResourceType_KV_ORACLE ResourceType = 7 + ResourceType_KV_DEX ResourceType = 8 + ResourceType_KV_EPOCH ResourceType = 9 + ResourceType_KV_TOKENFACTORY ResourceType = 11 ) var ResourceType_name = map[int32]string{ - 0: "ANY", - 1: "KV", - 2: "Mem", - 3: "DexMem", - 4: "KV_BANK", - 5: "KV_STAKING", - 6: "KV_WASM", - 7: "KV_ORACLE", - 8: "KV_DEX", - 9: "KV_EPOCH", + 0: "ANY", + 1: "KV", + 2: "Mem", + 3: "DexMem", + 4: "KV_BANK", + 5: "KV_STAKING", + 6: "KV_WASM", + 7: "KV_ORACLE", + 8: "KV_DEX", + 9: "KV_EPOCH", + 11: "KV_TOKENFACTORY", } var ResourceType_value = map[string]int32{ - "ANY": 0, - "KV": 1, - "Mem": 2, - "DexMem": 3, - "KV_BANK": 4, - "KV_STAKING": 5, - "KV_WASM": 6, - "KV_ORACLE": 7, - "KV_DEX": 8, - "KV_EPOCH": 9, + "ANY": 0, + "KV": 1, + "Mem": 2, + "DexMem": 3, + "KV_BANK": 4, + "KV_STAKING": 5, + "KV_WASM": 6, + "KV_ORACLE": 7, + "KV_DEX": 8, + "KV_EPOCH": 9, + "KV_TOKENFACTORY": 11, } func (x ResourceType) String() string { @@ -110,25 +113,26 @@ func init() { } var fileDescriptor_36568f7561081112 = []byte{ - // 307 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x5c, 0x90, 0x4f, 0x4f, 0xc2, 0x40, - 0x10, 0xc5, 0x5b, 0xfe, 0x14, 0x18, 0xd1, 0x4c, 0xf6, 0x6c, 0x7a, 0xf2, 0x44, 0x62, 0x2b, 0xf1, - 0xe6, 0x6d, 0x81, 0x46, 0x71, 0x6d, 0x6b, 0x4a, 0x5d, 0xd4, 0x4b, 0x03, 0xeb, 0x46, 0x8d, 0xc2, - 0x12, 0x76, 0x31, 0xf2, 0x09, 0xbc, 0xfa, 0xb1, 0x3c, 0x72, 0xf4, 0x68, 0xe0, 0x8b, 0x98, 0x52, - 0x2e, 0x7a, 0x9a, 0xc9, 0xbc, 0xf7, 0xe6, 0x25, 0x3f, 0x38, 0x12, 0x4a, 0x4f, 0x94, 0xf6, 0x47, - 0x42, 0x48, 0xad, 0x85, 0x9a, 0x9a, 0xb9, 0x7a, 0xf5, 0x85, 0x9a, 0x6a, 0x33, 0x9a, 0x1a, 0xed, - 0xcd, 0xe6, 0xca, 0x28, 0x72, 0x58, 0xb8, 0xbc, 0x3f, 0x2e, 0xef, 0xad, 0x3d, 0x96, 0x66, 0xd4, - 0x6e, 0x9d, 0x01, 0xd0, 0xad, 0x90, 0x2e, 0x67, 0x92, 0xec, 0x41, 0xed, 0x26, 0x62, 0x51, 0x3c, - 0x8c, 0xd0, 0x22, 0x75, 0xa8, 0x24, 0x01, 0xed, 0xa1, 0x4d, 0x1a, 0x50, 0x1d, 0x26, 0xfd, 0x34, - 0xc0, 0x12, 0x01, 0x70, 0xba, 0x71, 0x18, 0xf6, 0x53, 0x2c, 0xb7, 0x3e, 0x6c, 0x68, 0x26, 0x52, - 0xab, 0xc5, 0x5c, 0xc8, 0x6d, 0xbc, 0x06, 0x65, 0x1a, 0xdd, 0xa1, 0x45, 0x1c, 0x28, 0x31, 0x8e, - 0x76, 0x7e, 0x08, 0xe5, 0xa4, 0x88, 0xf5, 0xe4, 0x7b, 0xbe, 0x97, 0xf3, 0x12, 0xc6, 0xb3, 0x0e, - 0x8d, 0x18, 0x56, 0xc8, 0x01, 0x00, 0xe3, 0xd9, 0x20, 0xa5, 0xac, 0x1f, 0x9d, 0x63, 0x75, 0x27, - 0x0e, 0xe9, 0x20, 0x44, 0x87, 0xec, 0x43, 0x83, 0xf1, 0x2c, 0x4e, 0x68, 0xf7, 0x2a, 0xc0, 0x5a, - 0xfe, 0x84, 0xf1, 0xac, 0x17, 0xdc, 0x62, 0x9d, 0x34, 0xa1, 0xce, 0x78, 0x16, 0x5c, 0xc7, 0xdd, - 0x0b, 0x6c, 0x74, 0x2e, 0xbf, 0xd6, 0xae, 0xbd, 0x5a, 0xbb, 0xf6, 0xcf, 0xda, 0xb5, 0x3f, 0x37, - 0xae, 0xb5, 0xda, 0xb8, 0xd6, 0xf7, 0xc6, 0xb5, 0xee, 0x4f, 0x1e, 0x9f, 0xcd, 0xd3, 0x62, 0xec, - 0x09, 0x35, 0xf1, 0x77, 0xb8, 0x8a, 0x71, 0xac, 0x1f, 0x5e, 0x7c, 0xb3, 0x9c, 0xc9, 0x7f, 0xfc, - 0xc6, 0xce, 0x16, 0xdb, 0xe9, 0x6f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x80, 0x3c, 0xaa, 0x30, 0x5e, - 0x01, 0x00, 0x00, + // 325 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x5c, 0x90, 0xcf, 0x4e, 0xf2, 0x40, + 0x14, 0xc5, 0x5b, 0xfe, 0x14, 0xb8, 0xf0, 0x7d, 0x4e, 0xc6, 0xad, 0xe9, 0xca, 0x15, 0x89, 0xad, + 0xc4, 0x9d, 0xbb, 0xa1, 0x54, 0xc5, 0xb1, 0x53, 0x53, 0xea, 0x20, 0x6e, 0x1a, 0x18, 0x27, 0x6a, + 0x14, 0x86, 0x30, 0x83, 0x91, 0xb7, 0xf0, 0x01, 0x7c, 0x20, 0x97, 0x2c, 0x5d, 0x1a, 0x78, 0x11, + 0x53, 0x60, 0xa3, 0xab, 0x7b, 0x73, 0xcf, 0x39, 0xf7, 0x24, 0x3f, 0x38, 0x14, 0x4a, 0x8f, 0x95, + 0xf6, 0x87, 0x42, 0x48, 0xad, 0x85, 0x9a, 0x98, 0x99, 0x7a, 0xf1, 0x85, 0x9a, 0x68, 0x33, 0x9c, + 0x18, 0xed, 0x4d, 0x67, 0xca, 0x28, 0x7c, 0xb0, 0x75, 0x79, 0xbf, 0x5c, 0xde, 0x6b, 0x6b, 0x24, + 0xcd, 0xb0, 0xd5, 0x3c, 0x05, 0x20, 0x1b, 0x21, 0x5d, 0x4c, 0x25, 0xae, 0x43, 0xe5, 0x86, 0x51, + 0x16, 0xf7, 0x19, 0xb2, 0x70, 0x15, 0x4a, 0x49, 0x48, 0x3a, 0xc8, 0xc6, 0x35, 0x28, 0xf7, 0x93, + 0x6e, 0x1a, 0xa2, 0x02, 0x06, 0x70, 0x82, 0x38, 0x8a, 0xba, 0x29, 0x2a, 0x36, 0x3f, 0x6c, 0x68, + 0x24, 0x52, 0xab, 0xf9, 0x4c, 0xc8, 0x4d, 0xbc, 0x02, 0x45, 0xc2, 0x06, 0xc8, 0xc2, 0x0e, 0x14, + 0x28, 0x47, 0x76, 0x7e, 0x88, 0xe4, 0x78, 0x1b, 0xeb, 0xc8, 0xb7, 0x7c, 0x2f, 0xe6, 0x25, 0x94, + 0x67, 0x6d, 0xc2, 0x28, 0x2a, 0xe1, 0xff, 0x00, 0x94, 0x67, 0xbd, 0x94, 0xd0, 0x2e, 0x3b, 0x47, + 0xe5, 0x9d, 0xd8, 0x27, 0xbd, 0x08, 0x39, 0xf8, 0x1f, 0xd4, 0x28, 0xcf, 0xe2, 0x84, 0x04, 0x57, + 0x21, 0xaa, 0xe4, 0x4f, 0x28, 0xcf, 0x3a, 0xe1, 0x2d, 0xaa, 0xe2, 0x06, 0x54, 0x29, 0xcf, 0xc2, + 0xeb, 0x38, 0xb8, 0x40, 0x35, 0xbc, 0x0f, 0x7b, 0x94, 0x67, 0x69, 0x4c, 0x43, 0x76, 0x46, 0x82, + 0x34, 0x4e, 0x06, 0xa8, 0xde, 0xbe, 0xfc, 0x5c, 0xb9, 0xf6, 0x72, 0xe5, 0xda, 0xdf, 0x2b, 0xd7, + 0x7e, 0x5f, 0xbb, 0xd6, 0x72, 0xed, 0x5a, 0x5f, 0x6b, 0xd7, 0xba, 0x3b, 0x7e, 0x78, 0x32, 0x8f, + 0xf3, 0x91, 0x27, 0xd4, 0xd8, 0xdf, 0x31, 0xdc, 0x8e, 0x23, 0x7d, 0xff, 0xec, 0x9b, 0xc5, 0x54, + 0xfe, 0x81, 0x3a, 0x72, 0x36, 0x2c, 0x4f, 0x7e, 0x02, 0x00, 0x00, 0xff, 0xff, 0x48, 0x88, 0xf7, + 0xbb, 0x73, 0x01, 0x00, 0x00, } diff --git a/types/accesscontrol/resource.go b/types/accesscontrol/resource.go index 02971f199..be97c9164 100644 --- a/types/accesscontrol/resource.go +++ b/types/accesscontrol/resource.go @@ -15,14 +15,15 @@ var ResourceTree = map[ResourceType]TreeNode{ ResourceType_KV_STAKING, ResourceType_KV_WASM, }}, - ResourceType_Mem: {ResourceType_ANY, []ResourceType{ResourceType_DexMem}}, - ResourceType_DexMem: {ResourceType_Mem, []ResourceType{}}, - ResourceType_KV_BANK: {ResourceType_KV, []ResourceType{}}, - ResourceType_KV_STAKING: {ResourceType_KV, []ResourceType{}}, - ResourceType_KV_WASM: {ResourceType_KV, []ResourceType{}}, - ResourceType_KV_EPOCH: {ResourceType_KV, []ResourceType{}}, - ResourceType_KV_ORACLE: {ResourceType_KV, []ResourceType{}}, - ResourceType_KV_DEX: {ResourceType_KV, []ResourceType{}}, + ResourceType_Mem: {ResourceType_ANY, []ResourceType{ResourceType_DexMem}}, + ResourceType_DexMem: {ResourceType_Mem, []ResourceType{}}, + ResourceType_KV_BANK: {ResourceType_KV, []ResourceType{}}, + ResourceType_KV_STAKING: {ResourceType_KV, []ResourceType{}}, + ResourceType_KV_WASM: {ResourceType_KV, []ResourceType{}}, + ResourceType_KV_EPOCH: {ResourceType_KV, []ResourceType{}}, + ResourceType_KV_ORACLE: {ResourceType_KV, []ResourceType{}}, + ResourceType_KV_DEX: {ResourceType_KV, []ResourceType{}}, + ResourceType_KV_TOKENFACTORY: {ResourceType_KV, []ResourceType{}}, } // This returns a slice of all resource types that are dependent to a specific resource type diff --git a/types/context_cache.go b/types/context_cache.go index fb6775953..6bca7086c 100644 --- a/types/context_cache.go +++ b/types/context_cache.go @@ -2,6 +2,8 @@ package types import ( "sync" + + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -20,34 +22,52 @@ func NewContextMemCache() *ContextMemCache { } } -func (c *ContextMemCache) UpsertDeferredSends(moduleAccount string, amount Coins) { - // Separate locks needed for all mappings - atomic transaction needed +func (c *ContextMemCache) UpsertDeferredSends(moduleAccount string, amount Coins) error { + // Separate locks needed for all mappings - atmoic transaction needed c.deferredBankOpsLock.Lock() defer c.deferredBankOpsLock.Unlock() + if !amount.IsValid() { + return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, amount.String()) + } + // If there's already a pending withdrawal then subtract it from that amount first // or else add it to the deferredSends mapping ok := c.deferredWithdrawals.SafeSub(moduleAccount, amount) if !ok { c.deferredSends.UpsertMapping(moduleAccount, amount) } + return nil +} + +func (c *ContextMemCache) SafeSubDeferredSends(moduleAccount string, amount Coins) bool { + if !amount.IsValid() { + panic(sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, amount.String())) + } + + return c.deferredSends.SafeSub(moduleAccount, amount) } func (c *ContextMemCache) RangeOnDeferredSendsAndDelete(apply func (recipient string, amount Coins)) { c.deferredSends.RangeOnMapping(apply) } -func (c *ContextMemCache) UpsertDeferredWithdrawals(moduleAccount string, amount Coins) { - // Separate locks needed for all mappings - atomic transaction needed +func (c *ContextMemCache) UpsertDeferredWithdrawals(moduleAccount string, amount Coins) error { + // Separate locks needed for all mappings - atmoic transaction needed c.deferredBankOpsLock.Lock() defer c.deferredBankOpsLock.Unlock() + if !amount.IsValid() { + return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, amount.String()) + } + // If there's already a pending deposit then subtract it from that amount first // or else add it to the deferredWithdrawals mapping ok := c.deferredSends.SafeSub(moduleAccount, amount) if !ok { c.deferredWithdrawals.UpsertMapping(moduleAccount, amount) } + return nil } func (c *ContextMemCache) RangeOnDeferredWithdrawalsAndDelete(apply func (recipient string, amount Coins)) { diff --git a/types/deferred_bank_operations.go b/types/deferred_bank_operations.go index 06344f854..33564e1e7 100644 --- a/types/deferred_bank_operations.go +++ b/types/deferred_bank_operations.go @@ -17,27 +17,16 @@ func NewDeferredBankOperationMap() *DeferredBankOperationMapping { } } -func (m *DeferredBankOperationMapping) get(moduleAccount string) (Coins, bool) { - if v, ok := m.deferredOperations[moduleAccount]; ok { - return v, true - } - return nil, false -} - -func (m *DeferredBankOperationMapping) set(moduleAccount string, amount Coins) { - m.deferredOperations[moduleAccount] = amount -} - // If there's already a pending opposite operation then subtract it from that amount first // returns true if amount was subtracted func (m *DeferredBankOperationMapping) SafeSub(moduleAccount string, amount Coins) bool { m.mappingLock.Lock() defer m.mappingLock.Unlock() - if deferredAmount, ok := m.get(moduleAccount); ok { + if deferredAmount, ok := m.deferredOperations[moduleAccount]; ok { newAmount, isNegative := deferredAmount.SafeSub(amount) if !isNegative { - m.set(moduleAccount, newAmount) + m.deferredOperations[moduleAccount] = newAmount return true } } diff --git a/x/auth/types/expected_keepers.go b/x/auth/types/expected_keepers.go index 13620c215..4f7ed3bbb 100644 --- a/x/auth/types/expected_keepers.go +++ b/x/auth/types/expected_keepers.go @@ -8,4 +8,7 @@ import ( type BankKeeper interface { SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error DeferredSendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error + DeferredSendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amount sdk.Coins) error + DeferredMintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error + DeferredBurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error } diff --git a/x/bank/keeper/keeper.go b/x/bank/keeper/keeper.go index 569b7ff5a..eaa8d1a95 100644 --- a/x/bank/keeper/keeper.go +++ b/x/bank/keeper/keeper.go @@ -35,17 +35,21 @@ type Keeper interface { IterateAllDenomMetaData(ctx sdk.Context, cb func(types.Metadata) bool) SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - DeferredSendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amount 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 - DeferredSendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - WriteDeferredDepositsToModuleAccounts(ctx sdk.Context) []abci.Event 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 - WriteDeferredOperations(ctx sdk.Context) []abci.Event + MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error + DeferredSendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amount sdk.Coins) error + DeferredSendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error + WriteDeferredDepositsToModuleAccounts(ctx sdk.Context) []abci.Event + WriteDeferredOperations(ctx sdk.Context) []abci.Event + DeferredMintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error + DeferredBurnCoins(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 @@ -64,6 +68,8 @@ type BaseKeeper struct { } type MintingRestrictionFn func(ctx sdk.Context, coins sdk.Coins) error +type SubFn func(ctx sdk.Context, moduleName string, amounts sdk.Coins) error +type AddFn func(ctx sdk.Context, moduleName string, amounts sdk.Coins) error // GetPaginatedTotalSupply queries for the supply, ignoring 0 coins, with a given pagination func (k BaseKeeper) GetPaginatedTotalSupply(ctx sdk.Context, pagination *query.PageRequest) (sdk.Coins, *query.PageResponse, error) { @@ -325,6 +331,13 @@ func (k BaseKeeper) SendCoinsFromModuleToAccount( return sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", recipientAddr) } + // Try subtract from the in mem var first, prevents the condition where + // the module may have a pending deposit that would be enough to pay for this send + ok := ctx.ContextMemCache().SafeSubDeferredSends(senderModule, amt) + if ok { + return k.addCoins(ctx, recipientAddr, amt) + } + return k.SendCoins(ctx, senderAddr, recipientAddr, amt) } @@ -377,6 +390,13 @@ func (k BaseKeeper) SendCoinsFromModuleToModule( panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", recipientModule)) } + // Try subtract from the in mem var first, prevents the condition where + // the module may have a pending deposit that would be enough to pay for this send + ok := ctx.ContextMemCache().SafeSubDeferredSends(senderModule, amt) + if ok { + return k.addCoins(ctx, recipientAcc.GetAddress(), amt) + } + return k.SendCoins(ctx, senderAddr, recipientAcc.GetAddress(), amt) } @@ -444,6 +464,11 @@ func (k BaseKeeper) WriteDeferredWrithdrawlFromModuleAccounts(ctx sdk.Context) [ if recipientAcc == nil { panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", recipient)) } + + if amount.Empty() { + return + } + log.Printf("Removing coin=%s from module=%s address=%s", amount, recipient, recipientAcc.GetAddress()) k.subUnlockedCoins(ctx, recipientAcc.GetAddress(), amount) }, @@ -490,9 +515,7 @@ func (k BaseKeeper) UndelegateCoinsFromModuleToAccount( 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, amounts sdk.Coins) error { +func (k BaseKeeper) createCoins(ctx sdk.Context, moduleName string, amounts sdk.Coins, addFn AddFn) error { err := k.mintCoinsRestrictionFn(ctx, amounts) if err != nil { ctx.Logger().Error(fmt.Sprintf("Module %q attempted to mint coins %s it doesn't have permission for, error %v", moduleName, amounts, err)) @@ -507,11 +530,10 @@ func (k BaseKeeper) MintCoins(ctx sdk.Context, moduleName string, amounts sdk.Co panic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "module account %s does not have permissions to mint tokens", moduleName)) } - err = k.addCoins(ctx, acc.GetAddress(), amounts) + err = addFn(ctx, moduleName, amounts) if err != nil { return err } - for _, amount := range amounts { supply := k.GetSupply(ctx, amount.GetDenom()) supply = supply.Add(amount) @@ -529,9 +551,40 @@ func (k BaseKeeper) MintCoins(ctx sdk.Context, moduleName string, amounts sdk.Co return nil } -// BurnCoins burns coins deletes coins from the balance of the module account. +// 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) BurnCoins(ctx sdk.Context, moduleName string, amounts sdk.Coins) error { +func (k BaseKeeper) MintCoins(ctx sdk.Context, moduleName string, amounts sdk.Coins) error { + addFn := func(ctx sdk.Context, moduleName string, amounts sdk.Coins) error { + acc := k.ak.GetModuleAccount(ctx, moduleName) + return k.addCoins(ctx, acc.GetAddress(), amounts) + } + + err := k.createCoins(ctx, moduleName, amounts, addFn) + if err != nil { + return err + } + return nil +} + +// DeferredMintCoins creates new coins from thin air and adds it to the module account. +// It will not update the AVL store immediate but instead caches the data in an mem var +// it requires the user to flush the deposits all at once. Used for deterministic concurrency +// writes at the end of a block. +// It will panic if the module account does not exist or is unauthorized. +func (k BaseKeeper) DeferredMintCoins(ctx sdk.Context, moduleName string, amounts sdk.Coins) error { + addFn := func(ctx sdk.Context, moduleName string, amounts sdk.Coins) error { + return ctx.ContextMemCache().UpsertDeferredSends(moduleName, amounts) + } + + err := k.createCoins(ctx, moduleName, amounts, addFn) + if err != nil { + return err + } + + return nil +} + +func (k BaseKeeper) destroyCoins(ctx sdk.Context, moduleName string, amounts sdk.Coins, subFn SubFn) error { acc := k.ak.GetModuleAccount(ctx, moduleName) if acc == nil { panic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "module account %s does not exist", moduleName)) @@ -541,7 +594,7 @@ func (k BaseKeeper) BurnCoins(ctx sdk.Context, moduleName string, amounts sdk.Co panic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "module account %s does not have permissions to burn tokens", moduleName)) } - err := k.subUnlockedCoins(ctx, acc.GetAddress(), amounts) + err := subFn(ctx, moduleName, amounts) if err != nil { return err } @@ -559,6 +612,49 @@ func (k BaseKeeper) BurnCoins(ctx sdk.Context, moduleName string, amounts sdk.Co ctx.EventManager().EmitEvent( types.NewCoinBurnEvent(acc.GetAddress(), amounts), ) + 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, amounts sdk.Coins) error { + subFn := func(ctx sdk.Context, moduleName string, amounts sdk.Coins) error { + acc := k.ak.GetModuleAccount(ctx, moduleName) + return k.subUnlockedCoins(ctx, acc.GetAddress(), amounts) + } + + err := k.destroyCoins(ctx, moduleName, amounts, subFn) + if err != nil { + return err + } + + return nil +} + +// DeferredBurnCoins burns coins deletes coins from the balance of the module account. +// It will not update the AVL store immediate but instead caches the data in an mem var +// it requires the user to flush the deposits all at once. Used for deterministic concurrency +// writes at the end of a block. +// It will panic if the module account does not exist or is unauthorized. +func (k BaseKeeper) DeferredBurnCoins(ctx sdk.Context, moduleName string, amounts sdk.Coins) error { + subFn := func(ctx sdk.Context, moduleName string, amounts sdk.Coins) error { + + // Branch Context for validation and fail if the module doesn't have enough coins + // but don't write this to the underlying store + validationContext, _ := ctx.CacheContext() + acc := k.ak.GetModuleAccount(ctx, moduleName) + err := k.subUnlockedCoins(validationContext, acc.GetAddress(), amounts) + if err != nil { + return err + } + + return ctx.ContextMemCache().UpsertDeferredWithdrawals(moduleName, amounts) + } + + err := k.destroyCoins(ctx, moduleName, amounts, subFn) + if err != nil { + return err + } return nil } diff --git a/x/bank/keeper/keeper_test.go b/x/bank/keeper/keeper_test.go index b8e97fc6e..576b2ebd7 100644 --- a/x/bank/keeper/keeper_test.go +++ b/x/bank/keeper/keeper_test.go @@ -250,6 +250,59 @@ func (suite *IntegrationTestSuite) TestSupply_MintCoins() { suite.Require().Panics(func() { keeper.MintCoins(ctx, authtypes.Burner, initCoins) }) // nolint:errcheck } +func (suite *IntegrationTestSuite) TestSupply_DeferredMintCoins() { + ctx := suite.ctx + + // add module accounts to supply keeper + authKeeper, keeper := suite.initKeepersWithmAccPerms(make(map[string]bool)) + + authKeeper.SetModuleAccount(ctx, burnerAcc) + authKeeper.SetModuleAccount(ctx, minterAcc) + authKeeper.SetModuleAccount(ctx, multiPermAcc) + authKeeper.SetModuleAccount(ctx, randomPermAcc) + + initialSupply, _, err := keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) + suite.Require().NoError(err) + + suite.Require().Panics(func() { keeper.DeferredMintCoins(ctx, "", initCoins) }, "no module account") // nolint:errcheck + suite.Require().Panics(func() { keeper.DeferredMintCoins(ctx, authtypes.Burner, initCoins) }, "invalid permission") // nolint:errcheck + + err = keeper.DeferredMintCoins(ctx, authtypes.Minter, sdk.Coins{sdk.Coin{Denom: "denom", Amount: sdk.NewInt(-10)}}) + suite.Require().Error(err, "insufficient coins") + + suite.Require().Panics(func() { keeper.DeferredMintCoins(ctx, randomPerm, initCoins) }) // nolint:errcheck + + err = keeper.DeferredMintCoins(ctx, authtypes.Minter, initCoins) + suite.Require().NoError(err) + + suite.Require().Equal(sdk.Coins{}, getCoinsByName(ctx, keeper, authKeeper, authtypes.Minter)) + totalSupply, _, err := keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) + suite.Require().NoError(err) + + suite.Require().Equal(initialSupply.Add(initCoins...), totalSupply) + + // test same functionality on module account with multiple permissions + initialSupply, _, err = keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) + suite.Require().NoError(err) + + keeper.WriteDeferredOperations(ctx) + suite.Require().Equal(initialSupply, getCoinsByName(ctx, keeper, authKeeper, authtypes.Minter)) + + err = keeper.DeferredMintCoins(ctx, multiPermAcc.GetName(), initCoins) + suite.Require().NoError(err) + + totalSupply, _, err = keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) + suite.Require().NoError(err) + + suite.Require().Equal(sdk.Coins{}, getCoinsByName(ctx, keeper, authKeeper, multiPermAcc.GetName())) + keeper.WriteDeferredOperations(ctx) + suite.Require().Equal(initCoins, getCoinsByName(ctx, keeper, authKeeper, multiPermAcc.GetName())) + + + suite.Require().Equal(initialSupply.Add(initCoins...), totalSupply) + suite.Require().Panics(func() { keeper.DeferredMintCoins(ctx, authtypes.Burner, initCoins) }) // nolint:errcheck +} + func (suite *IntegrationTestSuite) TestSupply_BurnCoins() { ctx := suite.ctx // add module accounts to supply keeper @@ -301,6 +354,67 @@ func (suite *IntegrationTestSuite) TestSupply_BurnCoins() { suite.Require().Equal(supplyAfterInflation.Sub(initCoins), supplyAfterBurn) } +func (suite *IntegrationTestSuite) TestSupply_DeferredBurnCoins() { + ctx := suite.ctx + // add module accounts to supply keeper + authKeeper, keeper := suite.initKeepersWithmAccPerms(make(map[string]bool)) + + // set burnerAcc balance + authKeeper.SetModuleAccount(ctx, burnerAcc) + suite. + Require(). + NoError(keeper.MintCoins(ctx, authtypes.Minter, initCoins)) + suite. + Require(). + NoError(keeper.DeferredSendCoinsFromModuleToAccount(ctx, authtypes.Minter, burnerAcc.GetAddress(), initCoins)) + + // inflate supply + suite. + Require(). + NoError(keeper.DeferredMintCoins(ctx, authtypes.Minter, initCoins)) + supplyAfterInflation, _, err := keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) + keeper.WriteDeferredOperations(ctx) + + suite.Require().Panics(func() { keeper.BurnCoins(ctx, "", initCoins) }, "no module account") // nolint:errcheck + suite.Require().Panics(func() { keeper.BurnCoins(ctx, authtypes.Minter, initCoins) }, "invalid permission") // nolint:errcheck + suite.Require().Panics(func() { keeper.BurnCoins(ctx, randomPerm, supplyAfterInflation) }, "random permission") // nolint:errcheck + err = keeper.DeferredBurnCoins(ctx, authtypes.Burner, supplyAfterInflation) + keeper.WriteDeferredOperations(ctx) + suite.Require().Error(err, "insufficient coins") + + err = keeper.DeferredBurnCoins(ctx, authtypes.Burner, initCoins) + suite.Require().NoError(err) + supplyAfterBurn, _, err := keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) + + suite.Require().NoError(err) + + suite.Require().Equal(initCoins.String(), getCoinsByName(ctx, keeper, authKeeper, authtypes.Burner).String()) + keeper.WriteDeferredOperations(ctx) + suite.Require().Equal(sdk.NewCoins().String(), getCoinsByName(ctx, keeper, authKeeper, authtypes.Burner).String()) + + suite.Require().Equal(supplyAfterInflation.Sub(initCoins), supplyAfterBurn) + + // test same functionality on module account with multiple permissions + suite. + Require(). + NoError(keeper.DeferredMintCoins(ctx, authtypes.Minter, initCoins)) + + supplyAfterInflation, _, err = keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) + suite.Require().NoError(err) + suite.Require().NoError(keeper.SendCoins(ctx, authtypes.NewModuleAddress(authtypes.Minter), multiPermAcc.GetAddress(), initCoins)) + authKeeper.SetModuleAccount(ctx, multiPermAcc) + + err = keeper.DeferredBurnCoins(ctx, multiPermAcc.GetName(), initCoins) + supplyAfterBurn, _, err = keeper.GetPaginatedTotalSupply(ctx, &query.PageRequest{}) + suite.Require().NoError(err) + suite.Require().NoError(err) + + suite.Require().Equal(initCoins.String(), getCoinsByName(ctx, keeper, authKeeper, multiPermAcc.GetName()).String()) + keeper.WriteDeferredOperations(ctx) + suite.Require().Equal(sdk.NewCoins().String(), getCoinsByName(ctx, keeper, authKeeper, multiPermAcc.GetName()).String()) + suite.Require().Equal(supplyAfterInflation.Sub(initCoins), supplyAfterBurn) +} + func (suite *IntegrationTestSuite) TestSendCoinsNewAccount() { app, ctx := suite.app, suite.ctx balances := sdk.NewCoins(newFooCoin(100), newBarCoin(50))