2018-01-12 11:49:53 -08:00
|
|
|
package bank
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
2018-01-12 12:03:23 -08:00
|
|
|
sdk "github.com/cosmos/cosmos-sdk/types"
|
2018-01-12 11:49:53 -08:00
|
|
|
crypto "github.com/tendermint/go-crypto"
|
|
|
|
)
|
|
|
|
|
2018-01-22 05:44:24 -08:00
|
|
|
// CoinMapper manages transfers between accounts
|
|
|
|
type CoinMapper struct {
|
|
|
|
am sdk.AccountMapper
|
2018-01-12 11:49:53 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// SubtractCoins subtracts amt from the coins at the addr.
|
2018-01-22 05:44:24 -08:00
|
|
|
func (cm CoinMapper) SubtractCoins(ctx sdk.Context, addr crypto.Address, amt sdk.Coins) (sdk.Coins, error) {
|
|
|
|
acc := cm.am.GetAccount(ctx, addr)
|
2018-01-12 14:30:02 -08:00
|
|
|
if acc == nil {
|
2018-01-12 11:49:53 -08:00
|
|
|
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)
|
2018-01-22 05:44:24 -08:00
|
|
|
cm.am.SetAccount(ctx, acc)
|
2018-01-12 11:49:53 -08:00
|
|
|
return newCoins, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddCoins adds amt to the coins at the addr.
|
2018-01-22 05:44:24 -08:00
|
|
|
func (cm CoinMapper) AddCoins(ctx sdk.Context, addr crypto.Address, amt sdk.Coins) (sdk.Coins, error) {
|
|
|
|
acc := cm.am.GetAccount(ctx, addr)
|
2018-01-12 14:30:02 -08:00
|
|
|
if acc == nil {
|
2018-01-22 05:44:24 -08:00
|
|
|
acc = cm.am.NewAccountWithAddress(ctx, addr)
|
2018-01-12 11:49:53 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
coins := acc.GetCoins()
|
|
|
|
newCoins := coins.Plus(amt)
|
|
|
|
|
|
|
|
acc.SetCoins(newCoins)
|
2018-01-22 05:44:24 -08:00
|
|
|
cm.am.SetAccount(ctx, acc)
|
2018-01-12 11:49:53 -08:00
|
|
|
return newCoins, nil
|
|
|
|
}
|