Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: refine payment module #129

Merged
merged 2 commits into from
Mar 23, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion proto/greenfield/payment/base.proto
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import "gogoproto/gogo.proto";
option go_package = "github.com/bnb-chain/greenfield/x/payment/types";

// OutFlow defines the accumulative outflow stream rate in BNB
// from a stream account or a bucket to a SP
// from a stream account to a Storage Provider
message OutFlow {
// stream account address who receives the flow, usually SP(service provider)
string to_address = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
Expand All @@ -19,9 +19,14 @@ message OutFlow {
];
}

// StreamAccountStatus defines the status of a stream account
enum StreamAccountStatus {
option (gogoproto.goproto_enum_prefix) = false;

// STREAM_ACCOUNT_STATUS_ACTIVE defines the active status of a stream account.
STREAM_ACCOUNT_STATUS_ACTIVE = 0;
// STREAM_ACCOUNT_STATUS_FROZEN defines the frozen status of a stream account.
// A frozen stream account cannot be used as payment address for buckets.
// It can be unfrozen by depositing more BNB to the stream account.
STREAM_ACCOUNT_STATUS_FROZEN = 1;
}
2 changes: 0 additions & 2 deletions proto/greenfield/payment/params.proto
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ option go_package = "github.com/bnb-chain/greenfield/x/payment/types";

// Params defines the parameters for the module.
message Params {
option (gogoproto.goproto_stringer) = false;

// Time duration which the buffer balance need to be reserved for NetOutFlow e.g. 6 month
uint64 reserve_time = 1 [(gogoproto.moretags) = "yaml:\"reserve_time\""];
// The maximum number of payment accounts that can be created by one user
Expand Down
9 changes: 2 additions & 7 deletions x/payment/keeper/grpc_query_get_payment_accounts_by_owner.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ package keeper

import (
"context"
"encoding/binary"

sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/address"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"

Expand All @@ -28,14 +26,11 @@ func (k Keeper) GetPaymentAccountsByOwner(goCtx context.Context, req *types.Quer
return nil, status.Error(codes.NotFound, "not found")
}
count := countRecord.Count
user := sdk.MustAccAddressFromHex(req.Owner)
var paymentAccounts []string
var i uint64
for i = 0; i < count; i++ {
b := make([]byte, 8)
binary.LittleEndian.PutUint64(b, i)
paymentAccount := sdk.AccAddress(address.Derive(user.Bytes(), b)).String()
paymentAccounts = append(paymentAccounts, paymentAccount)
paymentAccount := k.DerivePaymentAccountAddress(owner, i)
paymentAccounts = append(paymentAccounts, paymentAccount.String())
}

return &types.QueryGetPaymentAccountsByOwnerResponse{
Expand Down
20 changes: 7 additions & 13 deletions x/payment/keeper/msg_server_create_payment_account.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,31 @@ package keeper

import (
"context"
"encoding/binary"

errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/address"

"github.com/bnb-chain/greenfield/x/payment/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)

func (k msgServer) CreatePaymentAccount(goCtx context.Context, msg *types.MsgCreatePaymentAccount) (*types.MsgCreatePaymentAccountResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)

// get current count
creator := sdk.MustAccAddressFromHex(msg.Creator)
countRecord, _ := k.Keeper.GetPaymentAccountCount(ctx, creator)
countRecord, _ := k.GetPaymentAccountCount(ctx, creator)
count := countRecord.Count
// get payment account count limit
params := k.Keeper.GetParams(ctx)
params := k.GetParams(ctx)
if count >= params.PaymentAccountCountLimit {
return nil, errorsmod.Wrapf(types.ErrReachPaymentAccountLimit, "current count: %d", count)
return nil, errorsmod.Wrapf(types.ErrReachPaymentAccountLimit, "current count: %d, limit: %d", count, params.PaymentAccountCountLimit)
}
// calculate the addr
b := make([]byte, 8)
binary.LittleEndian.PutUint64(b, count)
paymentAccountAddr := sdk.AccAddress(address.Derive(creator.Bytes(), b)).String()
paymentAccountAddr := k.DerivePaymentAccountAddress(creator, count).String()
newCount := count + 1
k.Keeper.SetPaymentAccountCount(ctx, &types.PaymentAccountCount{
k.SetPaymentAccountCount(ctx, &types.PaymentAccountCount{
Owner: msg.Creator,
Count: newCount,
})
k.Keeper.SetPaymentAccount(ctx, &types.PaymentAccount{
k.SetPaymentAccount(ctx, &types.PaymentAccount{
Addr: paymentAccountAddr,
Owner: msg.Creator,
Refundable: true,
Expand Down
3 changes: 2 additions & 1 deletion x/payment/keeper/msg_server_withdraw.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,15 @@ func (k msgServer) Withdraw(goCtx context.Context, msg *types.MsgWithdraw) (*typ
}
change := types.NewDefaultStreamRecordChangeWithAddr(from).WithStaticBalanceChange(msg.Amount.Neg())
err := k.UpdateStreamRecord(ctx, streamRecord, change, false)
k.SetStreamRecord(ctx, streamRecord)
if err != nil {
return nil, err
}
if streamRecord.StaticBalance.IsNegative() {
return nil, errors.Wrapf(types.ErrInsufficientBalance, "static balance: %s after withdraw", streamRecord.StaticBalance)
}
// bank transfer
creator, _ := sdk.AccAddressFromHexUnsafe(msg.Creator)
creator := sdk.MustAccAddressFromHex(msg.Creator)
coins := sdk.NewCoins(sdk.NewCoin(k.GetParams(ctx).FeeDenom, msg.Amount))
err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, creator, coins)
if err != nil {
Expand Down
9 changes: 9 additions & 0 deletions x/payment/keeper/payment_account.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package keeper

import (
"encoding/binary"

"github.com/cosmos/cosmos-sdk/store/prefix"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/address"

"github.com/bnb-chain/greenfield/x/payment/types"
)
Expand Down Expand Up @@ -65,3 +68,9 @@ func (k Keeper) IsPaymentAccountOwner(ctx sdk.Context, addr, owner sdk.AccAddres
paymentAccount, _ := k.GetPaymentAccount(ctx, addr)
return paymentAccount.Owner == owner.String()
}

func (k Keeper) DerivePaymentAccountAddress(owner sdk.AccAddress, index uint64) sdk.AccAddress {
b := make([]byte, 8)
binary.LittleEndian.PutUint64(b, index)
return address.Derive(owner.Bytes(), b)[:sdk.EthAddressLength]
}
7 changes: 6 additions & 1 deletion x/payment/types/base.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions x/payment/types/message_deposit.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,12 @@ func (msg *MsgDeposit) ValidateBasic() error {
if err != nil {
return errors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err)
}
_, err = sdk.AccAddressFromHexUnsafe(msg.To)
if err != nil {
return errors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid to address (%s)", err)
}
if msg.Amount.IsNil() || !msg.Amount.IsPositive() {
return errors.Wrapf(sdkerrors.ErrInvalidCoins, "invalid amount (%s)", msg.Amount)
}
return nil
}
4 changes: 4 additions & 0 deletions x/payment/types/message_disable_refund.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,9 @@ func (msg *MsgDisableRefund) ValidateBasic() error {
if err != nil {
return errors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err)
}
_, err = sdk.AccAddressFromHexUnsafe(msg.Addr)
if err != nil {
return errors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid payment address (%s)", err)
}
return nil
}
7 changes: 7 additions & 0 deletions x/payment/types/message_withdraw.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,12 @@ func (msg *MsgWithdraw) ValidateBasic() error {
if err != nil {
return errors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err)
}
_, err = sdk.AccAddressFromHexUnsafe(msg.From)
if err != nil {
return errors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid from address (%s)", err)
}
if msg.Amount.IsNil() || !msg.Amount.IsPositive() {
return errors.Wrapf(sdkerrors.ErrInvalidCoins, "invalid amount (%s)", msg.Amount)
}
return nil
}
29 changes: 12 additions & 17 deletions x/payment/types/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"fmt"

paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
"gopkg.in/yaml.v2"
)

var _ paramtypes.ParamSet = (*Params)(nil)
Expand Down Expand Up @@ -91,21 +90,16 @@ func (p Params) Validate() error {
return nil
}

// String implements the Stringer interface.
func (p Params) String() string {
out, _ := yaml.Marshal(p)
return string(out)
}

// validateReserveTime validates the ReserveTime param
func validateReserveTime(v interface{}) error {
reserveTime, ok := v.(uint64)
if !ok {
return fmt.Errorf("invalid parameter type: %T", v)
}

// TODO implement validation
_ = reserveTime
if reserveTime <= 0 {
return fmt.Errorf("reserve time must be positive")
}

return nil
}
Expand All @@ -117,9 +111,9 @@ func validateForcedSettleTime(v interface{}) error {
return fmt.Errorf("invalid parameter type: %T", v)
}

// TODO implement validation
_ = ForcedSettleTime

if ForcedSettleTime <= 0 {
return fmt.Errorf("forced settle time must be positive")
}
return nil
}

Expand All @@ -130,8 +124,9 @@ func validatePaymentAccountCountLimit(v interface{}) error {
return fmt.Errorf("invalid parameter type: %T", v)
}

// TODO implement validation
_ = paymentAccountCountLimit
if paymentAccountCountLimit <= 0 {
return fmt.Errorf("payment account count limit must be positive")
}

return nil
}
Expand All @@ -143,8 +138,9 @@ func validateMaxAutoForceSettleNum(v interface{}) error {
return fmt.Errorf("invalid parameter type: %T", v)
}

// TODO implement validation
_ = maxAutoForceSettleNum
if maxAutoForceSettleNum <= 0 {
return fmt.Errorf("max auto force settle num must be positive")
}

return nil
}
Expand All @@ -156,7 +152,6 @@ func validateFeeDenom(v interface{}) error {
return fmt.Errorf("invalid parameter type: %T", v)
}

// TODO implement validation
_ = feeDenom

return nil
Expand Down
55 changes: 28 additions & 27 deletions x/payment/types/params.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion x/permission/types/common.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.