github.com/NpoolPlatform/chain-middleware@v0.0.0-20240228100535-eb1bcf896eb9/pkg/mw/app/coin/update.go (about) 1 package appcoin 2 3 import ( 4 "context" 5 "fmt" 6 7 "github.com/NpoolPlatform/chain-middleware/pkg/db" 8 "github.com/NpoolPlatform/chain-middleware/pkg/db/ent" 9 entappexrate "github.com/NpoolPlatform/chain-middleware/pkg/db/ent/exchangerate" 10 11 appcoincrud "github.com/NpoolPlatform/chain-middleware/pkg/crud/app/coin" 12 appexratecrud "github.com/NpoolPlatform/chain-middleware/pkg/crud/app/coin/exrate" 13 npool "github.com/NpoolPlatform/message/npool/chain/mw/v1/app/coin" 14 ) 15 16 type updateHandler struct { 17 *Handler 18 } 19 20 func (h *updateHandler) updateAppCoin(ctx context.Context, tx *ent.Tx) error { 21 info, err := appcoincrud.UpdateSet( 22 tx.AppCoin.UpdateOneID(*h.ID), 23 &appcoincrud.Req{ 24 Name: h.Name, 25 DisplayNames: h.DisplayNames, 26 Logo: h.Logo, 27 ForPay: h.ForPay, 28 ProductPage: h.ProductPage, 29 WithdrawAutoReviewAmount: h.WithdrawAutoReviewAmount, 30 DailyRewardAmount: h.DailyRewardAmount, 31 Disabled: h.Disabled, 32 Display: h.Display, 33 DisplayIndex: h.DisplayIndex, 34 MaxAmountPerWithdraw: h.MaxAmountPerWithdraw, 35 }, 36 ).Save(ctx) 37 if err != nil { 38 return err 39 } 40 41 h.AppID = &info.AppID 42 h.CoinTypeID = &info.CoinTypeID 43 44 return nil 45 } 46 47 func (h *updateHandler) updateExrate(ctx context.Context, tx *ent.Tx) error { 48 info, err := tx. 49 ExchangeRate. 50 Query(). 51 Where( 52 entappexrate.AppID(*h.AppID), 53 entappexrate.CoinTypeID(*h.CoinTypeID), 54 ). 55 ForUpdate(). 56 Only(ctx) 57 if err != nil { 58 if !ent.IsNotFound(err) { 59 return err 60 } 61 } 62 63 if info != nil { 64 if _, err := appexratecrud.UpdateSet( 65 info.Update(), 66 &appexratecrud.Req{ 67 MarketValue: h.MarketValue, 68 SettlePercent: h.SettlePercent, 69 SettleTips: h.SettleTips, 70 Setter: h.Setter, 71 }, 72 ).Save(ctx); err != nil { 73 return err 74 } 75 return nil 76 } 77 78 if _, err := appexratecrud.CreateSet( 79 tx.ExchangeRate.Create(), 80 &appexratecrud.Req{ 81 AppID: h.AppID, 82 CoinTypeID: h.CoinTypeID, 83 MarketValue: h.MarketValue, 84 SettlePercent: h.SettlePercent, 85 SettleTips: h.SettleTips, 86 Setter: h.Setter, 87 }, 88 ).Save(ctx); err != nil { 89 return err 90 } 91 return nil 92 } 93 94 func (h *Handler) UpdateCoin(ctx context.Context) (*npool.Coin, error) { 95 if h.ID == nil { 96 return nil, fmt.Errorf("invalid id") 97 } 98 99 handler := &updateHandler{ 100 Handler: h, 101 } 102 103 err := db.WithTx(ctx, func(_ctx context.Context, tx *ent.Tx) error { 104 if err := handler.updateAppCoin(_ctx, tx); err != nil { 105 return err 106 } 107 if err := handler.updateExrate(_ctx, tx); err != nil { 108 return err 109 } 110 return nil 111 }) 112 if err != nil { 113 return nil, err 114 } 115 116 return h.GetCoin(ctx) 117 }