cosmos-sdk/x/bank/store.go

51 lines
1.2 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"
)
// CoinStore manages transfers between accounts
type CoinStore struct {
2018-01-12 12:03:23 -08:00
store sdk.AccountStore
}
// SubtractCoins subtracts amt from the coins at the addr.
2018-01-12 12:03:23 -08:00
func (cs CoinStore) SubtractCoins(ctx sdk.Context, addr crypto.Address, amt sdk.Coins) (sdk.Coins, error) {
acc, err := cs.store.GetAccount(ctx, addr)
if err != nil {
return amt, err
} else if acc == nil {
return amt, fmt.Errorf("Sending account (%s) does not exist", addr)
}
coins := acc.GetCoins()
newCoins := coins.Minus(amt)
if !newCoins.IsNotNegative() {
return amt, ErrInsufficientCoins(fmt.Sprintf("%s < %s", coins, amt))
}
acc.SetCoins(newCoins)
cs.store.SetAccount(ctx, acc)
return newCoins, nil
}
// AddCoins adds amt to the coins at the addr.
2018-01-12 12:03:23 -08:00
func (cs CoinStore) AddCoins(ctx sdk.Context, addr crypto.Address, amt sdk.Coins) (sdk.Coins, error) {
acc, err := cs.store.GetAccount(ctx, addr)
if err != nil {
return amt, err
} else if acc == nil {
acc = cs.store.NewAccountWithAddress(ctx, addr)
}
coins := acc.GetCoins()
newCoins := coins.Plus(amt)
acc.SetCoins(newCoins)
cs.store.SetAccount(ctx, acc)
return newCoins, nil
}