Skip to content

Commit

Permalink
added logic to approve-loan message server and added custom error typ…
Browse files Browse the repository at this point in the history
…e called ErrWrongLoanState in x/loan/types/errors.go
  • Loading branch information
outsmartchad committed May 17, 2024
1 parent 44c0cba commit 4c0a46e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
32 changes: 28 additions & 4 deletions x/loan/keeper/msg_server_approve_loan.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,39 @@ import (
"context"

"loan/x/loan/types"
errorsmod "cosmossdk.io/errors"

sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)

func (k msgServer) ApproveLoan(goCtx context.Context, msg *types.MsgApproveLoan) (*types.MsgApproveLoanResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)

// TODO: Handling the message
_ = ctx

loan, found := k.GetLoan(ctx, msg.Id)
if !found{
// cannot find the loan in the blockchain
return nil, errorsmod.Wrapf(sdkerrors.ErrKeyNotFound, "key %d doesn't exist", msg.Id)
}
if loan.Borrower == msg.Creator{
// should not be the same one to lend and borrow
return nil, errorsmod.Wrap(sdkerrors.ErrConflict, "the borrower and the lender should not be the same one")
}
if loan.State != "requested"{
// check if the state is requested first
return nil, errorsmod.Wrapf(types.ErrWrongLoanState, "%v", loan.State)
}
lender, _ := sdk.AccAddressFromBech32(msg.Creator)
borrower, _ := sdk.AccAddressFromBech32(loan.Borrower)
amt, err := sdk.ParseCoinsNormalized(loan.Amount)
if err != nil{
return nil, errorsmod.Wrap(types.ErrWrongLoanState, "Cannot parse coins in loan amount")
}
err = k.bankKeeper.SendCoins(ctx, lender, borrower, amt)
if err != nil{
return nil, err
}
loan.Lender = msg.Creator
loan.State = "approved"
k.SetLoan(ctx, loan)
return &types.MsgApproveLoanResponse{}, nil
}
1 change: 1 addition & 0 deletions x/loan/types/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ import (
var (
ErrInvalidSigner = sdkerrors.Register(ModuleName, 1100, "expected gov account as only signer for proposal message")
ErrSample = sdkerrors.Register(ModuleName, 1101, "sample error")
ErrWrongLoanState = sdkerrors.Register(ModuleName, 2, "Wrong loan state")
)

0 comments on commit 4c0a46e

Please sign in to comment.