cosmos-sdk/modules/fee/handler.go

82 lines
2.0 KiB
Go
Raw Normal View History

package fee
2017-06-01 11:01:19 -07:00
import (
"github.com/tendermint/basecoin"
"github.com/tendermint/basecoin/errors"
"github.com/tendermint/basecoin/stack"
2017-06-01 11:01:19 -07:00
"github.com/tendermint/basecoin/types"
)
const (
NameFee = "fee"
)
type AccountChecker interface {
// Get amount checks the current amount
GetAmount(store types.KVStore, addr basecoin.Actor) (types.Coins, error)
2017-06-01 11:01:19 -07:00
// ChangeAmount modifies the balance by the given amount and returns the new balance
// always returns an error if leading to negative balance
ChangeAmount(store types.KVStore, addr basecoin.Actor, coins types.Coins) (types.Coins, error)
2017-06-01 11:01:19 -07:00
}
type SimpleFeeHandler struct {
AccountChecker
MinFee types.Coins
stack.PassOption
2017-06-01 11:01:19 -07:00
}
func (_ SimpleFeeHandler) Name() string {
return NameFee
}
var _ stack.Middleware = SimpleFeeHandler{}
// Yes, I know refactor a bit... really too late already
2017-06-01 11:01:19 -07:00
2017-06-27 10:40:48 -07:00
func (h SimpleFeeHandler) CheckTx(ctx basecoin.Context, store types.KVStore, tx basecoin.Tx, next basecoin.Checker) (res basecoin.Result, err error) {
feeTx, ok := tx.Unwrap().(*Fee)
2017-06-01 11:01:19 -07:00
if !ok {
2017-07-03 05:50:33 -07:00
return res, errors.ErrInvalidFormat(tx)
}
fees := types.Coins{feeTx.Fee}
if !fees.IsGTE(h.MinFee) {
2017-07-03 05:50:33 -07:00
return res, ErrInsufficientFees()
}
if !ctx.HasPermission(feeTx.Payer) {
2017-07-03 05:50:33 -07:00
return res, errors.ErrUnauthorized()
2017-06-01 11:01:19 -07:00
}
_, err = h.ChangeAmount(store, feeTx.Payer, fees.Negative())
2017-06-01 11:01:19 -07:00
if err != nil {
return res, err
}
return basecoin.Result{Log: "Valid tx"}, nil
2017-06-01 11:01:19 -07:00
}
2017-06-27 10:40:48 -07:00
func (h SimpleFeeHandler) DeliverTx(ctx basecoin.Context, store types.KVStore, tx basecoin.Tx, next basecoin.Deliver) (res basecoin.Result, err error) {
feeTx, ok := tx.Unwrap().(*Fee)
2017-06-01 11:01:19 -07:00
if !ok {
2017-07-03 05:50:33 -07:00
return res, errors.ErrInvalidFormat(tx)
}
fees := types.Coins{feeTx.Fee}
if !fees.IsGTE(h.MinFee) {
2017-07-03 05:50:33 -07:00
return res, ErrInsufficientFees()
}
if !ctx.HasPermission(feeTx.Payer) {
2017-07-03 05:50:33 -07:00
return res, errors.ErrUnauthorized()
2017-06-01 11:01:19 -07:00
}
_, err = h.ChangeAmount(store, feeTx.Payer, fees.Negative())
2017-06-01 11:01:19 -07:00
if err != nil {
return res, err
}
2017-06-27 10:40:48 -07:00
return next.DeliverTx(ctx, store, feeTx.Next())
2017-06-01 11:01:19 -07:00
}