Skip to content

Commit

Permalink
refactor: update contract and user usecases
Browse files Browse the repository at this point in the history
  • Loading branch information
henriquemarlon committed Nov 19, 2024
1 parent 685cd3f commit 0e24701
Show file tree
Hide file tree
Showing 14 changed files with 583 additions and 314 deletions.
17 changes: 9 additions & 8 deletions cmd/tribes-rollup/root/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,21 +113,22 @@ func run(cmd *cobra.Command, args []string) {
func NewDApp(ah *AdvanceHandlers, ih *InspectHandlers, ms *Middlewares) *router.Router {
r := router.NewRouter()

r.HandleAdvance("createContract", ms.RBAC.Middleware(ah.ContractAdvanceHandlers.CreateContractHandler, "admin"))
r.HandleAdvance("updateContract", ms.RBAC.Middleware(ah.ContractAdvanceHandlers.UpdateContractHandler, "admin"))
r.HandleAdvance("deleteContract", ms.RBAC.Middleware(ah.ContractAdvanceHandlers.DeleteContractHandler, "admin"))
r.HandleAdvance("createContract", ms.RBAC.Middleware(ah.ContractAdvanceHandlers.CreateContractHandler, []string{"admin"}))
r.HandleAdvance("updateContract", ms.RBAC.Middleware(ah.ContractAdvanceHandlers.UpdateContractHandler, []string{"admin"}))
r.HandleAdvance("deleteContract", ms.RBAC.Middleware(ah.ContractAdvanceHandlers.DeleteContractHandler, []string{"admin"}))

r.HandleAdvance("createOrder", ah.OrderAdvanceHandlers.CreateOrderHandler)

r.HandleAdvance("createCrowdfunding", ms.TLSN.Middleware(ah.CrowdfundingAdvanceHandlers.CreateCrowdfundingHandler))
r.HandleAdvance("closeCrowdfunding", ah.CrowdfundingAdvanceHandlers.CloseCrowdfundingHandler)
r.HandleAdvance("settleCrowdfunding", ms.RBAC.Middleware(ah.CrowdfundingAdvanceHandlers.SettleCrowdfundingHandler, "creator"))
r.HandleAdvance("settleCrowdfunding", ms.RBAC.Middleware(ah.CrowdfundingAdvanceHandlers.SettleCrowdfundingHandler, []string{"creator"}))

r.HandleAdvance("withdraw", ah.UserAdvanceHandlers.WithdrawHandler)
r.HandleAdvance("withdrawApp", ms.RBAC.Middleware(ah.UserAdvanceHandlers.WithdrawAppHandler, "admin"))
// r.HandleAdvance("withdraw", ah.UserAdvanceHandlers.WithdrawHandler)
// r.HandleAdvance("withdrawApp", ms.RBAC.Middleware(ah.UserAdvanceHandlers.WithdrawAppHandler, []string{"admin"}))

r.HandleAdvance("createUser", ms.RBAC.Middleware(ah.UserAdvanceHandlers.CreateUserHandler, "admin"))
r.HandleAdvance("deleteUser", ms.RBAC.Middleware(ah.UserAdvanceHandlers.DeleteUserHandler, "admin"))
r.HandleAdvance("createUser", ms.RBAC.Middleware(ah.UserAdvanceHandlers.CreateUserHandler, []string{"admin"}))
r.HandleAdvance("updateUser", ms.RBAC.Middleware(ah.UserAdvanceHandlers.UpdateUserHandler, []string{"admin"}))
r.HandleAdvance("deleteUser", ms.RBAC.Middleware(ah.UserAdvanceHandlers.DeleteUserHandler, []string{"admin"}))

r.HandleInspect("crowdfunding", ih.CrowdfundingInspectHandlers.FindAllCrowdfundingsHandler)
r.HandleInspect("crowdfunding/{id}", ih.CrowdfundingInspectHandlers.FindCrowdfundingByIdHandler)
Expand Down
388 changes: 220 additions & 168 deletions coverage.md

Large diffs are not rendered by default.

9 changes: 5 additions & 4 deletions internal/domain/entity/crowdfunding.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@ var (
type CrowdfundingState string

const (
CrowdfundingStateOngoing CrowdfundingState = "ongoing"
CrowdfundingStateClosed CrowdfundingState = "closed"
CrowdfundingStateCanceled CrowdfundingState = "canceled"
CrowdfundingStateSettled CrowdfundingState = "settled"
CrowdfundingStateUnderReview CrowdfundingState = "under_review"
CrowdfundingStateClosed CrowdfundingState = "closed"
CrowdfundingStateOngoing CrowdfundingState = "ongoing"
CrowdfundingStateCanceled CrowdfundingState = "canceled"
CrowdfundingStateSettled CrowdfundingState = "settled"
)

type CrowdfundingRepository interface {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package advance_handler

import (
"encoding/json"
"fmt"

"github.com/rollmelette/rollmelette"
"github.com/tribeshq/tribes/internal/domain/entity"
"github.com/tribeshq/tribes/internal/usecase/crowdfunding_usecase"
Expand Down Expand Up @@ -34,10 +36,23 @@ func (h *CrowdfundingAdvanceHandlers) CreateCrowdfundingHandler(env rollmelette.
return err
}
createCrowdfunding := crowdfunding_usecase.NewCreateCrowdfundingUseCase(h.UserRepository, h.CrowdfundingRepository)
res, err := createCrowdfunding.Execute(input, metadata)
res, err := createCrowdfunding.Execute(input, deposit, metadata)
if err != nil {
return err
}
// TODO: remove this check when update to V2
appAddress, isSet := env.AppAddress()
if !isSet {
return fmt.Errorf("no application address defined yet, contact the Tribes support")
}
if err := env.ERC20Transfer(
deposit.(*rollmelette.ERC20Deposit).Token,
metadata.MsgSender,
appAddress,
deposit.(*rollmelette.ERC20Deposit).Amount,
); err != nil {
return err
}
crowdfunding, err := json.Marshal(res)
if err != nil {
return err
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@ import (
// "encoding/json"
// "fmt"

"encoding/json"

"github.com/rollmelette/rollmelette"
"github.com/tribeshq/tribes/internal/domain/entity"
"github.com/tribeshq/tribes/internal/usecase/order_usecase"
// "github.com/tribeshq/tribes/internal/usecase/contract_usecase"
// "github.com/tribeshq/tribes/internal/usecase/order_usecase"
// "github.com/tribeshq/tribes/internal/usecase/user_usecase"
Expand All @@ -28,40 +31,19 @@ func NewOrderAdvanceHandlers(orderRepository entity.OrderRepository, userReposit
}

func (h *OrderAdvanceHandlers) CreateOrderHandler(env rollmelette.Env, metadata rollmelette.Metadata, deposit rollmelette.Deposit, payload []byte) error {
// switch deposit := deposit.(type) {
// case *rollmelette.ERC20Deposit:
// var input order_usecase.CreateOrderInputDTO
// if err := json.Unmarshal(payload, &input); err != nil {
// return err
// }
// createOrder := order_usecase.NewCreateOrderUseCase(h.OrderRepository, h.ContractRepository, h.CrowdfundingRepository)
// res, err := createOrder.Execute(&input, deposit, metadata)
// if err != nil {
// return err
// }

// findContractBySymbol := contract_usecase.NewFindContractBySymbolUseCase(h.ContractRepository)
// stablecoin, err := findContractBySymbol.Execute(&contract_usecase.FindContractBySymbolInputDTO{Symbol: "STABLECOIN"})
// if err != nil {
// return err
// }
// findUserByRole := user_usecase.NewFindUserByRoleUseCase(h.UserRepository)
// crowdfundingeer, err := findUserByRole.Execute(&user_usecase.FindUserByRoleInputDTO{Role: "crowdfundingeer"})
// if err != nil {
// return err
// }

// if err := env.ERC20Transfer(stablecoin.Address, res.Investor, crowdfundingeer.Address, res.Amount.ToBig()); err != nil {
// return err
// }
// order, err := json.Marshal(res)
// if err != nil {
// return err
// }
// env.Notice(append([]byte("order created - "), order...))
// return nil
// default:
// return fmt.Errorf("unsupported deposit type")
// }
var input order_usecase.CreateOrderInputDTO
if err := json.Unmarshal(payload, &input); err != nil {
return err
}
createOrder := order_usecase.NewCreateOrderUseCase(h.OrderRepository, h.ContractRepository, h.CrowdfundingRepository)
res, err := createOrder.Execute(&input, deposit, metadata)
if err != nil {
return err
}
order, err := json.Marshal(res)
if err != nil {
return err
}
env.Notice(append([]byte("order created - "), order...))
return nil
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (

"github.com/rollmelette/rollmelette"
"github.com/tribeshq/tribes/internal/domain/entity"
"github.com/tribeshq/tribes/internal/usecase/contract_usecase"
"github.com/tribeshq/tribes/internal/usecase/user_usecase"
)

Expand Down Expand Up @@ -41,6 +40,20 @@ func (h *UserAdvanceHandlers) CreateUserHandler(env rollmelette.Env, metadata ro
}

func (h *UserAdvanceHandlers) UpdateUserHandler(env rollmelette.Env, metadata rollmelette.Metadata, deposit rollmelette.Deposit, payload []byte) error {
var input user_usecase.UpdateUserInputDTO
if err := json.Unmarshal(payload, &input); err != nil {
return err
}
updateUser := user_usecase.NewUpdateUserUseCase(h.UserRepository)
res, err := updateUser.Execute(&input, metadata)
if err != nil {
return err
}
user, err := json.Marshal(res)
if err != nil {
return err
}
env.Notice(append([]byte("user updated - "), user...))
return nil
}

Expand All @@ -62,45 +75,45 @@ func (h *UserAdvanceHandlers) DeleteUserHandler(env rollmelette.Env, metadata ro
return nil
}

func (h *UserAdvanceHandlers) WithdrawHandler(env rollmelette.Env, metadata rollmelette.Metadata, deposit rollmelette.Deposit, payload []byte) error {
findContractBySymbol := contract_usecase.NewFindContractBySymbolUseCase(h.ContractRepository)
stablecoin, err := findContractBySymbol.Execute(&contract_usecase.FindContractBySymbolInputDTO{Symbol: "STABLECOIN"})
if err != nil {
return err
}
stablecoinBalance := env.ERC20BalanceOf(stablecoin.Address, metadata.MsgSender)
if stablecoinBalance.Sign() == 0 {
return fmt.Errorf("no balance of %v to withdraw", stablecoin.Symbol)
}
stablecoinVoucherIndex, err := env.ERC20Withdraw(stablecoin.Address, metadata.MsgSender, stablecoinBalance)
if err != nil {
return err
}
env.Notice([]byte(fmt.Sprintf("withdrawn %v of %v from %v with voucher index: %v", stablecoin.Symbol, stablecoinBalance, metadata.MsgSender, stablecoinVoucherIndex)))
return nil
}
// func (h *UserAdvanceHandlers) WithdrawHandler(env rollmelette.Env, metadata rollmelette.Metadata, deposit rollmelette.Deposit, payload []byte) error {
// findContractBySymbol := contract_usecase.NewFindContractBySymbolUseCase(h.ContractRepository)
// stablecoin, err := findContractBySymbol.Execute(&contract_usecase.FindContractBySymbolInputDTO{Symbol: "STABLECOIN"})
// if err != nil {
// return err
// }
// stablecoinBalance := env.ERC20BalanceOf(stablecoin.Address, metadata.MsgSender)
// if stablecoinBalance.Sign() == 0 {
// return fmt.Errorf("no balance of %v to withdraw", stablecoin.Symbol)
// }
// stablecoinVoucherIndex, err := env.ERC20Withdraw(stablecoin.Address, metadata.MsgSender, stablecoinBalance)
// if err != nil {
// return err
// }
// env.Notice([]byte(fmt.Sprintf("withdrawn %v of %v from %v with voucher index: %v", stablecoin.Symbol, stablecoinBalance, metadata.MsgSender, stablecoinVoucherIndex)))
// return nil
// }

func (h *UserAdvanceHandlers) WithdrawAppHandler(env rollmelette.Env, metadata rollmelette.Metadata, deposit rollmelette.Deposit, payload []byte) error {
findContractBySymbol := contract_usecase.NewFindContractBySymbolUseCase(h.ContractRepository)
stablecoin, err := findContractBySymbol.Execute(&contract_usecase.FindContractBySymbolInputDTO{Symbol: "STABLECOIN"})
if err != nil {
return err
}
application, isDefined := env.AppAddress()
if !isDefined {
return fmt.Errorf("no application address defined yet, contact the Tribes support")
}
stablecoinBalance := env.ERC20BalanceOf(stablecoin.Address, application)
if stablecoinBalance.Sign() == 0 {
return fmt.Errorf("no balance of %v to withdraw", stablecoin.Symbol)
}
if err := env.ERC20Transfer(stablecoin.Address, application, metadata.MsgSender, stablecoinBalance); err != nil {
return err
}
stablecoinVoucherIndex, err := env.ERC20Withdraw(stablecoin.Address, metadata.MsgSender, stablecoinBalance)
if err != nil {
return err
}
env.Notice([]byte(fmt.Sprintf("withdrawn %v of %v from %v with voucher index: %v", stablecoin.Symbol, stablecoinBalance, metadata.MsgSender, stablecoinVoucherIndex)))
return nil
}
// func (h *UserAdvanceHandlers) WithdrawAppHandler(env rollmelette.Env, metadata rollmelette.Metadata, deposit rollmelette.Deposit, payload []byte) error {
// findContractBySymbol := contract_usecase.NewFindContractBySymbolUseCase(h.ContractRepository)
// stablecoin, err := findContractBySymbol.Execute(&contract_usecase.FindContractBySymbolInputDTO{Symbol: "STABLECOIN"})
// if err != nil {
// return err
// }
// application, isDefined := env.AppAddress()
// if !isDefined {
// return fmt.Errorf("no application address defined yet, contact the Tribes support")
// }
// stablecoinBalance := env.ERC20BalanceOf(stablecoin.Address, application)
// if stablecoinBalance.Sign() == 0 {
// return fmt.Errorf("no balance of %v to withdraw", stablecoin.Symbol)
// }
// if err := env.ERC20Transfer(stablecoin.Address, application, metadata.MsgSender, stablecoinBalance); err != nil {
// return err
// }
// stablecoinVoucherIndex, err := env.ERC20Withdraw(stablecoin.Address, metadata.MsgSender, stablecoinBalance)
// if err != nil {
// return err
// }
// env.Notice([]byte(fmt.Sprintf("withdrawn %v of %v from %v with voucher index: %v", stablecoin.Symbol, stablecoinBalance, metadata.MsgSender, stablecoinVoucherIndex)))
// return nil
// }
8 changes: 5 additions & 3 deletions internal/infra/cartesi/middleware/rbac.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func NewRBACMiddleware(userRepository entity.UserRepository) *RBACMiddleware {
}
}

func (m *RBACMiddleware) Middleware(handlerFunc router.AdvanceHandlerFunc, role string) router.AdvanceHandlerFunc {
func (m *RBACMiddleware) Middleware(handlerFunc router.AdvanceHandlerFunc, role []string) router.AdvanceHandlerFunc {
return func(env rollmelette.Env, metadata rollmelette.Metadata, deposit rollmelette.Deposit, payload []byte) error {
findUserByAddress := user_usecase.NewFindUserByAddressUseCase(m.UserRepository)
user, err := findUserByAddress.Execute(&user_usecase.FindUserByAddressInputDTO{
Expand All @@ -33,8 +33,10 @@ func (m *RBACMiddleware) Middleware(handlerFunc router.AdvanceHandlerFunc, role
}
return err
}
if user.Role != role && user.Role != "admin" {
return fmt.Errorf("user with address: %v don't have necessary permission: %v", user.Address, role)
for _, r := range role {
if user.Role != r {
return fmt.Errorf("user with address: %v don't have necessary permission", user.Address)
}
}
return handlerFunc(env, metadata, deposit, payload)
}
Expand Down
20 changes: 10 additions & 10 deletions internal/infra/repository/crowdfunding_repository_sqlite.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,8 @@ func (r *CrowdfundingRepositorySqlite) FindCrowdfundingsByInvestor(investor comm
err := r.Db.Raw(`
SELECT c.id, c.creator, c.debt_issued, c.max_interest_rate, c.state, c.expires_at, c.created_at, c.updated_at
FROM crowdfundings c
JOIN crowdfunding_investors ci ON c.id = ci.crowdfunding_id
WHERE ci.investor = ?
JOIN orders o ON c.id = o.crowdfunding_id
WHERE o.investor = ?
`, investor.String()).Scan(&results).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
Expand Down Expand Up @@ -226,14 +226,6 @@ func (r *CrowdfundingRepositorySqlite) FindCrowdfundingsByInvestor(investor comm
return crowdfundings, nil
}

func (r *CrowdfundingRepositorySqlite) CloseCrowdfunding(crowdfundingId uint) ([]*entity.Crowdfunding, error) {
return nil, nil
}

func (r *CrowdfundingRepositorySqlite) SettleCrowdfunding(crowdfundingId uint) ([]*entity.Crowdfunding, error) {
return nil, nil
}

func (r *CrowdfundingRepositorySqlite) UpdateCrowdfunding(input *entity.Crowdfunding) (*entity.Crowdfunding, error) {
var crowdfundingJSON map[string]interface{}
err := r.Db.Where("id = ?", input.Id).First(&crowdfundingJSON).Error
Expand Down Expand Up @@ -280,3 +272,11 @@ func (r *CrowdfundingRepositorySqlite) DeleteCrowdfunding(id uint) error {
}
return nil
}

func (r *CrowdfundingRepositorySqlite) CloseCrowdfunding(crowdfundingId uint) ([]*entity.Crowdfunding, error) {
return nil, nil
}

func (r *CrowdfundingRepositorySqlite) SettleCrowdfunding(crowdfundingId uint) ([]*entity.Crowdfunding, error) {
return nil, nil
}
12 changes: 9 additions & 3 deletions internal/infra/repository/order_repository_sqlite.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,9 +170,15 @@ func (r *OrderRepositorySqlite) UpdateOrder(input *entity.Order) (*entity.Order,
return nil, err
}

orderJSON["amount"] = input.Amount.String()
orderJSON["interest_rate"] = input.InterestRate.String()
orderJSON["state"] = input.State
if input.Amount.Sign() > 0 {
orderJSON["amount"] = input.Amount.String()
}
if input.InterestRate.Sign() > 0 {
orderJSON["interest_rate"] = input.InterestRate.String()
}
if input.State != "" {
orderJSON["state"] = input.State
}
orderJSON["updated_at"] = input.UpdatedAt

orderBytes, err := json.Marshal(orderJSON)
Expand Down
19 changes: 14 additions & 5 deletions internal/infra/repository/user_respository_sqlite.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,18 @@ func (r *UserRepositorySqlite) UpdateUser(input *entity.User) (*entity.User, err
return nil, err
}

userJSON["role"] = input.Role
userJSON["address"] = input.Address.String()
userJSON["investment_limit"] = input.InvestmentLimit.String()
userJSON["debt_issuance_limit"] = input.DebtIssuanceLimit.String()
if input.Role != "" {
userJSON["role"] = input.Role
}
if input.Address != (common.Address{}) {
userJSON["address"] = input.Address.String()
}
if input.InvestmentLimit != nil {
userJSON["investment_limit"] = input.InvestmentLimit.String()
}
if input.InvestmentLimit != nil {
userJSON["debt_issuance_limit"] = input.DebtIssuanceLimit.String()
}
userJSON["updated_at"] = input.UpdatedAt

userBytes, err := json.Marshal(userJSON)
Expand All @@ -129,13 +137,14 @@ func (r *UserRepositorySqlite) UpdateUser(input *entity.User) (*entity.User, err
return nil, err
}

res := r.Db.Save(userJSON)
res := r.Db.Save(&user)
if res.Error != nil {
return nil, fmt.Errorf("failed to update user: %w", res.Error)
}
return &user, nil
}


func (r *UserRepositorySqlite) DeleteUser(address common.Address) error {
res := r.Db.Delete(&entity.User{}, "address = ?", address.String())
if res.Error != nil {
Expand Down
Loading

0 comments on commit 0e24701

Please sign in to comment.