cosmos-sdk/x/bank/mapper.go

47 lines
1.1 KiB
Go
Raw Normal View History

package bank
import (
"fmt"
2018-01-12 12:03:23 -08:00
sdk "github.com/cosmos/cosmos-sdk/types"
crypto "github.com/tendermint/go-crypto"
)
// CoinMapper manages transfers between accounts
type CoinMapper struct {
am sdk.AccountMapper
}
// SubtractCoins subtracts amt from the coins at the addr.
2018-01-26 06:22:56 -08:00
func (cm CoinMapper) SubtractCoins(ctx sdk.Context, addr crypto.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {
acc := cm.am.GetAccount(ctx, addr)
2018-01-12 14:30:02 -08:00
if acc == nil {
2018-01-26 06:22:56 -08:00
return amt, sdk.ErrUnrecognizedAddress(addr)
}
coins := acc.GetCoins()
newCoins := coins.Minus(amt)
if !newCoins.IsNotNegative() {
return amt, ErrInsufficientCoins(fmt.Sprintf("%s < %s", coins, amt))
}
acc.SetCoins(newCoins)
cm.am.SetAccount(ctx, acc)
return newCoins, nil
}
// AddCoins adds amt to the coins at the addr.
2018-01-26 06:22:56 -08:00
func (cm CoinMapper) AddCoins(ctx sdk.Context, addr crypto.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {
acc := cm.am.GetAccount(ctx, addr)
2018-01-12 14:30:02 -08:00
if acc == nil {
acc = cm.am.NewAccountWithAddress(ctx, addr)
}
coins := acc.GetCoins()
newCoins := coins.Plus(amt)
acc.SetCoins(newCoins)
cm.am.SetAccount(ctx, acc)
return newCoins, nil
}