From 8bd990ce3c1f6c07ebfdb5cc10d251a23b555b1b Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Tue, 31 Oct 2023 14:38:52 +0800 Subject: [PATCH 01/67] dutch auction --- block_parser/block_parser.go | 1 + cmd/main.go | 5 +- dao/dao.go | 1 + dao/t_auction_order.go | 28 +++ http_server/api_code/monitor.go | 5 +- http_server/handle/account_detail.go | 27 ++- http_server/handle/auction_info.go | 345 +++++++++++++++++++++++++++ http_server/router.go | 11 +- tables/t_account_info.go | 6 + tables/t_auction_order.go | 40 ++++ timer/recycle_early.go | 1 + timer/timer.go | 1 + txtool/txtool.go | 1 + 13 files changed, 460 insertions(+), 12 deletions(-) create mode 100644 dao/t_auction_order.go create mode 100644 http_server/handle/auction_info.go create mode 100644 tables/t_auction_order.go diff --git a/block_parser/block_parser.go b/block_parser/block_parser.go index 0442c14c..d9313569 100644 --- a/block_parser/block_parser.go +++ b/block_parser/block_parser.go @@ -35,6 +35,7 @@ type BlockParser struct { } func (b *BlockParser) Run() error { + return nil b.registerTransactionHandle() currentBlockNumber, err := b.DasCore.Client().GetTipBlockNumber(b.Ctx) if err != nil { diff --git a/cmd/main.go b/cmd/main.go index e938c7f1..abbdbb70 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -7,7 +7,6 @@ import ( "das_register_server/config" "das_register_server/dao" "das_register_server/http_server" - "das_register_server/prometheus" "das_register_server/timer" "das_register_server/txtool" "das_register_server/unipay" @@ -145,8 +144,8 @@ func runServer(ctx *cli.Context) error { txTool.Run() // prometheus - prometheus.Init() - prometheus.Tools.Run() + //prometheus.Init() + //prometheus.Tools.Run() // block parser bp := block_parser.BlockParser{ diff --git a/dao/dao.go b/dao/dao.go index 07800c7e..c6c782d3 100644 --- a/dao/dao.go +++ b/dao/dao.go @@ -34,6 +34,7 @@ func NewGormDB(dbMysql, parserMysql config.DbMysql) (*DbDao, error) { &tables.TableDasOrderTxInfo{}, &tables.TableRegisterPendingInfo{}, &tables.TableCoupon{}, + &tables.TableAuctionOrder{}, ); err != nil { return nil, err } diff --git a/dao/t_auction_order.go b/dao/t_auction_order.go new file mode 100644 index 00000000..251e2ffd --- /dev/null +++ b/dao/t_auction_order.go @@ -0,0 +1,28 @@ +package dao + +import ( + "das_register_server/tables" + "fmt" + "github.com/dotbitHQ/das-lib/common" +) + +func (d *DbDao) GetPendingAuctionOrder(algorithmId common.DasAlgorithmId, subAlgithmId common.DasSubAlgorithmId, addr string) (list []tables.TableAuctionOrder, err error) { + sql := fmt.Sprintf(`SELECT o.id,o.account,o.outpoint,o.basic_price,o.premium_price,o.order_id,p.status FROM %s o LEFT JOIN %s p ON o.outpoint=p.outpoint WHERE o.algorithm_id = %d and o.sub_algorithm_id = %d and o.address = "%s" and p.status = 0 order by bid_time desc`, tables.TableNameAuctionOrder, tables.TableNameRegisterPendingInfo, algorithmId, subAlgithmId, addr) + err = d.db.Raw(sql).Find(&list).Error + return list, nil +} + +func (d *DbDao) GetAuctionOrderByAccount(account string) (list []tables.TableAuctionOrder, err error) { + sql := fmt.Sprintf(`SELECT o.account,o.outpoint,o.address,o.algorithm_id,o.sub_algorithm_id,p.status FROM %s o +LEFT JOIN %s p ON o.outpoint=p.outpoint +WHERE o.account= "%s" and p.status != %d`, tables.TableNameAuctionOrder, tables.TableNameRegisterPendingInfo, account, tables.StatusRejected) + err = d.db.Raw(sql).Find(&list).Error + return list, nil +} + +func (d *DbDao) GetAuctionOrderStatus(algorithmId common.DasAlgorithmId, subAlgithmId common.DasSubAlgorithmId, addr, account string) (list tables.TableAuctionOrder, err error) { + sql := fmt.Sprintf(`SELECT o.id,o.account,o.outpoint,o.basic_price,o.premium_price,o.order_id,p.status FROM %s o LEFT JOIN %s p ON o.outpoint=p.outpoint WHERE o.account="%s" and o.algorithm_id = %d and o.sub_algorithm_id = %d and o.address = "%s" order by bid_time desc`, tables.TableNameAuctionOrder, tables.TableNameRegisterPendingInfo, account, algorithmId, subAlgithmId, addr) + fmt.Println(sql) + err = d.db.Raw(sql).First(&list).Error + return list, nil +} diff --git a/http_server/api_code/monitor.go b/http_server/api_code/monitor.go index 71f87ed2..6cf2feef 100644 --- a/http_server/api_code/monitor.go +++ b/http_server/api_code/monitor.go @@ -3,7 +3,6 @@ package api_code import ( "bytes" "das_register_server/config" - "das_register_server/prometheus" "encoding/json" "fmt" api_code "github.com/dotbitHQ/das-lib/http_api" @@ -42,7 +41,7 @@ func PushLog(url string, req ReqPushLog) { func DoMonitorLog(method string) gin.HandlerFunc { return func(ctx *gin.Context) { - startTime := time.Now() + //startTime := time.Now() //ip := getClientIp(ctx) blw := &bodyWriter{body: bytes.NewBufferString(""), ResponseWriter: ctx.Writer} @@ -71,7 +70,7 @@ func DoMonitorLog(method string) gin.HandlerFunc { if resp.ErrNo == api_code.ApiCodeSuccess { resp.ErrMsg = "" } - prometheus.Tools.Metrics.Api().WithLabelValues(method, fmt.Sprint(statusCode), fmt.Sprint(resp.ErrNo), resp.ErrMsg).Observe(time.Since(startTime).Seconds()) + //prometheus.Tools.Metrics.Api().WithLabelValues(method, fmt.Sprint(statusCode), fmt.Sprint(resp.ErrNo), resp.ErrMsg).Observe(time.Since(startTime).Seconds()) } } diff --git a/http_server/handle/account_detail.go b/http_server/handle/account_detail.go index a0ada294..06cdedb4 100644 --- a/http_server/handle/account_detail.go +++ b/http_server/handle/account_detail.go @@ -3,6 +3,7 @@ package handle import ( "bytes" "das_register_server/config" + "time" //"das_register_server/http_server/api_code" "das_register_server/tables" @@ -44,6 +45,7 @@ type RespAccountDetail struct { CustomScript string `json:"custom_script"` PremiumPercentage decimal.Decimal `json:"premium_percentage"` PremiumBase decimal.Decimal `json:"premium_base"` + ReRegisterTime uint64 `json:"re_registered_time"` } func (h *HttpHandle) RpcAccountDetail(p json.RawMessage, apiResp *api_code.ApiResp) { @@ -163,8 +165,29 @@ func (h *HttpHandle) doAccountDetail(req *ReqAccountDetail, apiResp *api_code.Ap // check sub account count := strings.Count(req.Account, ".") - if count == 1 && acc.Id > 0 { + //now < expired_at + 90 + 27 => expired_at > now-90-27 + //expired_at+90 < now => expired_at < now - 90 + //now > expired_at+90+27 + //now < expired_at+90+30 + nowTime := uint64(time.Now().Unix()) + //27 days : watting for bid + if nowTime-117*24*3600 < acc.ExpiredAt && acc.ExpiredAt < nowTime-90*24*3600 { + resp.Status = tables.SearchStatusOnDutchAuction + //resp.AuctionInfo.StartPremium = common.StartPremium + //resp.AuctionInfo.StartTime = acc.ExpiredAt + 90*24*3600 + //resp.AuctionInfo.EndTime = acc.ExpiredAt + 117*24*3600 + //resp.AuctionInfo.TotalDays = common.TOTALDAYS + apiResp.ApiRespOK(resp) + return nil + } + //3 days : can`t bid or register or renew, watting for recycle by keeper + if nowTime-120*24*3600 < acc.ExpiredAt && acc.ExpiredAt < nowTime-117*24*3600 { + resp.Status = tables.SearchStatusAuctionRecycling + resp.ReRegisterTime = acc.ExpiredAt + 120*24*3600 + apiResp.ApiRespOK(resp) + return nil + } accOutpoint := common.String2OutPointStruct(acc.Outpoint) accTx, er := h.dasCore.Client().GetTransaction(h.ctx, accOutpoint.TxHash) if er != nil { @@ -190,7 +213,6 @@ func (h *HttpHandle) doAccountDetail(req *ReqAccountDetail, apiResp *api_code.Ap return fmt.Errorf("getAccountPrice err: %s", err.Error()) } } - if acc.Id > 0 { resp.Status = acc.FormatAccountStatus() resp.ExpiredAt = int64(acc.ExpiredAt) * 1e3 @@ -245,6 +267,7 @@ func (h *HttpHandle) doAccountDetail(req *ReqAccountDetail, apiResp *api_code.Ap return nil } + //主账号 if count == 1 { // reserve account accountName := strings.ToLower(strings.TrimSuffix(req.Account, common.DasAccountSuffix)) diff --git a/http_server/handle/auction_info.go b/http_server/handle/auction_info.go new file mode 100644 index 00000000..6f2a92e9 --- /dev/null +++ b/http_server/handle/auction_info.go @@ -0,0 +1,345 @@ +package handle + +import ( + "das_register_server/config" + "das_register_server/tables" + "fmt" + "github.com/dotbitHQ/das-lib/common" + "github.com/dotbitHQ/das-lib/core" + "github.com/dotbitHQ/das-lib/http_api" + "github.com/gin-gonic/gin" + "github.com/scorpiotzh/toolib" + "github.com/shopspring/decimal" + "gorm.io/gorm" + "net/http" + "time" +) + +type ReqAuctionPrice struct { + Account string `json:"account"` +} + +type RespAuctionPrice struct { + BasicPrice decimal.Decimal `json:"basic_price"` + PremiumPrice int64 `json:"premium_price"` +} + +//查询价格 +func (h *HttpHandle) GetAccountAuctionPrice(ctx *gin.Context) { + var ( + funcName = "GetAccountAuctionPrice" + clientIp = GetClientIp(ctx) + req ReqAuctionPrice + apiResp http_api.ApiResp + err error + ) + + if err := ctx.ShouldBindJSON(&req); err != nil { + log.Error("ShouldBindJSON err: ", err.Error(), funcName, clientIp) + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params invalid") + ctx.JSON(http.StatusOK, apiResp) + return + } + log.Info("ApiReq:", funcName, clientIp, toolib.JsonString(req)) + + if err = h.doGetAccountAuctionPrice(&req, &apiResp); err != nil { + log.Error("GetAccountAuctionInfo err:", err.Error(), funcName, clientIp) + } + ctx.JSON(http.StatusOK, apiResp) +} +func (h *HttpHandle) doGetAccountAuctionPrice(req *ReqAuctionPrice, apiResp *http_api.ApiResp) (err error) { + var resp RespAuctionPrice + if req.Account == "" { + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params invalid: account is empty") + return + } + accountId := common.Bytes2Hex(common.GetAccountIdByAccount(req.Account)) + acc, err := h.dbDao.GetAccountInfoByAccountId(accountId) + if err != nil && err != gorm.ErrRecordNotFound { + apiResp.ApiRespErr(http_api.ApiCodeDbError, "search account err") + return fmt.Errorf("SearchAccount err: %s", err.Error()) + } + nowTime := uint64(time.Now().Unix()) + //exp + 90 + 27 +3 + //now > exp+117 exp< now - 117 + //now< exp+90 exp>now -90 + if acc.ExpiredAt > nowTime-90*24*3600 || acc.ExpiredAt < nowTime-117*24*3600 { + apiResp.ApiRespErr(http_api.ApiCodeAuctionAccountNotFound, "This account has not been in dutch auction") + return + } + //计算长度 + _, accLen, err := common.GetDotBitAccountLength(req.Account) + if err != nil { + return + } + if accLen == 0 { + err = fmt.Errorf("accLen is 0") + return + } + baseAmount, accountPrice, err := h.getAccountPrice(uint8(accLen), "", req.Account, false) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeError500, "get account price err") + return fmt.Errorf("getAccountPrice err: %s", err.Error()) + } + resp.BasicPrice = baseAmount.Add(accountPrice) + fmt.Println(acc.ExpiredAt) + resp.PremiumPrice = common.Premium(int64(acc.ExpiredAt)) + apiResp.ApiRespOK(resp) + return +} + +type ReqAccountAuctionInfo struct { + Account string `json:"account"` + core.ChainTypeAddress + address string + chainType common.ChainType +} + +type RespAccountAuctionInfo struct { + AccountId string `json:"account_id"` + Account string `json:"account"` + BidStatus tables.BidStatus `json:"bid_status"` + StartsaleTime uint64 `json:"start_auction_time"` + EndSaleTime uint64 `json:"end_auction_time"` + ExipiredTime uint64 `json:"expired_at"` + BasicPrice decimal.Decimal `json:"basic_price"` +} + +func (h *HttpHandle) GetAccountAuctionInfo(ctx *gin.Context) { + var ( + funcName = "GetAccountAuctionInfo" + clientIp = GetClientIp(ctx) + req ReqAccountAuctionInfo + apiResp http_api.ApiResp + err error + ) + + if err := ctx.ShouldBindJSON(&req); err != nil { + log.Error("ShouldBindJSON err: ", err.Error(), funcName, clientIp) + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params invalid") + ctx.JSON(http.StatusOK, apiResp) + return + } + log.Info("ApiReq:", funcName, clientIp, toolib.JsonString(req)) + + if err = h.doGetAccountAuctionInfo(&req, &apiResp); err != nil { + log.Error("GetAccountAuctionInfo err:", err.Error(), funcName, clientIp) + } + ctx.JSON(http.StatusOK, apiResp) +} + +func (h *HttpHandle) doGetAccountAuctionInfo(req *ReqAccountAuctionInfo, apiResp *http_api.ApiResp) (err error) { + var resp RespAccountAuctionInfo + if req.Account == "" { + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params invalid: account is empty") + return + } + + addrHex, err := req.FormatChainTypeAddress(config.Cfg.Server.Net, true) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) + return nil + } + fmt.Println(addrHex.DasAlgorithmId, addrHex.DasSubAlgorithmId, addrHex.AddressHex) + req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType + if req.chainType != 1 { + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) + return nil + } + + accountId := common.Bytes2Hex(common.GetAccountIdByAccount(req.Account)) + acc, err := h.dbDao.GetAccountInfoByAccountId(accountId) + if err != nil && err != gorm.ErrRecordNotFound { + apiResp.ApiRespErr(http_api.ApiCodeDbError, "search account err") + return fmt.Errorf("SearchAccount err: %s", err.Error()) + } + nowTime := uint64(time.Now().Unix()) + if acc.Id == 0 { + apiResp.ApiRespErr(http_api.ApiCodeAccountNotExist, fmt.Sprintf("account [%s] not exist", req.Account)) + return + } + if acc.ExpiredAt > nowTime-90*24*3600 || acc.ExpiredAt < nowTime-117*24*3600 { + apiResp.ApiRespErr(http_api.ApiCodeAuctionAccountNotFound, "This account has not been in dutch auction") + return + } + + //查询账号的竞拍状态 + list, err := h.dbDao.GetAuctionOrderByAccount(req.Account) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeDbError, "db error") + return + } + + //无人竞拍(有发送中和上链成功的订单) + if len(list) == 0 { + resp.BidStatus = tables.BidStatusNoOne + } else { + resp.BidStatus = tables.BidStatusByOthers //被其他人竞拍 + for _, v := range list { + //被自己竞拍 + if v.AlgorithmId == addrHex.DasAlgorithmId && v.SubAlgorithmId == addrHex.DasSubAlgorithmId && v.Address == addrHex.AddressHex { + resp.BidStatus = tables.BidStatusByMe + } + } + apiResp.ApiRespOK(resp) + return + } + + //计算长度 + _, accLen, err := common.GetDotBitAccountLength(req.Account) + if err != nil { + return + } + if accLen == 0 { + err = fmt.Errorf("accLen is 0") + return + } + baseAmount, accountPrice, err := h.getAccountPrice(uint8(accLen), "", req.Account, false) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeError500, "get account price err") + return fmt.Errorf("getAccountPrice err: %s", err.Error()) + } + resp.AccountId = acc.AccountId + resp.Account = req.Account + resp.StartsaleTime = acc.ExpiredAt + 90*86400 + resp.EndSaleTime = acc.ExpiredAt + 27*86400 + resp.BasicPrice = accountPrice.Add(baseAmount) + resp.ExipiredTime = acc.ExpiredAt + apiResp.ApiRespOK(resp) + return +} + +type ReqGetAuctionOrder struct { + Account string `json:"account"` + core.ChainTypeAddress + address string + chainType common.ChainType +} +type RepReqGetAuctionOrder struct { + Account string `json:"account"` + OrderId string `json:"order_id"` + Outpoint string `json:"outpoint"` + Status int `json:"status"` + BasicPrice decimal.Decimal `json:"basic_price" gorm:"column:basic_price;type:decimal(60,0) NOT NULL DEFAULT '0' COMMENT ''"` + PremiumPrice decimal.Decimal `json:"premium_price" gorm:"column:premium_price;type:decimal(60,0) NOT NULL DEFAULT '0' COMMENT ''"` +} + +func (h *HttpHandle) GetAuctionOrderStatus(ctx *gin.Context) { + var ( + funcName = "GetAuctionOrder" + clientIp = GetClientIp(ctx) + req ReqGetAuctionOrder + apiResp http_api.ApiResp + err error + ) + + if err := ctx.ShouldBindJSON(&req); err != nil { + log.Error("ShouldBindJSON err: ", err.Error(), funcName, clientIp) + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params invalid") + ctx.JSON(http.StatusOK, apiResp) + return + } + + log.Info("ApiReq:", funcName, clientIp, toolib.JsonString(req)) + + if err = h.doGetAuctionOrderStatus(&req, &apiResp); err != nil { + log.Error("GetBidStatus err:", err.Error(), funcName, clientIp) + } + ctx.JSON(http.StatusOK, apiResp) +} + +func (h *HttpHandle) doGetAuctionOrderStatus(req *ReqGetAuctionOrder, apiResp *http_api.ApiResp) (err error) { + var resp RepReqGetAuctionOrder + + addrHex, err := req.FormatChainTypeAddress(config.Cfg.Server.Net, true) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) + return nil + } + req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType + if req.chainType != 1 { + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) + return nil + } + order, err := h.dbDao.GetAuctionOrderStatus(addrHex.DasAlgorithmId, addrHex.DasSubAlgorithmId, addrHex.AddressHex, req.Account) + if err != nil { + fmt.Println("11111111 ", err) + apiResp.ApiRespErr(http_api.ApiCodeDbError, "db error") + return + } + if order.Id == 0 { + apiResp.ApiRespErr(http_api.ApiCodeAuctionOrderNotFound, "order not found") + return + } + fmt.Println(order) + resp.OrderId = order.OrderId + resp.Account = order.Account + resp.PremiumPrice = order.PremiumPrice + resp.BasicPrice = order.BasicPrice + resp.Outpoint = order.Outpoint + resp.Status = order.Status + apiResp.ApiRespOK(resp) + return +} + +type ReqGetGetPendingAuctionOrder struct { + core.ChainTypeAddress + address string + chainType common.ChainType +} + +func (h *HttpHandle) GetPendingAuctionOrder(ctx *gin.Context) { + var ( + funcName = "GetPendingAuctionOrder" + clientIp = GetClientIp(ctx) + req ReqGetGetPendingAuctionOrder + apiResp http_api.ApiResp + err error + ) + + if err := ctx.ShouldBindJSON(&req); err != nil { + log.Error("ShouldBindJSON err: ", err.Error(), funcName, clientIp) + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params invalid") + ctx.JSON(http.StatusOK, apiResp) + return + } + + log.Info("ApiReq:", funcName, clientIp, toolib.JsonString(req)) + + if err = h.doGetPendingAuctionOrder(&req, &apiResp); err != nil { + log.Error("GetBidStatus err:", err.Error(), funcName, clientIp) + } + ctx.JSON(http.StatusOK, apiResp) +} + +func (h *HttpHandle) doGetPendingAuctionOrder(req *ReqGetGetPendingAuctionOrder, apiResp *http_api.ApiResp) (err error) { + //var resp []RepReqGetAuctionOrder + resp := make([]RepReqGetAuctionOrder, 0) + addrHex, err := req.FormatChainTypeAddress(config.Cfg.Server.Net, true) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) + return nil + } + req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType + if req.chainType != 1 { + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) + return nil + } + list, err := h.dbDao.GetPendingAuctionOrder(addrHex.DasAlgorithmId, addrHex.DasSubAlgorithmId, addrHex.AddressHex) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeDbError, "db error") + return + } + for _, v := range list { + resp = append(resp, RepReqGetAuctionOrder{ + OrderId: v.OrderId, + Account: v.Account, + PremiumPrice: v.PremiumPrice, + BasicPrice: v.BasicPrice, + Outpoint: v.Outpoint, + Status: v.Status, + }) + } + apiResp.ApiRespOK(resp) + return +} diff --git a/http_server/router.go b/http_server/router.go index 7ebd32e8..d8051878 100644 --- a/http_server/router.go +++ b/http_server/router.go @@ -5,7 +5,6 @@ import ( "das_register_server/http_server/api_code" "encoding/json" "github.com/dotbitHQ/das-lib/common" - sentrygin "github.com/getsentry/sentry-go/gin" "github.com/gin-gonic/gin" "github.com/scorpiotzh/toolib" "net/http" @@ -26,9 +25,9 @@ func (h *HttpServer) initRouter() { toolib.AllowOriginList = append(toolib.AllowOriginList, originList...) } h.engine.Use(toolib.MiddlewareCors()) - h.engine.Use(sentrygin.New(sentrygin.Options{ - Repanic: true, - })) + //h.engine.Use(sentrygin.New(sentrygin.Options{ + // Repanic: true, + //})) v1 := h.engine.Group("v1") { // cache @@ -60,6 +59,10 @@ func (h *HttpServer) initRouter() { v1.POST("/account/order/detail", api_code.DoMonitorLog(api_code.MethodOrderDetail), h.h.OrderDetail) v1.POST("/address/deposit", api_code.DoMonitorLog(api_code.MethodAddressDeposit), cacheHandleLong, h.h.AddressDeposit) v1.POST("/character/set/list", api_code.DoMonitorLog(api_code.MethodCharacterSetList), cacheHandleLong, h.h.CharacterSetList) + v1.POST("/account/auction/info", api_code.DoMonitorLog(api_code.MethodCharacterSetList), cacheHandleLong, h.h.GetAccountAuctionInfo) + v1.POST("/account/auction/price", api_code.DoMonitorLog(api_code.MethodCharacterSetList), cacheHandleLong, h.h.GetAccountAuctionPrice) + v1.POST("/account/auction/order-status", api_code.DoMonitorLog(api_code.MethodCharacterSetList), cacheHandleLong, h.h.GetAuctionOrderStatus) + v1.POST("/account/auction/pending-order", api_code.DoMonitorLog(api_code.MethodCharacterSetList), cacheHandleLong, h.h.GetPendingAuctionOrder) // operate //v1.POST("/reverse/declare", api_code.DoMonitorLog(api_code.MethodReverseDeclare), h.h.ReverseDeclare) diff --git a/tables/t_account_info.go b/tables/t_account_info.go index 32ef79ab..6a832d1e 100644 --- a/tables/t_account_info.go +++ b/tables/t_account_info.go @@ -63,6 +63,12 @@ const ( SearchStatusUnAvailableAccount SearchStatus = 13 SearchStatusSubAccountUnRegister SearchStatus = 14 SearchStatusOnCross SearchStatus = 15 + SearchStatusOnDutchAuction SearchStatus = 17 + SearchStatusAuctionRecycling SearchStatus = 18 + + // 90天之后 三天以内 弹第一个框 dutchAuctionRecycling 18 // 荷兰拍结束的 后三天 :返回可以开始注册的时间 + // 90天之内 第二个弹框取消 + //90天之后 27天以内 荷兰拍阶段 弹第三个框 dutchAuction 17 // ) func (t *TableAccountInfo) IsExpired() bool { diff --git a/tables/t_auction_order.go b/tables/t_auction_order.go new file mode 100644 index 00000000..7761f65d --- /dev/null +++ b/tables/t_auction_order.go @@ -0,0 +1,40 @@ +package tables + +import ( + "github.com/dotbitHQ/das-lib/common" + "github.com/shopspring/decimal" + "time" +) + +const ( + TableNameAuctionOrder = "t_auction_order" +) + +type TableAuctionOrder struct { + Id uint64 `json:"id" gorm:"column:id;primaryKey;type:bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT ''"` + Account string `json:"account" gorm:"column:account;type:varchar(255) DEFAULT NULL"` + AccountId string `json:"account_id" gorm:"column:account_id;type:varchar(255) DEFAULT NULL"` + OrderId string `json:"order_id" gorm:"column:order_id;type:varchar(255) DEFAULT NULL"` + Address string `json:"address" gorm:"column:address;type:varchar(255) DEFAULT NULL"` + AlgorithmId common.DasAlgorithmId `json:"algorithm_id" gorm:"column:algorithm_id"` + SubAlgorithmId common.DasSubAlgorithmId `json:"sub_algorithm_id" gorm:"column:sub_algorithm_id"` + BasicPrice decimal.Decimal `json:"basic_price" gorm:"column:basic_price;type:decimal(60,0) NOT NULL DEFAULT '0' COMMENT ''"` + PremiumPrice decimal.Decimal `json:"premium_price" gorm:"column:premium_price;type:decimal(60,0) NOT NULL DEFAULT '0' COMMENT ''"` + Status int `json:"status"` + BidTime uint64 `json:"bid_time" gorm:"column:bid_time;type:bigint NOT NULL DEFAULT '0'"` + Outpoint string `json:"outpoint" gorm:"column:outpoint;type:varchar(255) DEFAULT NULL"` + CreatedAt time.Time `json:"created_at" gorm:"column:created_at;type:timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''"` + UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at;type:timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''"` +} + +func (t *TableAuctionOrder) TableName() string { + return TableNameAuctionOrder +} + +type BidStatus int + +const ( + BidStatusNoOne BidStatus = 0 //账号没有人竞 + BidStatusByOthers BidStatus = 1 //账号被其他人竞拍 + BidStatusByMe BidStatus = 2 //账号被我竞拍 +) diff --git a/timer/recycle_early.go b/timer/recycle_early.go index 0eef0479..e987a3d9 100644 --- a/timer/recycle_early.go +++ b/timer/recycle_early.go @@ -254,6 +254,7 @@ func (t *TxTimer) doRecyclePreEarly() error { } func (t *TxTimer) DoRecyclePreEarly() { + return if config.Cfg.Server.RecyclePreEarlyCronSpec == "" { return } diff --git a/timer/timer.go b/timer/timer.go index db57d101..f5628f92 100644 --- a/timer/timer.go +++ b/timer/timer.go @@ -48,6 +48,7 @@ func NewTxTimer(p TxTimerParam) *TxTimer { } func (t *TxTimer) Run() error { + return nil if err := t.doUpdateTokenMap(); err != nil { return fmt.Errorf("doUpdateTokenMap init token err: %s", err.Error()) } diff --git a/txtool/txtool.go b/txtool/txtool.go index 785f6ab2..4d1b5c05 100644 --- a/txtool/txtool.go +++ b/txtool/txtool.go @@ -32,6 +32,7 @@ type TxTool struct { } func (t *TxTool) Run() { + return tickerApply := time.NewTicker(time.Second * 5) tickerPreRegister := time.NewTicker(time.Second * 6) tickerRenew := time.NewTicker(time.Second * 7) From 4ddfb7a2ac7d8cb637e0bf65346bf5f3a15ea919 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Thu, 2 Nov 2023 14:20:24 +0800 Subject: [PATCH 02/67] bid api --- http_server/handle/auction_bid.go | 138 ++++++++++++++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 http_server/handle/auction_bid.go diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go new file mode 100644 index 00000000..a5689a11 --- /dev/null +++ b/http_server/handle/auction_bid.go @@ -0,0 +1,138 @@ +package handle + +import ( + "das_register_server/config" + "das_register_server/tables" + "fmt" + "github.com/dotbitHQ/das-lib/common" + "github.com/dotbitHQ/das-lib/core" + "github.com/dotbitHQ/das-lib/http_api" + "github.com/dotbitHQ/das-lib/txbuilder" + "github.com/gin-gonic/gin" + "github.com/nervosnetwork/ckb-sdk-go/types" + "github.com/scorpiotzh/toolib" + "gorm.io/gorm" + "net/http" + "time" +) + +type ReqAuctionBid struct { + Account string `json:"account"` + address string + chainType common.ChainType + core.ChainTypeAddress +} + +type RespAuctionBid struct { + SignInfo +} + +//查询价格 +func (h *HttpHandle) GetAccountAuctionBid(ctx *gin.Context) { + var ( + funcName = "GetAccountAuctionPrice" + clientIp = GetClientIp(ctx) + req ReqAuctionBid + apiResp http_api.ApiResp + err error + ) + + if err := ctx.ShouldBindJSON(&req); err != nil { + log.Error("ShouldBindJSON err: ", err.Error(), funcName, clientIp) + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params invalid") + ctx.JSON(http.StatusOK, apiResp) + return + } + log.Info("ApiReq:", funcName, clientIp, toolib.JsonString(req)) + + if err = h.doGetAccountAuctionBid(&req, &apiResp); err != nil { + log.Error("GetAccountAuctionInfo err:", err.Error(), funcName, clientIp) + } + ctx.JSON(http.StatusOK, apiResp) +} +func (h *HttpHandle) doGetAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.ApiResp) (err error) { + var resp RespAuctionBid + if req.Account == "" { + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params invalid: account is empty") + return + } + accountId := common.Bytes2Hex(common.GetAccountIdByAccount(req.Account)) + acc, err := h.dbDao.GetAccountInfoByAccountId(accountId) + if err != nil && err != gorm.ErrRecordNotFound { + apiResp.ApiRespErr(http_api.ApiCodeDbError, "search account err") + return fmt.Errorf("SearchAccount err: %s", err.Error()) + } + nowTime := uint64(time.Now().Unix()) + //exp + 90 + 27 +3 + //now > exp+117 exp< now - 117 + //now< exp+90 exp>now -90 + if acc.ExpiredAt > nowTime-90*24*3600 || acc.ExpiredAt < nowTime-117*24*3600 { + apiResp.ApiRespErr(http_api.ApiCodeAuctionAccountNotFound, "This account has not been in dutch auction") + return + } + //计算长度 + _, accLen, err := common.GetDotBitAccountLength(req.Account) + if err != nil { + return + } + if accLen == 0 { + err = fmt.Errorf("accLen is 0") + return + } + baseAmount, accountPrice, err := h.getAccountPrice(uint8(accLen), "", req.Account, false) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeError500, "get account price err") + return fmt.Errorf("getAccountPrice err: %s", err.Error()) + } + basicPrice := baseAmount.Add(accountPrice) + premiumPrice := common.Premium(int64(acc.ExpiredAt)) + //check user`s DP + + // + addrHex, err := req.FormatChainTypeAddress(config.Cfg.Server.Net, true) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) + return nil + } + fmt.Println(addrHex.DasAlgorithmId, addrHex.DasSubAlgorithmId, addrHex.AddressHex) + req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType + + var reqBuild reqBuildTx + reqBuild.Action = common.DasActionTransferAccount + reqBuild.Account = req.Account + reqBuild.ChainType = req.chainType + reqBuild.Address = req.address + reqBuild.Capacity = 0 + var p auctionBidParams + p.account = &acc + txParams, err := h.buildAuctionBidTx(&reqBuild, &p) + + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeError500, "build tx err: "+err.Error()) + return fmt.Errorf("buildEditManagerTx err: %s", err.Error()) + } + if si, err := h.buildTx(&reqBuild, txParams); err != nil { + apiResp.ApiRespErr(http_api.ApiCodeError500, "build tx err: "+err.Error()) + return fmt.Errorf("buildTx: %s", err.Error()) + } else { + resp.SignInfo = *si + } + + apiResp.ApiRespOK(resp) + return nil +} + +type auctionBidParams struct { + account *tables.TableAccountInfo +} + +func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*txbuilder.BuildTransactionParams, error) { + var txParams txbuilder.BuildTransactionParams + + // inputs account cell + accOutPoint := common.String2OutPointStruct(p.account.Outpoint) + txParams.Inputs = append(txParams.Inputs, &types.CellInput{ + PreviousOutput: accOutPoint, + }) + return &txParams, nil +} From d863d3753cc536efde1e4b563a353b996c11f948 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Fri, 3 Nov 2023 13:28:49 +0800 Subject: [PATCH 03/67] bid tx --- cmd/main.go | 1 + http_server/handle/auction_bid.go | 145 +++++++++++++++++++++++++- http_server/handle/handle.go | 4 + http_server/handle/reverse_declare.go | 2 +- http_server/http_server.go | 3 + 5 files changed, 151 insertions(+), 4 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index abbdbb70..d40969c4 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -201,6 +201,7 @@ func runServer(ctx *cli.Context) error { DasCore: dasCore, DasCache: dasCache, TxBuilderBase: txBuilderBase, + ServerScript: serverScript, MapReservedAccounts: builderConfigCell.ConfigCellPreservedAccountMap, MapUnAvailableAccounts: builderConfigCell.ConfigCellUnavailableAccountMap, }) diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index a5689a11..4d5f3e64 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -7,10 +7,14 @@ import ( "github.com/dotbitHQ/das-lib/common" "github.com/dotbitHQ/das-lib/core" "github.com/dotbitHQ/das-lib/http_api" + "github.com/dotbitHQ/das-lib/molecule" "github.com/dotbitHQ/das-lib/txbuilder" + "github.com/dotbitHQ/das-lib/witness" "github.com/gin-gonic/gin" + "github.com/nervosnetwork/ckb-sdk-go/indexer" "github.com/nervosnetwork/ckb-sdk-go/types" "github.com/scorpiotzh/toolib" + "github.com/shopspring/decimal" "gorm.io/gorm" "net/http" "time" @@ -85,7 +89,7 @@ func (h *HttpHandle) doGetAccountAuctionBid(req *ReqAuctionBid, apiResp *http_ap return fmt.Errorf("getAccountPrice err: %s", err.Error()) } basicPrice := baseAmount.Add(accountPrice) - premiumPrice := common.Premium(int64(acc.ExpiredAt)) + premiumPrice := decimal.NewFromInt(common.Premium(int64(acc.ExpiredAt))) //check user`s DP // @@ -98,13 +102,15 @@ func (h *HttpHandle) doGetAccountAuctionBid(req *ReqAuctionBid, apiResp *http_ap req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType var reqBuild reqBuildTx - reqBuild.Action = common.DasActionTransferAccount + reqBuild.Action = common.DasBidExpiredAccountAuction reqBuild.Account = req.Account reqBuild.ChainType = req.chainType reqBuild.Address = req.address reqBuild.Capacity = 0 var p auctionBidParams p.account = &acc + p.basicPrice = basicPrice + p.premiumPrice = premiumPrice txParams, err := h.buildAuctionBidTx(&reqBuild, &p) if err != nil { @@ -123,16 +129,149 @@ func (h *HttpHandle) doGetAccountAuctionBid(req *ReqAuctionBid, apiResp *http_ap } type auctionBidParams struct { - account *tables.TableAccountInfo + account *tables.TableAccountInfo + basicPrice decimal.Decimal + premiumPrice decimal.Decimal } func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*txbuilder.BuildTransactionParams, error) { var txParams txbuilder.BuildTransactionParams + contractAcc, err := core.GetDasContractInfo(common.DasContractNameAccountCellType) + if err != nil { + return nil, fmt.Errorf("GetDasContractInfo err: %s", err.Error()) + } + contractDas, err := core.GetDasContractInfo(common.DasContractNameDispatchCellType) + if err != nil { + return nil, fmt.Errorf("GetDasContractInfo err: %s", err.Error()) + } // inputs account cell accOutPoint := common.String2OutPointStruct(p.account.Outpoint) txParams.Inputs = append(txParams.Inputs, &types.CellInput{ PreviousOutput: accOutPoint, }) + + // witness account cell + res, err := h.dasCore.Client().GetTransaction(h.ctx, accOutPoint.TxHash) + if err != nil { + return nil, fmt.Errorf("GetTransaction err: %s", err.Error()) + } + builderMap, err := witness.AccountCellDataBuilderMapFromTx(res.Transaction, common.DataTypeNew) + if err != nil { + return nil, fmt.Errorf("AccountCellDataBuilderMapFromTx err: %s", err.Error()) + } + builder, ok := builderMap[req.Account] + if !ok { + return nil, fmt.Errorf("builderMap not exist account: %s", req.Account) + } + + timeCell, err := h.dasCore.GetTimeCell() + if err != nil { + return nil, fmt.Errorf("GetTimeCell err: %s", err.Error()) + } + + //witness + //-----witness action + actionWitness, err := witness.GenActionDataWitness(common.DasBidExpiredAccountAuction, nil) + if err != nil { + return nil, fmt.Errorf("GenActionDataWitness err: %s", err.Error()) + } + txParams.Witnesses = append(txParams.Witnesses, actionWitness) + //-----acc witness + accWitness, accData, err := builder.GenWitness(&witness.AccountCellParam{ + OldIndex: 0, + NewIndex: 0, + Action: common.DasBidExpiredAccountAuction, + LastTransferAccountAt: timeCell.Timestamp(), + }) + txParams.Witnesses = append(txParams.Witnesses, accWitness) + + // inputs + //-----AccountCell + accOutpoint := common.String2OutPointStruct(p.account.Outpoint) + txParams.Inputs = append(txParams.Inputs, &types.CellInput{ + PreviousOutput: accOutpoint, + }) + + //------DPCell + + //------NormalCell + needCapacity := res.Transaction.Outputs[builder.Index].Capacity + liveCell, totalCapacity, err := h.dasCore.GetBalanceCells(&core.ParamGetBalanceCells{ + DasCache: h.dasCache, + LockScript: h.serverScript, + CapacityNeed: needCapacity, + CapacityForChange: common.MinCellOccupiedCkb, + SearchOrder: indexer.SearchOrderAsc, + }) + if err != nil { + return nil, fmt.Errorf("GetBalanceCells err: %s", err.Error()) + } + if change := totalCapacity - needCapacity; change > 0 { + splitCkb := 2000 * common.OneCkb + if config.Cfg.Server.SplitCkb > 0 { + splitCkb = config.Cfg.Server.SplitCkb * common.OneCkb + } + changeList, err := core.SplitOutputCell2(change, splitCkb, 200, h.serverScript, nil, indexer.SearchOrderAsc) + if err != nil { + return nil, fmt.Errorf("SplitOutputCell2 err: %s", err.Error()) + } + for i := 0; i < len(changeList); i++ { + txParams.Outputs = append(txParams.Outputs, changeList[i]) + txParams.OutputsData = append(txParams.OutputsData, []byte{}) + } + } + // inputs + for _, v := range liveCell { + txParams.Inputs = append(txParams.Inputs, &types.CellInput{ + PreviousOutput: v.OutPoint, + }) + } + + //output + + //-----AccountCell + lockArgs, err := h.dasCore.Daf().HexToArgs(core.DasAddressHex{ + DasAlgorithmId: req.ChainType.ToDasAlgorithmId(true), + AddressHex: req.Address, + IsMulti: false, + ChainType: req.ChainType, + }, core.DasAddressHex{ + DasAlgorithmId: req.ChainType.ToDasAlgorithmId(true), + AddressHex: req.Address, + IsMulti: false, + ChainType: req.ChainType, + }) + txParams.Outputs = append(txParams.Outputs, &types.CellOutput{ + Capacity: res.Transaction.Outputs[builder.Index].Capacity, + Lock: contractDas.ToScript(lockArgs), + Type: contractAcc.ToScript(nil), + }) + newExpiredAt := int64(builder.ExpiredAt) + common.OneYearSec + byteExpiredAt := molecule.Go64ToBytes(newExpiredAt) + accData = append(accData, res.Transaction.OutputsData[builder.Index][32:]...) + accData1 := accData[:common.ExpireTimeEndIndex-common.ExpireTimeLen] + accData2 := accData[common.ExpireTimeEndIndex:] + newAccData := append(accData1, byteExpiredAt...) + newAccData = append(newAccData, accData2...) + txParams.OutputsData = append(txParams.OutputsData, newAccData) // change expired_at + + //DPCell + + //oldowner balanceCell + oldOwnerAddrHex := core.DasAddressHex{ + DasAlgorithmId: p.account.OwnerChainType.ToDasAlgorithmId(true), + AddressHex: p.account.Owner, + IsMulti: false, + ChainType: p.account.OwnerChainType, + } + oldOwnerLockArgs, err := h.dasCore.Daf().HexToArgs(oldOwnerAddrHex, oldOwnerAddrHex) + txParams.Outputs = append(txParams.Outputs, &types.CellOutput{ + Capacity: res.Transaction.Outputs[builder.Index].Capacity, + Lock: contractDas.ToScript(oldOwnerLockArgs), + Type: contractAcc.ToScript(nil), + }) + txParams.OutputsData = append(txParams.OutputsData, []byte{}) + return &txParams, nil } diff --git a/http_server/handle/handle.go b/http_server/handle/handle.go index 913f4b70..cec702d1 100644 --- a/http_server/handle/handle.go +++ b/http_server/handle/handle.go @@ -13,6 +13,7 @@ import ( "github.com/dotbitHQ/das-lib/http_api/logger" "github.com/dotbitHQ/das-lib/txbuilder" "github.com/gin-gonic/gin" + "github.com/nervosnetwork/ckb-sdk-go/types" ) var ( @@ -26,6 +27,7 @@ type HttpHandle struct { dasCore *core.DasCore dasCache *dascache.DasCache txBuilderBase *txbuilder.DasTxBuilderBase + serverScript *types.Script mapReservedAccounts map[string]struct{} mapUnAvailableAccounts map[string]struct{} } @@ -37,6 +39,7 @@ type HttpHandleParams struct { DasCore *core.DasCore DasCache *dascache.DasCache TxBuilderBase *txbuilder.DasTxBuilderBase + ServerScript *types.Script MapReservedAccounts map[string]struct{} MapUnAvailableAccounts map[string]struct{} } @@ -49,6 +52,7 @@ func Initialize(p HttpHandleParams) *HttpHandle { dasCore: p.DasCore, dasCache: p.DasCache, txBuilderBase: p.TxBuilderBase, + serverScript: p.ServerScript, mapReservedAccounts: p.MapReservedAccounts, mapUnAvailableAccounts: p.MapUnAvailableAccounts, } diff --git a/http_server/handle/reverse_declare.go b/http_server/handle/reverse_declare.go index 34a33c89..9689af73 100644 --- a/http_server/handle/reverse_declare.go +++ b/http_server/handle/reverse_declare.go @@ -236,7 +236,7 @@ func (h *HttpHandle) buildTx(req *reqBuildTx, txParams *txbuilder.BuildTransacti sizeInBlock, _ := txBuilder.Transaction.SizeInBlock() changeCapacity := txBuilder.Transaction.Outputs[len(txBuilder.Transaction.Outputs)-1].Capacity + common.OneCkb - sizeInBlock - 1000 txBuilder.Transaction.Outputs[len(txBuilder.Transaction.Outputs)-1].Capacity = changeCapacity - case common.DasActionEditRecords, common.DasActionEditManager, common.DasActionTransferAccount: + case common.DasActionEditRecords, common.DasActionEditManager, common.DasActionTransferAccount, common.DasBidExpiredAccountAuction: sizeInBlock, _ := txBuilder.Transaction.SizeInBlock() changeCapacity := txBuilder.Transaction.Outputs[0].Capacity - sizeInBlock - 1000 txBuilder.Transaction.Outputs[0].Capacity = changeCapacity diff --git a/http_server/http_server.go b/http_server/http_server.go index 39f44dcc..46eeb7d6 100644 --- a/http_server/http_server.go +++ b/http_server/http_server.go @@ -10,6 +10,7 @@ import ( "github.com/dotbitHQ/das-lib/http_api/logger" "github.com/dotbitHQ/das-lib/txbuilder" "github.com/gin-gonic/gin" + "github.com/nervosnetwork/ckb-sdk-go/types" "net/http" ) @@ -38,6 +39,7 @@ type HttpServerParams struct { DasCore *core.DasCore DasCache *dascache.DasCache TxBuilderBase *txbuilder.DasTxBuilderBase + ServerScript *types.Script MapReservedAccounts map[string]struct{} MapUnAvailableAccounts map[string]struct{} } @@ -58,6 +60,7 @@ func Initialize(p HttpServerParams) (*HttpServer, error) { TxBuilderBase: p.TxBuilderBase, MapReservedAccounts: p.MapReservedAccounts, MapUnAvailableAccounts: p.MapUnAvailableAccounts, + ServerScript: p.ServerScript, }), rc: p.Rc, } From 0e0b1b0d38a337f9aa7419d8b594985db5551dfc Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Mon, 6 Nov 2023 18:04:24 +0800 Subject: [PATCH 04/67] edit params --- http_server/handle/auction_info.go | 4 ---- 1 file changed, 4 deletions(-) diff --git a/http_server/handle/auction_info.go b/http_server/handle/auction_info.go index 6f2a92e9..99ae5766 100644 --- a/http_server/handle/auction_info.go +++ b/http_server/handle/auction_info.go @@ -257,10 +257,6 @@ func (h *HttpHandle) doGetAuctionOrderStatus(req *ReqGetAuctionOrder, apiResp *h return nil } req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType - if req.chainType != 1 { - apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) - return nil - } order, err := h.dbDao.GetAuctionOrderStatus(addrHex.DasAlgorithmId, addrHex.DasSubAlgorithmId, addrHex.AddressHex, req.Account) if err != nil { fmt.Println("11111111 ", err) From a43f18e022a3e0a81a913d955fa00016b6196005 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Mon, 6 Nov 2023 22:02:36 +0800 Subject: [PATCH 05/67] api doc --- API.md | 253 ++++++++++++++++++++++++- dao/t_auction_order.go | 4 + go.mod | 4 +- go.sum | 4 +- http_server/handle/auction_bid.go | 30 +-- http_server/handle/auction_info.go | 5 +- http_server/handle/common.go | 20 +- http_server/handle/reverse_declare.go | 19 +- http_server/handle/transaction_send.go | 26 +++ http_server/router.go | 1 + tables/t_auction_order.go | 7 +- 11 files changed, 339 insertions(+), 34 deletions(-) diff --git a/API.md b/API.md index 2f78c1b2..bc698b98 100644 --- a/API.md +++ b/API.md @@ -17,6 +17,10 @@ * [Account Order Detail](#account-order-detail) * [Address Deposit](#address-deposit) * [Character Set List](#character-set-list) + * [Account Auction Info](#account-auction-info) + * [Account Auction Price](#account-auction-price) + * [Account Auction OrderStatus](#account-auction-order_status) + * [Account Auction PendingOrders](#account-auction-pending_orders) * [OPERATE API LIST](#operate-api-list) * [Reverse Declare (Deprecated)](#reverse-declare) * [Reverse Redeclare (Deprecated)](#reverse-redeclare) @@ -35,6 +39,7 @@ * [Account Order Pay Hash](#account-order-pay-hash) * [Account Register](#account-register) * [Account Renew](#account-renew) + * [Account Auction Bid](#account-auction-bid) * [NODE RPC](#node-rpc) * [Node Ckb Rpc](#node-ckb-rpc) @@ -307,7 +312,8 @@ curl -X POST http://127.0.0.1:8120/v1/account/mine -d'{"chain_type":1,"address": * 13: unregisterable * 14: sub-account * 15: cross-chain - + * 17: on dutch auction period + * 18: on dutch auction deliver period ```json { "err_no": 0, @@ -1836,3 +1842,248 @@ curl -X POST http://127.0.0.1:8119/v1/account/renew -d'{"chain_type":1,"address" curl -X POST http://127.0.0.1:8120/v1/node/ckb/rpc -d'{"jsonrpc":"2.0","id":2976777,"method":"get_blockchain_info","params":[]}' ``` + +#### Account Auction Info + +**Request** + +* path: /account/auction/info + * get dutch auction info of a account +* param: + +```json +{ + "account":"michaeltest1.bit", + "type":"blockchain", + "key_info":{ + "coin_type":"60", + "key":"0xd437b8e9cA16Fce24bF3258760c3567214213C5A" + } +} +``` + +**Response** + +```json +{ + "err_no": 0, + "err_msg": "", + "data": { + "account_id": "", + "account": "", + "bid_status": 2, + "start_auction_time": 0, + "end_auction_time": 0, + "expired_at": 0, + "basic_price": "0" + } +} +``` + +**Usage** + +```curl +curl --location 'http://127.0.0.1:8120/v1/account/auction/info' \ +--header 'Content-Type: application/json' \ +--data '{ + "account":"michaeltest1.bit", + "type":"blockchain", + "key_info":{ + "coin_type":"60", + "key":"0xd437b8e9cA16Fce24bF3258760c3567214213C5A" + } +}' +``` + + +#### Account Auction Price + +**Request** + +* path: /account/auction/price + * get dutch auction price of a account +* param: + +```json +{ + "account":"michaeltest1.bit" +} +``` + +**Response** + +```json +{ + "err_no": 0, + "err_msg": "", + "data": { + "basic_price": "5.8", + "premium_price": 20 + } +} +``` + +**Usage** + +```curl +curl --location 'http://127.0.0.1:8120/v1/account/auction/price' \ +--header 'Content-Type: application/json' \ +--data '{ + "account":"michaeltest1.bit" +}' +``` + +#### Account Auction OrderStatus + +**Request** + +* path: /account/auction/order-status + * get status of a dutch auction order +* param: + +```json +{ + "account":"michaeltest1.bit", + "type":"blockchain", + "key_info":{ + "coin_type":"60", + "key":"0xd437b8e9cA16Fce24bF3258760c3567214213C5A" + } +} +``` + +**Response** + +```json +{ + "err_no": 0, + "err_msg": "", + "data": { + "account": "michaeltest1.bit", + "order_id": "abc123123", + "outpoint": "0xeb4871b7af2ca7129a43c5991c408148abd195eb5699223fad11a712b1e1d584-0", + "status": 0, + "basic_price": "6", + "premium_price": "100" + } +} +``` + +**Usage** + +```curl +curl --location 'http://127.0.0.1:8120/v1/account/auction/order-status' \ +--header 'Content-Type: application/json' \ +--data '{ + "account":"michaeltest1.bit", + "type":"blockchain", + "key_info":{ + "coin_type":"60", + "key":"0xd437b8e9cA16Fce24bF3258760c3567214213C5A" + } +}' +``` + +#### Account Auction PendingOrders + +**Request** + +* path: /account/auction/pending-order + * get dutch auction order with pending status +* param: + +```json +{ + "type":"blockchain", + "key_info":{ + "coin_type":"60", + "key":"0xd437b8e9cA16Fce24bF3258760c3567214213C5A" + } +} +``` + +**Response** + +```json +{ + "err_no": 0, + "err_msg": "", + "data": [ + { + "account": "michaeltest1.bit", + "order_id": "abc123123", + "outpoint": "0xeb4871b7af2ca7129a43c5991c408148abd195eb5699223fad11a712b1e1d584-0", + "status": 0, + "basic_price": "6", + "premium_price": "100" + } + ] +} +``` + +**Usage** + +```curl +curl --location 'http://127.0.0.1:8120/v1/account/auction/pending-order' \ +--header 'Content-Type: application/json' \ +--data '{ + "type":"blockchain", + "key_info":{ + "coin_type":"60", + "key":"0xd437b8e9cA16Fce24bF3258760c3567214213C5A" + } +}' +``` + +#### Account Auction Bid + +**Request** + +* path: /account/auction/bid + * bid a account during dutch auction period +* param: + +```json +{ + "account":"michaeltest1.bit", + "type":"blockchain", + "key_info":{ + "coin_type":"60", + "key":"0xd437b8e9cA16Fce24bF3258760c3567214213C5A" + } +} +``` + +**Response** + +```json +{ + "err_no": 0, + "err_msg": "", + "data": { + "sign_key": "", + "sign_list": [ + { + "sign_type": 5, + "sign_msg": "" + } + ], + "mm_json": {} + } +} +``` + +**Usage** + +```curl +curl --location 'http://127.0.0.1:8120/v1/account/auction/bid' \ +--header 'Content-Type: application/json' \ +--data '{ + "account":"michaeltest1.bit", + "type":"blockchain", + "key_info":{ + "coin_type":"60", + "key":"0xd437b8e9cA16Fce24bF3258760c3567214213C5A" + } +}' +``` \ No newline at end of file diff --git a/dao/t_auction_order.go b/dao/t_auction_order.go index 251e2ffd..072f12b0 100644 --- a/dao/t_auction_order.go +++ b/dao/t_auction_order.go @@ -26,3 +26,7 @@ func (d *DbDao) GetAuctionOrderStatus(algorithmId common.DasAlgorithmId, subAlgi err = d.db.Raw(sql).First(&list).Error return list, nil } + +func (d *DbDao) CreateAuctionOrder(auctionOrder tables.TableAuctionOrder) (err error) { + return d.db.Create(&auctionOrder).Error +} diff --git a/go.mod b/go.mod index 029ef630..625aefc0 100644 --- a/go.mod +++ b/go.mod @@ -3,10 +3,10 @@ module das_register_server go 1.18 require ( - github.com/dotbitHQ/das-lib v1.1.1-0.20231009040002-1f163142f334 + github.com/dotbitHQ/das-lib v1.1.1-0.20231106140104-e0342efb3797 github.com/ethereum/go-ethereum v1.10.26 github.com/fsnotify/fsnotify v1.5.4 - github.com/getsentry/sentry-go v0.24.0 + github.com/getsentry/sentry-go v0.24.0 // indirect github.com/gin-gonic/gin v1.9.1 github.com/go-redis/redis v6.15.9+incompatible github.com/minio/blake2b-simd v0.0.0-20160723061019-3f5f724cb5b1 diff --git a/go.sum b/go.sum index acb827e3..43212fbe 100644 --- a/go.sum +++ b/go.sum @@ -145,8 +145,8 @@ github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5O github.com/docker/docker v1.4.2-0.20180625184442-8e610b2b55bf/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/dop251/goja v0.0.0-20211011172007-d99e4b8cbf48/go.mod h1:R9ET47fwRVRPZnOGvHxxhuZcbrMCuiqOz3Rlrh4KSnk= github.com/dop251/goja_nodejs v0.0.0-20210225215109-d91c329300e7/go.mod h1:hn7BA7c8pLvoGndExHudxTDKZ84Pyvv+90pbBjbTz0Y= -github.com/dotbitHQ/das-lib v1.1.1-0.20231009040002-1f163142f334 h1:U+rSu5AW/ylTslLs3Is/fo3tJyNQWURAH8XBVJk1X5I= -github.com/dotbitHQ/das-lib v1.1.1-0.20231009040002-1f163142f334/go.mod h1:bWgGqfGuc9moidjzK7MpC0q80d694ucm0961MEMNiaI= +github.com/dotbitHQ/das-lib v1.1.1-0.20231106140104-e0342efb3797 h1:yHR+ePURrDQajBkVDbr3UqiOa7MZEFmWifcnfv1r0Dc= +github.com/dotbitHQ/das-lib v1.1.1-0.20231106140104-e0342efb3797/go.mod h1:6zhVMmqpRLq1bR8BqAdh/Nf8GQdJ5pREhBAwnImYQGg= github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts= github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= github.com/elazarl/goproxy v0.0.0-20221015165544-a0805db90819 h1:RIB4cRk+lBqKK3Oy0r2gRX4ui7tuhiZq2SuTtTCi0/0= diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index 4d5f3e64..03da4109 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -32,9 +32,9 @@ type RespAuctionBid struct { } //查询价格 -func (h *HttpHandle) GetAccountAuctionBid(ctx *gin.Context) { +func (h *HttpHandle) AccountAuctionBid(ctx *gin.Context) { var ( - funcName = "GetAccountAuctionPrice" + funcName = "AccountAuctionBid" clientIp = GetClientIp(ctx) req ReqAuctionBid apiResp http_api.ApiResp @@ -49,13 +49,21 @@ func (h *HttpHandle) GetAccountAuctionBid(ctx *gin.Context) { } log.Info("ApiReq:", funcName, clientIp, toolib.JsonString(req)) - if err = h.doGetAccountAuctionBid(&req, &apiResp); err != nil { + if err = h.doAccountAuctionBid(&req, &apiResp); err != nil { log.Error("GetAccountAuctionInfo err:", err.Error(), funcName, clientIp) } ctx.JSON(http.StatusOK, apiResp) } -func (h *HttpHandle) doGetAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.ApiResp) (err error) { +func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.ApiResp) (err error) { var resp RespAuctionBid + addrHex, err := req.FormatChainTypeAddress(config.Cfg.Server.Net, true) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) + return nil + } + fmt.Println(addrHex.DasAlgorithmId, addrHex.DasSubAlgorithmId, addrHex.AddressHex) + req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType + if req.Account == "" { apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params invalid: account is empty") return @@ -89,17 +97,10 @@ func (h *HttpHandle) doGetAccountAuctionBid(req *ReqAuctionBid, apiResp *http_ap return fmt.Errorf("getAccountPrice err: %s", err.Error()) } basicPrice := baseAmount.Add(accountPrice) - premiumPrice := decimal.NewFromInt(common.Premium(int64(acc.ExpiredAt))) + premiumPrice := decimal.NewFromInt(common.Premium(int64(acc.ExpiredAt), int64(nowTime))) //check user`s DP // - addrHex, err := req.FormatChainTypeAddress(config.Cfg.Server.Net, true) - if err != nil { - apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) - return nil - } - fmt.Println(addrHex.DasAlgorithmId, addrHex.DasSubAlgorithmId, addrHex.AddressHex) - req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType var reqBuild reqBuildTx reqBuild.Action = common.DasBidExpiredAccountAuction @@ -107,6 +108,11 @@ func (h *HttpHandle) doGetAccountAuctionBid(req *ReqAuctionBid, apiResp *http_ap reqBuild.ChainType = req.chainType reqBuild.Address = req.address reqBuild.Capacity = 0 + reqBuild.AuctionInfo = AuctionInfo{ + BasicPrice: basicPrice, + PremiumPrice: premiumPrice, + BidTime: int64(nowTime), + } var p auctionBidParams p.account = &acc p.basicPrice = basicPrice diff --git a/http_server/handle/auction_info.go b/http_server/handle/auction_info.go index 99ae5766..bd50a51a 100644 --- a/http_server/handle/auction_info.go +++ b/http_server/handle/auction_info.go @@ -83,7 +83,7 @@ func (h *HttpHandle) doGetAccountAuctionPrice(req *ReqAuctionPrice, apiResp *htt } resp.BasicPrice = baseAmount.Add(accountPrice) fmt.Println(acc.ExpiredAt) - resp.PremiumPrice = common.Premium(int64(acc.ExpiredAt)) + resp.PremiumPrice = common.Premium(int64(acc.ExpiredAt), int64(nowTime)) apiResp.ApiRespOK(resp) return } @@ -259,7 +259,7 @@ func (h *HttpHandle) doGetAuctionOrderStatus(req *ReqGetAuctionOrder, apiResp *h req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType order, err := h.dbDao.GetAuctionOrderStatus(addrHex.DasAlgorithmId, addrHex.DasSubAlgorithmId, addrHex.AddressHex, req.Account) if err != nil { - fmt.Println("11111111 ", err) + apiResp.ApiRespErr(http_api.ApiCodeDbError, "db error") return } @@ -309,7 +309,6 @@ func (h *HttpHandle) GetPendingAuctionOrder(ctx *gin.Context) { } func (h *HttpHandle) doGetPendingAuctionOrder(req *ReqGetGetPendingAuctionOrder, apiResp *http_api.ApiResp) (err error) { - //var resp []RepReqGetAuctionOrder resp := make([]RepReqGetAuctionOrder, 0) addrHex, err := req.FormatChainTypeAddress(config.Cfg.Server.Net, true) if err != nil { diff --git a/http_server/handle/common.go b/http_server/handle/common.go index 6d9bd4a2..32b3d4cc 100644 --- a/http_server/handle/common.go +++ b/http_server/handle/common.go @@ -6,6 +6,7 @@ import ( "github.com/dotbitHQ/das-lib/common" "github.com/dotbitHQ/das-lib/txbuilder" "github.com/scorpiotzh/toolib" + "github.com/shopspring/decimal" "time" ) @@ -43,13 +44,20 @@ func (s *SignInfo) SignListString() string { return toolib.JsonString(s.SignList) } +type AuctionInfo struct { + BasicPrice decimal.Decimal `json:"basic_price"` + PremiumPrice decimal.Decimal `json:"premium_price"` + BidTime int64 `json:"bid_time"` +} + type SignInfoCache struct { - ChainType common.ChainType `json:"chain_type"` - Address string `json:"address"` - Action string `json:"action"` - Account string `json:"account"` - Capacity uint64 `json:"capacity"` - BuilderTx *txbuilder.DasTxBuilderTransaction `json:"builder_tx"` + ChainType common.ChainType `json:"chain_type"` + Address string `json:"address"` + Action string `json:"action"` + Account string `json:"account"` + Capacity uint64 `json:"capacity"` + BuilderTx *txbuilder.DasTxBuilderTransaction `json:"builder_tx"` + AuctionInfo AuctionInfo `json:"auction_info"` } func (s *SignInfoCache) SignKey() string { diff --git a/http_server/handle/reverse_declare.go b/http_server/handle/reverse_declare.go index 9689af73..f8586495 100644 --- a/http_server/handle/reverse_declare.go +++ b/http_server/handle/reverse_declare.go @@ -201,12 +201,13 @@ func (h *HttpHandle) doReverseDeclare(req *ReqReverseDeclare, apiResp *api_code. } type reqBuildTx struct { - Action common.DasAction - ChainType common.ChainType `json:"chain_type"` - Address string `json:"address"` - Account string `json:"account"` - Capacity uint64 `json:"capacity"` - EvmChainId int64 `json:"evm_chain_id"` + Action common.DasAction + ChainType common.ChainType `json:"chain_type"` + Address string `json:"address"` + Account string `json:"account"` + Capacity uint64 `json:"capacity"` + EvmChainId int64 `json:"evm_chain_id"` + AuctionInfo AuctionInfo `json:"auction_info"` } type DeclareParams struct { @@ -216,7 +217,6 @@ type DeclareParams struct { TotalCapacity uint64 DeclareCapacity uint64 FeeCapacity uint64 - //AccountInfo *tables.TableAccountInfo } func (h *HttpHandle) buildTx(req *reqBuildTx, txParams *txbuilder.BuildTransactionParams) (*SignInfo, error) { @@ -269,6 +269,11 @@ func (h *HttpHandle) buildTx(req *reqBuildTx, txParams *txbuilder.BuildTransacti sic.Capacity = req.Capacity sic.BuilderTx = txBuilder.DasTxBuilderTransaction + //dutch auction + if req.Action == common.DasBidExpiredAccountAuction { + sic.AuctionInfo = req.AuctionInfo + } + signKey := sic.SignKey() cacheStr := toolib.JsonString(&sic) if err = h.rc.SetSignTxCache(signKey, cacheStr); err != nil { diff --git a/http_server/handle/transaction_send.go b/http_server/handle/transaction_send.go index de9f92e3..c2998001 100644 --- a/http_server/handle/transaction_send.go +++ b/http_server/handle/transaction_send.go @@ -187,6 +187,32 @@ func (h *HttpHandle) doTransactionSend(req *ReqTransactionSend, apiResp *api_cod if err = h.dbDao.CreatePending(&pending); err != nil { log.Error("CreatePending err: ", err.Error(), toolib.JsonString(pending)) } + + if sic.Action == common.DasBidExpiredAccountAuction { + addressHex, err := h.dasCore.Daf().NormalToHex(core.DasAddressNormal{ + ChainType: sic.ChainType, + AddressNormal: sic.Address, + Is712: true, + }) + if err != nil { + apiResp.ApiRespErr(api_code.ApiCodeParamsInvalid, "address NormalToHex err") + return fmt.Errorf("NormalToHex err: %s", err.Error()) + } + auctionOrder := tables.TableAuctionOrder{ + Account: sic.Account, + AccountId: common.Bytes2Hex(common.GetAccountIdByAccount(sic.Account)), + Address: sic.Address, + BasicPrice: sic.AuctionInfo.BasicPrice, + PremiumPrice: sic.AuctionInfo.PremiumPrice, + BidTime: sic.AuctionInfo.BidTime, + AlgorithmId: addressHex.DasAlgorithmId, + SubAlgorithmId: addressHex.DasSubAlgorithmId, + ChainType: sic.ChainType, + } + if err = h.dbDao.CreateAuctionOrder(auctionOrder); err != nil { + log.Error("CreateAuctionOrder err: ", err.Error(), toolib.JsonString(auctionOrder)) + } + } } } diff --git a/http_server/router.go b/http_server/router.go index d8051878..06aaa5ed 100644 --- a/http_server/router.go +++ b/http_server/router.go @@ -82,6 +82,7 @@ func (h *HttpServer) initRouter() { v1.POST("/account/order/pay/hash", api_code.DoMonitorLog(api_code.MethodOrderPayHash), h.h.OrderPayHash) v1.POST("/account/coupon/check", api_code.DoMonitorLog(api_code.MethodOrderCheckCoupon), cacheHandleShort, h.h.CheckCoupon) //v1.POST("/account/edit/script", api_code.DoMonitorLog(api_code.MethodEditScript), h.h.EditScript) + v1.POST("/account/auction/bid", api_code.DoMonitorLog(api_code.MethodCharacterSetList), cacheHandleLong, h.h.AccountAuctionBid) // node rpc v1.POST("/node/ckb/rpc", api_code.DoMonitorLog(api_code.MethodCkbRpc), h.h.CkbRpc) diff --git a/tables/t_auction_order.go b/tables/t_auction_order.go index 7761f65d..43756385 100644 --- a/tables/t_auction_order.go +++ b/tables/t_auction_order.go @@ -16,12 +16,13 @@ type TableAuctionOrder struct { AccountId string `json:"account_id" gorm:"column:account_id;type:varchar(255) DEFAULT NULL"` OrderId string `json:"order_id" gorm:"column:order_id;type:varchar(255) DEFAULT NULL"` Address string `json:"address" gorm:"column:address;type:varchar(255) DEFAULT NULL"` + ChainType common.ChainType `json:"chain_type" gorm:"column:chain_type;index:k_chain_type_address;type:smallint(6) NOT NULL DEFAULT '0' COMMENT 'order chain type'"` AlgorithmId common.DasAlgorithmId `json:"algorithm_id" gorm:"column:algorithm_id"` SubAlgorithmId common.DasSubAlgorithmId `json:"sub_algorithm_id" gorm:"column:sub_algorithm_id"` BasicPrice decimal.Decimal `json:"basic_price" gorm:"column:basic_price;type:decimal(60,0) NOT NULL DEFAULT '0' COMMENT ''"` PremiumPrice decimal.Decimal `json:"premium_price" gorm:"column:premium_price;type:decimal(60,0) NOT NULL DEFAULT '0' COMMENT ''"` Status int `json:"status"` - BidTime uint64 `json:"bid_time" gorm:"column:bid_time;type:bigint NOT NULL DEFAULT '0'"` + BidTime int64 `json:"bid_time" gorm:"column:bid_time;type:bigint NOT NULL DEFAULT '0'"` Outpoint string `json:"outpoint" gorm:"column:outpoint;type:varchar(255) DEFAULT NULL"` CreatedAt time.Time `json:"created_at" gorm:"column:created_at;type:timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''"` UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at;type:timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''"` @@ -38,3 +39,7 @@ const ( BidStatusByOthers BidStatus = 1 //账号被其他人竞拍 BidStatusByMe BidStatus = 2 //账号被我竞拍 ) + +func (t *TableAuctionOrder) CreateOrderId() { + t.OrderId = CreateOrderId(1, t.AccountId, common.DasBidExpiredAccountAuction, t.ChainType, t.Address, t.BidTime) +} From 9f69e066438b68b8a3a4753d27be07001f1f12e0 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Mon, 6 Nov 2023 22:11:31 +0800 Subject: [PATCH 06/67] update api doc --- API.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/API.md b/API.md index bc698b98..60e89fa7 100644 --- a/API.md +++ b/API.md @@ -314,6 +314,7 @@ curl -X POST http://127.0.0.1:8120/v1/account/mine -d'{"chain_type":1,"address": * 15: cross-chain * 17: on dutch auction period * 18: on dutch auction deliver period +* re_registered_time: Time for re registration ```json { "err_no": 0, @@ -331,7 +332,8 @@ curl -X POST http://127.0.0.1:8120/v1/account/mine -d'{"chain_type":1,"address": "base_amount": "3.89", "confirm_proposal_hash": "0xec7bec47a4d3ad467253925a7e097f311e0738d625d55f8b3420cabaaa9b5201", "premium_percentage": "",// for stripe usd premium - "premium_base": "" // for stripe usd premium + "premium_base": "", // for stripe usd premium + "re_registered_time": 1672211096 } } ``` From 16386ed1869214d2da6fa675afb18064413eb5b1 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Tue, 7 Nov 2023 10:17:05 +0800 Subject: [PATCH 07/67] remove test debug --- block_parser/block_parser.go | 1 - timer/recycle_early.go | 1 - timer/timer.go | 1 - txtool/txtool.go | 1 - 4 files changed, 4 deletions(-) diff --git a/block_parser/block_parser.go b/block_parser/block_parser.go index d9313569..0442c14c 100644 --- a/block_parser/block_parser.go +++ b/block_parser/block_parser.go @@ -35,7 +35,6 @@ type BlockParser struct { } func (b *BlockParser) Run() error { - return nil b.registerTransactionHandle() currentBlockNumber, err := b.DasCore.Client().GetTipBlockNumber(b.Ctx) if err != nil { diff --git a/timer/recycle_early.go b/timer/recycle_early.go index e987a3d9..0eef0479 100644 --- a/timer/recycle_early.go +++ b/timer/recycle_early.go @@ -254,7 +254,6 @@ func (t *TxTimer) doRecyclePreEarly() error { } func (t *TxTimer) DoRecyclePreEarly() { - return if config.Cfg.Server.RecyclePreEarlyCronSpec == "" { return } diff --git a/timer/timer.go b/timer/timer.go index f5628f92..db57d101 100644 --- a/timer/timer.go +++ b/timer/timer.go @@ -48,7 +48,6 @@ func NewTxTimer(p TxTimerParam) *TxTimer { } func (t *TxTimer) Run() error { - return nil if err := t.doUpdateTokenMap(); err != nil { return fmt.Errorf("doUpdateTokenMap init token err: %s", err.Error()) } diff --git a/txtool/txtool.go b/txtool/txtool.go index 4d1b5c05..785f6ab2 100644 --- a/txtool/txtool.go +++ b/txtool/txtool.go @@ -32,7 +32,6 @@ type TxTool struct { } func (t *TxTool) Run() { - return tickerApply := time.NewTicker(time.Second * 5) tickerPreRegister := time.NewTicker(time.Second * 6) tickerRenew := time.NewTicker(time.Second * 7) From 493e9eb4ae459e6a0f6fd44eff6b108396df3ad3 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Tue, 7 Nov 2023 22:05:18 +0800 Subject: [PATCH 08/67] update auction config with contract --- http_server/handle/account_detail.go | 65 +++++++++++++++++++++------- http_server/handle/auction_bid.go | 7 ++- http_server/handle/auction_info.go | 13 ++++-- 3 files changed, 64 insertions(+), 21 deletions(-) diff --git a/http_server/handle/account_detail.go b/http_server/handle/account_detail.go index 06cdedb4..7346de83 100644 --- a/http_server/handle/account_detail.go +++ b/http_server/handle/account_detail.go @@ -148,6 +148,48 @@ func (h *HttpHandle) getAccountPrice(accLen uint8, args, account string, isRenew return } +func (h *HttpHandle) checkDutchAuction(expiredAt uint64) (status tables.SearchStatus, reRegisterTime uint64, err error) { + nowTime := uint64(time.Now().Unix()) + //27 days : watting for bid + //h.dasCore.ConfigCellDataBuilderByTypeArgsList() + builderConfigCell, err := h.dasCore.ConfigCellDataBuilderByTypeArgs(common.ConfigCellTypeArgsAccount) + if err != nil { + err = fmt.Errorf("ConfigCellDataBuilderByTypeArgs err: %s", err.Error()) + return + } + + gracePeriodTime, err := builderConfigCell.ExpirationGracePeriod() + if err != nil { + err = fmt.Errorf("ExpirationGracePeriod err: %s", err.Error()) + return + } + + auctionPeriodTime, err := builderConfigCell.ExpirationAuctionPeriod() + if err != nil { + err = fmt.Errorf("ExpirationAuctionPeriod err: %s", err.Error()) + return + } + + deliverPeriodTime, err := builderConfigCell.ExpirationDeliverPeriod() + if err != nil { + err = fmt.Errorf("ExpirationDeliverPeriod err: %s", err.Error()) + return + } + // nowTime-117*24*3600 < expiredAt && expiredAt < nowTime-90*24*3600 + if nowTime-uint64(gracePeriodTime)-uint64(auctionPeriodTime) < expiredAt && expiredAt < nowTime-uint64(gracePeriodTime) { + status = tables.SearchStatusOnDutchAuction + return + } + //3 days : can`t bid or register or renew, watting for recycle by keeper + //nowTime-120*24*3600 < expiredAt && expiredAt < nowTime-117*24*3600 + if nowTime-uint64(gracePeriodTime)-uint64(auctionPeriodTime)-uint64(deliverPeriodTime) < expiredAt && expiredAt < nowTime-uint64(gracePeriodTime)-uint64(auctionPeriodTime) { + status = tables.SearchStatusAuctionRecycling + reRegisterTime = expiredAt + uint64(gracePeriodTime+auctionPeriodTime+deliverPeriodTime) + return + } + return +} + func (h *HttpHandle) doAccountDetail(req *ReqAccountDetail, apiResp *api_code.ApiResp) error { var resp RespAccountDetail resp.Account = req.Account @@ -170,24 +212,16 @@ func (h *HttpHandle) doAccountDetail(req *ReqAccountDetail, apiResp *api_code.Ap //expired_at+90 < now => expired_at < now - 90 //now > expired_at+90+27 //now < expired_at+90+30 - nowTime := uint64(time.Now().Unix()) - //27 days : watting for bid - if nowTime-117*24*3600 < acc.ExpiredAt && acc.ExpiredAt < nowTime-90*24*3600 { - resp.Status = tables.SearchStatusOnDutchAuction - //resp.AuctionInfo.StartPremium = common.StartPremium - //resp.AuctionInfo.StartTime = acc.ExpiredAt + 90*24*3600 - //resp.AuctionInfo.EndTime = acc.ExpiredAt + 117*24*3600 - //resp.AuctionInfo.TotalDays = common.TOTALDAYS - apiResp.ApiRespOK(resp) - return nil - } - //3 days : can`t bid or register or renew, watting for recycle by keeper - if nowTime-120*24*3600 < acc.ExpiredAt && acc.ExpiredAt < nowTime-117*24*3600 { - resp.Status = tables.SearchStatusAuctionRecycling - resp.ReRegisterTime = acc.ExpiredAt + 120*24*3600 + if status, reRegisterTime, err := h.checkDutchAuction(acc.ExpiredAt); err != nil { + apiResp.ApiRespErr(api_code.ApiCodeError500, "checkDutchAuction err") + return fmt.Errorf("checkDutchAuction err: %s", err.Error()) + } else if status != 0 { + resp.Status = status + resp.ReRegisterTime = reRegisterTime apiResp.ApiRespOK(resp) return nil } + accOutpoint := common.String2OutPointStruct(acc.Outpoint) accTx, er := h.dasCore.Client().GetTransaction(h.ctx, accOutpoint.TxHash) if er != nil { @@ -267,7 +301,6 @@ func (h *HttpHandle) doAccountDetail(req *ReqAccountDetail, apiResp *api_code.Ap return nil } - //主账号 if count == 1 { // reserve account accountName := strings.ToLower(strings.TrimSuffix(req.Account, common.DasAccountSuffix)) diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index 03da4109..ac638c05 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -78,9 +78,12 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A //exp + 90 + 27 +3 //now > exp+117 exp< now - 117 //now< exp+90 exp>now -90 - if acc.ExpiredAt > nowTime-90*24*3600 || acc.ExpiredAt < nowTime-117*24*3600 { + if status, _, err := h.checkDutchAuction(acc.ExpiredAt); err != nil { + apiResp.ApiRespErr(http_api.ApiCodeError500, "checkDutchAuction err") + return fmt.Errorf("checkDutchAuction err: %s", err.Error()) + } else if status != tables.SearchStatusOnDutchAuction { apiResp.ApiRespErr(http_api.ApiCodeAuctionAccountNotFound, "This account has not been in dutch auction") - return + return nil } //计算长度 _, accLen, err := common.GetDotBitAccountLength(req.Account) diff --git a/http_server/handle/auction_info.go b/http_server/handle/auction_info.go index bd50a51a..c3bd9744 100644 --- a/http_server/handle/auction_info.go +++ b/http_server/handle/auction_info.go @@ -153,15 +153,22 @@ func (h *HttpHandle) doGetAccountAuctionInfo(req *ReqAccountAuctionInfo, apiResp apiResp.ApiRespErr(http_api.ApiCodeDbError, "search account err") return fmt.Errorf("SearchAccount err: %s", err.Error()) } - nowTime := uint64(time.Now().Unix()) if acc.Id == 0 { apiResp.ApiRespErr(http_api.ApiCodeAccountNotExist, fmt.Sprintf("account [%s] not exist", req.Account)) return } - if acc.ExpiredAt > nowTime-90*24*3600 || acc.ExpiredAt < nowTime-117*24*3600 { + + if status, _, err := h.checkDutchAuction(acc.ExpiredAt); err != nil { + apiResp.ApiRespErr(http_api.ApiCodeError500, "checkDutchAuction err") + return fmt.Errorf("checkDutchAuction err: %s", err.Error()) + } else if status != tables.SearchStatusOnDutchAuction { apiResp.ApiRespErr(http_api.ApiCodeAuctionAccountNotFound, "This account has not been in dutch auction") - return + return nil } + //if acc.ExpiredAt > nowTime-90*24*3600 || acc.ExpiredAt < nowTime-117*24*3600 { + // apiResp.ApiRespErr(http_api.ApiCodeAuctionAccountNotFound, "This account has not been in dutch auction") + // return + //} //查询账号的竞拍状态 list, err := h.dbDao.GetAuctionOrderByAccount(req.Account) From 1dd6eb6061d18c7b9f0b7aee83314ca4a8024d29 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Wed, 8 Nov 2023 11:58:12 +0800 Subject: [PATCH 09/67] add baseamount --- API.md | 3 ++- http_server/handle/auction_info.go | 6 ++++-- http_server/handle/reverse_declare.go | 2 +- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/API.md b/API.md index 60e89fa7..b2f0b2e9 100644 --- a/API.md +++ b/API.md @@ -1877,7 +1877,8 @@ curl -X POST http://127.0.0.1:8120/v1/node/ckb/rpc -d'{"jsonrpc":"2.0","id":2976 "start_auction_time": 0, "end_auction_time": 0, "expired_at": 0, - "basic_price": "0" + "account_price": "5", + "base_amount": "0.82" } } ``` diff --git a/http_server/handle/auction_info.go b/http_server/handle/auction_info.go index c3bd9744..55ac041c 100644 --- a/http_server/handle/auction_info.go +++ b/http_server/handle/auction_info.go @@ -102,7 +102,8 @@ type RespAccountAuctionInfo struct { StartsaleTime uint64 `json:"start_auction_time"` EndSaleTime uint64 `json:"end_auction_time"` ExipiredTime uint64 `json:"expired_at"` - BasicPrice decimal.Decimal `json:"basic_price"` + AccountPrice decimal.Decimal `json:"account_price"` + BaseAmount decimal.Decimal `json:"base_amount"` } func (h *HttpHandle) GetAccountAuctionInfo(ctx *gin.Context) { @@ -210,7 +211,8 @@ func (h *HttpHandle) doGetAccountAuctionInfo(req *ReqAccountAuctionInfo, apiResp resp.Account = req.Account resp.StartsaleTime = acc.ExpiredAt + 90*86400 resp.EndSaleTime = acc.ExpiredAt + 27*86400 - resp.BasicPrice = accountPrice.Add(baseAmount) + resp.AccountPrice = accountPrice + resp.BaseAmount = baseAmount resp.ExipiredTime = acc.ExpiredAt apiResp.ApiRespOK(resp) return diff --git a/http_server/handle/reverse_declare.go b/http_server/handle/reverse_declare.go index f8586495..675a44ff 100644 --- a/http_server/handle/reverse_declare.go +++ b/http_server/handle/reverse_declare.go @@ -254,7 +254,7 @@ func (h *HttpHandle) buildTx(req *reqBuildTx, txParams *txbuilder.BuildTransacti case common.DasActionConfigSubAccountCustomScript: default: mmJsonObj, err = txBuilder.BuildMMJsonObj(req.EvmChainId) - if req.Action != tables.DasActionTransferBalance && err != nil { + if req.Action != tables.DasActionTransferBalance && req.Action != common.DasBidExpiredAccountAuction && err != nil { return nil, fmt.Errorf("txBuilder.BuildMMJsonObj err: %s", err.Error()) } else { log.Info("BuildTx:", mmJsonObj.String()) From 5760641d9d46c7ce27208aa14277dde52e861f96 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Wed, 8 Nov 2023 12:21:38 +0800 Subject: [PATCH 10/67] test for dutch auction --- http_server/handle/transaction_send.go | 54 ++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/http_server/handle/transaction_send.go b/http_server/handle/transaction_send.go index c2998001..339ab1bb 100644 --- a/http_server/handle/transaction_send.go +++ b/http_server/handle/transaction_send.go @@ -149,6 +149,60 @@ func (h *HttpHandle) doTransactionSend(req *ReqTransactionSend, apiResp *api_cod } } + //test for dutch auction + if sic.Action == common.DasBidExpiredAccountAuction { + // operate limit + _ = h.rc.SetApiLimit(sic.ChainType, sic.Address, sic.Action) + _ = h.rc.SetAccountLimit(sic.Account, time.Minute*2) + + hash := sic.BuilderTx.Transaction.Hash + resp.Hash = hash.Hex() + // cache tx inputs + h.dasCache.AddCellInputByAction("", sic.BuilderTx.Transaction.Inputs) + // pending tx + pending := tables.TableRegisterPendingInfo{ + Account: sic.Account, + Action: sic.Action, + ChainType: sic.ChainType, + Address: sic.Address, + Capacity: sic.Capacity, + Outpoint: common.OutPoint2String(hash.Hex(), 0), + BlockTimestamp: uint64(time.Now().UnixNano() / 1e6), + } + if err := h.dbDao.CreatePending(&pending); err != nil { + log.Error("CreatePending err: ", err.Error(), toolib.JsonString(pending)) + } + + if sic.Action == common.DasBidExpiredAccountAuction { + addressHex, err := h.dasCore.Daf().NormalToHex(core.DasAddressNormal{ + ChainType: sic.ChainType, + AddressNormal: sic.Address, + Is712: true, + }) + if err != nil { + apiResp.ApiRespErr(api_code.ApiCodeParamsInvalid, "address NormalToHex err") + return fmt.Errorf("NormalToHex err: %s", err.Error()) + } + auctionOrder := tables.TableAuctionOrder{ + Account: sic.Account, + AccountId: common.Bytes2Hex(common.GetAccountIdByAccount(sic.Account)), + Address: sic.Address, + BasicPrice: sic.AuctionInfo.BasicPrice, + PremiumPrice: sic.AuctionInfo.PremiumPrice, + BidTime: sic.AuctionInfo.BidTime, + AlgorithmId: addressHex.DasAlgorithmId, + SubAlgorithmId: addressHex.DasSubAlgorithmId, + ChainType: sic.ChainType, + } + if err = h.dbDao.CreateAuctionOrder(auctionOrder); err != nil { + log.Error("CreateAuctionOrder err: ", err.Error(), toolib.JsonString(auctionOrder)) + } + } + + apiResp.ApiRespOK(resp) + return nil + } + // send tx if hash, err := txBuilder.SendTransaction(); err != nil { if strings.Contains(err.Error(), "PoolRejectedDuplicatedTransaction") || From 7dadb98e501f362df3746dc21a5f84f3319a1370 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Wed, 8 Nov 2023 12:45:46 +0800 Subject: [PATCH 11/67] dutch auction test --- http_server/handle/transaction_send.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/http_server/handle/transaction_send.go b/http_server/handle/transaction_send.go index 339ab1bb..6134f118 100644 --- a/http_server/handle/transaction_send.go +++ b/http_server/handle/transaction_send.go @@ -1,6 +1,7 @@ package handle import ( + "crypto/sha256" "das_register_server/tables" "encoding/json" "fmt" @@ -155,8 +156,8 @@ func (h *HttpHandle) doTransactionSend(req *ReqTransactionSend, apiResp *api_cod _ = h.rc.SetApiLimit(sic.ChainType, sic.Address, sic.Action) _ = h.rc.SetAccountLimit(sic.Account, time.Minute*2) - hash := sic.BuilderTx.Transaction.Hash - resp.Hash = hash.Hex() + hash := sha256.Sum256([]byte(randStr(10))) + resp.Hash = common.Bytes2Hex(hash[:]) // cache tx inputs h.dasCache.AddCellInputByAction("", sic.BuilderTx.Transaction.Inputs) // pending tx @@ -166,7 +167,7 @@ func (h *HttpHandle) doTransactionSend(req *ReqTransactionSend, apiResp *api_cod ChainType: sic.ChainType, Address: sic.Address, Capacity: sic.Capacity, - Outpoint: common.OutPoint2String(hash.Hex(), 0), + Outpoint: common.OutPoint2String(resp.Hash, 0), BlockTimestamp: uint64(time.Now().UnixNano() / 1e6), } if err := h.dbDao.CreatePending(&pending); err != nil { @@ -193,6 +194,7 @@ func (h *HttpHandle) doTransactionSend(req *ReqTransactionSend, apiResp *api_cod AlgorithmId: addressHex.DasAlgorithmId, SubAlgorithmId: addressHex.DasSubAlgorithmId, ChainType: sic.ChainType, + Outpoint: pending.Outpoint, } if err = h.dbDao.CreateAuctionOrder(auctionOrder); err != nil { log.Error("CreateAuctionOrder err: ", err.Error(), toolib.JsonString(auctionOrder)) @@ -262,6 +264,7 @@ func (h *HttpHandle) doTransactionSend(req *ReqTransactionSend, apiResp *api_cod AlgorithmId: addressHex.DasAlgorithmId, SubAlgorithmId: addressHex.DasSubAlgorithmId, ChainType: sic.ChainType, + Outpoint: pending.Outpoint, } if err = h.dbDao.CreateAuctionOrder(auctionOrder); err != nil { log.Error("CreateAuctionOrder err: ", err.Error(), toolib.JsonString(auctionOrder)) From 46eba95d4c4bf8648f29fa707f8a6b5fe442ca49 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Wed, 8 Nov 2023 16:11:12 +0800 Subject: [PATCH 12/67] add txhash --- API.md | 5 ++--- dao/t_auction_order.go | 4 ++-- http_server/handle/auction_info.go | 17 +++++++---------- 3 files changed, 11 insertions(+), 15 deletions(-) diff --git a/API.md b/API.md index b2f0b2e9..38d3ab8a 100644 --- a/API.md +++ b/API.md @@ -1947,6 +1947,7 @@ curl --location 'http://127.0.0.1:8120/v1/account/auction/price' \ ```json { "account":"michaeltest1.bit", + "hash": "0xb9e094dd6fcaa6c68d44233cb5331e63bd966fa86659fc45d30089336021f26e", "type":"blockchain", "key_info":{ "coin_type":"60", @@ -1963,8 +1964,7 @@ curl --location 'http://127.0.0.1:8120/v1/account/auction/price' \ "err_msg": "", "data": { "account": "michaeltest1.bit", - "order_id": "abc123123", - "outpoint": "0xeb4871b7af2ca7129a43c5991c408148abd195eb5699223fad11a712b1e1d584-0", + "hash": "0xeb4871b7af2ca7129a43c5991c408148abd195eb5699223fad11a712b1e1d584", "status": 0, "basic_price": "6", "premium_price": "100" @@ -2014,7 +2014,6 @@ curl --location 'http://127.0.0.1:8120/v1/account/auction/order-status' \ "data": [ { "account": "michaeltest1.bit", - "order_id": "abc123123", "outpoint": "0xeb4871b7af2ca7129a43c5991c408148abd195eb5699223fad11a712b1e1d584-0", "status": 0, "basic_price": "6", diff --git a/dao/t_auction_order.go b/dao/t_auction_order.go index 072f12b0..c925136f 100644 --- a/dao/t_auction_order.go +++ b/dao/t_auction_order.go @@ -20,8 +20,8 @@ WHERE o.account= "%s" and p.status != %d`, tables.TableNameAuctionOrder, tables. return list, nil } -func (d *DbDao) GetAuctionOrderStatus(algorithmId common.DasAlgorithmId, subAlgithmId common.DasSubAlgorithmId, addr, account string) (list tables.TableAuctionOrder, err error) { - sql := fmt.Sprintf(`SELECT o.id,o.account,o.outpoint,o.basic_price,o.premium_price,o.order_id,p.status FROM %s o LEFT JOIN %s p ON o.outpoint=p.outpoint WHERE o.account="%s" and o.algorithm_id = %d and o.sub_algorithm_id = %d and o.address = "%s" order by bid_time desc`, tables.TableNameAuctionOrder, tables.TableNameRegisterPendingInfo, account, algorithmId, subAlgithmId, addr) +func (d *DbDao) GetAuctionOrderStatus(algorithmId common.DasAlgorithmId, subAlgithmId common.DasSubAlgorithmId, addr, hash string) (list tables.TableAuctionOrder, err error) { + sql := fmt.Sprintf(`SELECT o.id,o.account,o.outpoint,o.basic_price,o.premium_price,o.order_id,p.status FROM %s o LEFT JOIN %s p ON o.outpoint=p.outpoint WHERE p.outpoint="%s" and o.algorithm_id = %d and o.sub_algorithm_id = %d and o.address = "%s" order by bid_time desc`, tables.TableNameAuctionOrder, tables.TableNameRegisterPendingInfo, fmt.Sprintf("%s-0", hash), algorithmId, subAlgithmId, addr) fmt.Println(sql) err = d.db.Raw(sql).First(&list).Error return list, nil diff --git a/http_server/handle/auction_info.go b/http_server/handle/auction_info.go index 55ac041c..7adbbd6e 100644 --- a/http_server/handle/auction_info.go +++ b/http_server/handle/auction_info.go @@ -219,15 +219,14 @@ func (h *HttpHandle) doGetAccountAuctionInfo(req *ReqAccountAuctionInfo, apiResp } type ReqGetAuctionOrder struct { - Account string `json:"account"` + Hash string `json:"hash" binding:"required"` core.ChainTypeAddress address string chainType common.ChainType } type RepReqGetAuctionOrder struct { Account string `json:"account"` - OrderId string `json:"order_id"` - Outpoint string `json:"outpoint"` + Hash string `json:"hash"` Status int `json:"status"` BasicPrice decimal.Decimal `json:"basic_price" gorm:"column:basic_price;type:decimal(60,0) NOT NULL DEFAULT '0' COMMENT ''"` PremiumPrice decimal.Decimal `json:"premium_price" gorm:"column:premium_price;type:decimal(60,0) NOT NULL DEFAULT '0' COMMENT ''"` @@ -266,9 +265,8 @@ func (h *HttpHandle) doGetAuctionOrderStatus(req *ReqGetAuctionOrder, apiResp *h return nil } req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType - order, err := h.dbDao.GetAuctionOrderStatus(addrHex.DasAlgorithmId, addrHex.DasSubAlgorithmId, addrHex.AddressHex, req.Account) + order, err := h.dbDao.GetAuctionOrderStatus(addrHex.DasAlgorithmId, addrHex.DasSubAlgorithmId, addrHex.AddressHex, req.Hash) if err != nil { - apiResp.ApiRespErr(http_api.ApiCodeDbError, "db error") return } @@ -276,12 +274,11 @@ func (h *HttpHandle) doGetAuctionOrderStatus(req *ReqGetAuctionOrder, apiResp *h apiResp.ApiRespErr(http_api.ApiCodeAuctionOrderNotFound, "order not found") return } - fmt.Println(order) - resp.OrderId = order.OrderId + resp.Account = order.Account resp.PremiumPrice = order.PremiumPrice resp.BasicPrice = order.BasicPrice - resp.Outpoint = order.Outpoint + resp.Hash, _ = common.String2OutPoint(order.Outpoint) resp.Status = order.Status apiResp.ApiRespOK(resp) return @@ -335,12 +332,12 @@ func (h *HttpHandle) doGetPendingAuctionOrder(req *ReqGetGetPendingAuctionOrder, return } for _, v := range list { + hash, _ := common.String2OutPoint(v.Outpoint) resp = append(resp, RepReqGetAuctionOrder{ - OrderId: v.OrderId, Account: v.Account, PremiumPrice: v.PremiumPrice, BasicPrice: v.BasicPrice, - Outpoint: v.Outpoint, + Hash: hash, Status: v.Status, }) } From cc1a1c86b1f2f2d276c06fd79c16bb30058e8117 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Thu, 9 Nov 2023 17:44:49 +0800 Subject: [PATCH 13/67] auction bid tx --- cmd/main.go | 2 +- config/config.go | 8 + http_server/handle/auction_bid.go | 245 +++++++++++++++++--------- http_server/handle/reverse_declare.go | 2 +- tables/t_auction_order.go | 2 +- 5 files changed, 174 insertions(+), 85 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index d40969c4..be31bc13 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -250,7 +250,7 @@ func initDasCore() (*core.DasCore, *dascache.DasCache, error) { common.DasContractNameBalanceCellType, common.DasContractNameDispatchCellType, common.DasContractNameApplyRegisterCellType, common.DasContractNamePreAccountCellType, common.DasContractNameProposalCellType, common.DasContractNameReverseRecordCellType, common.DasContractNameIncomeCellType, common.DasContractNameAlwaysSuccess, common.DASContractNameEip712LibCellType, - common.DASContractNameSubAccountCellType, common.DasKeyListCellType) + common.DASContractNameSubAccountCellType, common.DasKeyListCellType, common.DasContractNameDpCellType) ops := []core.DasCoreOption{ core.WithClient(ckbClient), core.WithDasContractArgs(env.ContractArgs), diff --git a/config/config.go b/config/config.go index 0619806c..58d1476c 100644 --- a/config/config.go +++ b/config/config.go @@ -76,6 +76,14 @@ type CfgServer struct { UniPayRefundSwitch bool `json:"uni_pay_refund_switch" yaml:"uni_pay_refund_switch"` HedgeUrl string `json:"hedge_url" yaml:"hedge_url"` PrometheusPushGateway string `json:"prometheus_push_gateway" yaml:"prometheus_push_gateway"` + // ConfigCellDPoint.transfer_whitelist + TransferWhitelist string `json:"transfer_whitelist" yaml:"transfer_whitelist"` + TransferWhitelistPrivate string `json:"transfer_whitelist_private" yaml:"transfer_whitelist_private"` + //ConfigCellDPoint.capacity_recycle_whitelist + CapacityWhitelist string `json:"capacity_whitelist" yaml:"capacity_whitelist"` + CapacityWhitelistPrivate string `json:"capacity_whitelist_private" yaml:"capacity_whitelist_private"` + SplitCount int `json:"split_count" yaml:"split_count"` + SplitAmount uint64 `json:"split_amount" yaml:"split_amount"` } `json:"server" yaml:"server"` Origins []string `json:"origins" yaml:"origins"` InviterWhitelist map[string]string `json:"inviter_whitelist" yaml:"inviter_whitelist"` diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index ac638c05..ae828184 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -11,6 +11,7 @@ import ( "github.com/dotbitHQ/das-lib/txbuilder" "github.com/dotbitHQ/das-lib/witness" "github.com/gin-gonic/gin" + "github.com/nervosnetwork/ckb-sdk-go/address" "github.com/nervosnetwork/ckb-sdk-go/indexer" "github.com/nervosnetwork/ckb-sdk-go/types" "github.com/scorpiotzh/toolib" @@ -62,6 +63,11 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A return nil } fmt.Println(addrHex.DasAlgorithmId, addrHex.DasSubAlgorithmId, addrHex.AddressHex) + fromLock, _, err := h.dasCore.Daf().HexToScript(*addrHex) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "key info is invalid: "+err.Error()) + return nil + } req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType if req.Account == "" { @@ -101,10 +107,22 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A } basicPrice := baseAmount.Add(accountPrice) premiumPrice := decimal.NewFromInt(common.Premium(int64(acc.ExpiredAt), int64(nowTime))) + //totalPrice := basicPrice.Add(premiumPrice) //check user`s DP - - // - + amountDP := basicPrice.Add(premiumPrice).BigInt().Uint64() * common.UsdRateBase + log.Info("GetDpCells:", common.Bytes2Hex(fromLock.Args), amountDP) + _, _, _, err = h.dasCore.GetDpCells(&core.ParamGetDpCells{ + DasCache: h.dasCache, + LockScript: fromLock, + AmountNeed: amountDP, + CurrentBlockNumber: 0, + SearchOrder: indexer.SearchOrderAsc, + }) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeError500, err.Error()) + return fmt.Errorf("dasCore.GetDpCells err: ", err.Error()) + } + fmt.Println("11111111111111") var reqBuild reqBuildTx reqBuild.Action = common.DasBidExpiredAccountAuction reqBuild.Account = req.Account @@ -116,12 +134,33 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A PremiumPrice: premiumPrice, BidTime: int64(nowTime), } + + // to lock & normal cell lock + //转账地址 用于接收荷兰拍竞拍dp的地址 + if config.Cfg.Server.TransferWhitelist == "" || config.Cfg.Server.CapacityWhitelist == "" { + return fmt.Errorf("TransferWhitelist or CapacityWhitelist is empty") + } + toLock, err := address.Parse(config.Cfg.Server.TransferWhitelist) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeError500, err.Error()) + return fmt.Errorf("address.Parse err: %s", err.Error()) + } + //回收地址(接收dpcell 释放的capacity) + normalCellLock, err := address.Parse(config.Cfg.Server.CapacityWhitelist) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeError500, err.Error()) + return fmt.Errorf("address.Parse err: %s", err.Error()) + } var p auctionBidParams - p.account = &acc - p.basicPrice = basicPrice - p.premiumPrice = premiumPrice + p.Account = &acc + p.AmountDP = amountDP + p.FromLock = fromLock + p.ToLock = toLock.Script + p.NormalCellLock = normalCellLock.Script + //p.basicPrice = basicPrice + //p.premiumPrice = premiumPrice txParams, err := h.buildAuctionBidTx(&reqBuild, &p) - + fmt.Println("2222222222222") if err != nil { apiResp.ApiRespErr(http_api.ApiCodeError500, "build tx err: "+err.Error()) return fmt.Errorf("buildEditManagerTx err: %s", err.Error()) @@ -138,34 +177,41 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A } type auctionBidParams struct { - account *tables.TableAccountInfo - basicPrice decimal.Decimal - premiumPrice decimal.Decimal + Account *tables.TableAccountInfo + AmountDP uint64 + FromLock *types.Script + ToLock *types.Script + NormalCellLock *types.Script } func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*txbuilder.BuildTransactionParams, error) { var txParams txbuilder.BuildTransactionParams - - contractAcc, err := core.GetDasContractInfo(common.DasContractNameAccountCellType) + fmt.Println("44444444444") + //contractAcc, err := core.GetDasContractInfo(common.DasContractNameAccountCellType) + //if err != nil { + // return nil, fmt.Errorf("GetDasContractInfo err: %s", err.Error()) + //} + contractDas, err := core.GetDasContractInfo(common.DasContractNameDispatchCellType) if err != nil { return nil, fmt.Errorf("GetDasContractInfo err: %s", err.Error()) } - contractDas, err := core.GetDasContractInfo(common.DasContractNameDispatchCellType) + balanceContract, err := core.GetDasContractInfo(common.DasContractNameBalanceCellType) if err != nil { return nil, fmt.Errorf("GetDasContractInfo err: %s", err.Error()) } - // inputs account cell - accOutPoint := common.String2OutPointStruct(p.account.Outpoint) - txParams.Inputs = append(txParams.Inputs, &types.CellInput{ - PreviousOutput: accOutPoint, - }) + timeCell, err := h.dasCore.GetTimeCell() + if err != nil { + return nil, fmt.Errorf("GetTimeCell err: %s", err.Error()) + } + accOutPoint := common.String2OutPointStruct(p.Account.Outpoint) // witness account cell - res, err := h.dasCore.Client().GetTransaction(h.ctx, accOutPoint.TxHash) + accTx, err := h.dasCore.Client().GetTransaction(h.ctx, accOutPoint.TxHash) if err != nil { return nil, fmt.Errorf("GetTransaction err: %s", err.Error()) } - builderMap, err := witness.AccountCellDataBuilderMapFromTx(res.Transaction, common.DataTypeNew) + + builderMap, err := witness.AccountCellDataBuilderMapFromTx(accTx.Transaction, common.DataTypeNew) if err != nil { return nil, fmt.Errorf("AccountCellDataBuilderMapFromTx err: %s", err.Error()) } @@ -173,12 +219,10 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t if !ok { return nil, fmt.Errorf("builderMap not exist account: %s", req.Account) } - - timeCell, err := h.dasCore.GetTimeCell() - if err != nil { - return nil, fmt.Errorf("GetTimeCell err: %s", err.Error()) - } - + accCellCapacity := accTx.Transaction.Outputs[builder.Index].Capacity + oldAccOwnerArgs := accTx.Transaction.Outputs[builder.Index].Lock.Args + fmt.Println("55555555555") + // //witness //-----witness action actionWitness, err := witness.GenActionDataWitness(common.DasBidExpiredAccountAuction, nil) @@ -195,90 +239,127 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t }) txParams.Witnesses = append(txParams.Witnesses, accWitness) - // inputs - //-----AccountCell - accOutpoint := common.String2OutPointStruct(p.account.Outpoint) + //input account cell txParams.Inputs = append(txParams.Inputs, &types.CellInput{ - PreviousOutput: accOutpoint, + PreviousOutput: accOutPoint, }) - //------DPCell + //output account cell + newOwnerAddrHex := core.DasAddressHex{ + DasAlgorithmId: req.ChainType.ToDasAlgorithmId(true), + AddressHex: req.Address, + IsMulti: false, + ChainType: req.ChainType, + } + lockArgs, err := h.dasCore.Daf().HexToArgs(newOwnerAddrHex, newOwnerAddrHex) - //------NormalCell - needCapacity := res.Transaction.Outputs[builder.Index].Capacity - liveCell, totalCapacity, err := h.dasCore.GetBalanceCells(&core.ParamGetBalanceCells{ + txParams.Outputs = append(txParams.Outputs, &types.CellOutput{ + Capacity: accTx.Transaction.Outputs[builder.Index].Capacity, + Lock: contractDas.ToScript(lockArgs), + Type: accTx.Transaction.Outputs[builder.Index].Type, + }) + newExpiredAt := int64(builder.ExpiredAt) + common.OneYearSec + byteExpiredAt := molecule.Go64ToBytes(newExpiredAt) + accData = append(accData, accTx.Transaction.OutputsData[builder.Index][32:]...) + accData1 := accData[:common.ExpireTimeEndIndex-common.ExpireTimeLen] + accData2 := accData[common.ExpireTimeEndIndex:] + newAccData := append(accData1, byteExpiredAt...) + newAccData = append(newAccData, accData2...) + fmt.Println("newAccData: ", newAccData) + txParams.OutputsData = append(txParams.OutputsData, newAccData) // change expired_at + + //dp + liveCell, totalDP, totalCapacity, err := h.dasCore.GetDpCells(&core.ParamGetDpCells{ + DasCache: h.dasCache, + LockScript: p.FromLock, + AmountNeed: p.AmountDP, + CurrentBlockNumber: 0, + SearchOrder: indexer.SearchOrderAsc, + }) + if err != nil { + return nil, fmt.Errorf("GetDpCells err: %s", err.Error()) + } + + for _, v := range liveCell { + txParams.Inputs = append(txParams.Inputs, &types.CellInput{ + PreviousOutput: v.OutPoint, + }) + } + + // outputs + outputs, outputsData, normalCellCapacity, err := h.dasCore.SplitDPCell(&core.ParamSplitDPCell{ + FromLock: p.FromLock, //发送dp方的lock + ToLock: p.ToLock, //接收dp方的lock + DPLiveCell: liveCell, //发送方的dp cell + DPLiveCellCapacity: totalCapacity, //发送方dp的capacity + DPTotalAmount: totalDP, //总的dp金额 + DPTransferAmount: p.AmountDP, //要转账的dp金额 + DPSplitCount: config.Cfg.Server.SplitCount, + DPSplitAmount: config.Cfg.Server.SplitAmount, + NormalCellLock: p.NormalCellLock, //回收dp cell的ckb的接收地址 + }) + if err != nil { + return nil, fmt.Errorf("SplitDPCell err: %s", err.Error()) + } + for i, _ := range outputs { + txParams.Outputs = append(txParams.Outputs, outputs[i]) + txParams.OutputsData = append(txParams.OutputsData, outputsData[i]) + } + + //input dp cell capacity < output dp cell capacity 需要用注册商的nomal cell 来垫付 + //input dp cell capacity > output dp cell capacity : has been return in "h.dasCore.SplitDPCell" + normalCells, totalNormal, err := h.dasCore.GetBalanceCells(&core.ParamGetBalanceCells{ DasCache: h.dasCache, - LockScript: h.serverScript, - CapacityNeed: needCapacity, + LockScript: p.NormalCellLock, + CapacityNeed: normalCellCapacity + accCellCapacity, CapacityForChange: common.MinCellOccupiedCkb, SearchOrder: indexer.SearchOrderAsc, }) if err != nil { return nil, fmt.Errorf("GetBalanceCells err: %s", err.Error()) } - if change := totalCapacity - needCapacity; change > 0 { - splitCkb := 2000 * common.OneCkb - if config.Cfg.Server.SplitCkb > 0 { - splitCkb = config.Cfg.Server.SplitCkb * common.OneCkb - } - changeList, err := core.SplitOutputCell2(change, splitCkb, 200, h.serverScript, nil, indexer.SearchOrderAsc) - if err != nil { - return nil, fmt.Errorf("SplitOutputCell2 err: %s", err.Error()) - } - for i := 0; i < len(changeList); i++ { - txParams.Outputs = append(txParams.Outputs, changeList[i]) - txParams.OutputsData = append(txParams.OutputsData, []byte{}) - } - } - // inputs - for _, v := range liveCell { + for _, v := range normalCells { txParams.Inputs = append(txParams.Inputs, &types.CellInput{ PreviousOutput: v.OutPoint, }) } + //返还给旧账户的 capacity + txParams.Outputs = append(txParams.Outputs, &types.CellOutput{ + Capacity: accCellCapacity, + Lock: contractDas.ToScript(oldAccOwnerArgs), + Type: balanceContract.ToScript(nil), + }) + txParams.OutputsData = append(txParams.OutputsData, []byte{}) + + log.Info("normalCellCapacity:", normalCellCapacity, common.Bytes2Hex(p.NormalCellLock.Args)) + //找零 + if change := totalNormal - normalCellCapacity - accCellCapacity; change > 0 { + txParams.Outputs = append(txParams.Outputs, &types.CellOutput{ + Capacity: change, + Lock: p.NormalCellLock, + Type: nil, + }) + txParams.OutputsData = append(txParams.OutputsData, []byte{}) + } - //output + //注册商支付older owner的account cell的capacity //-----AccountCell - lockArgs, err := h.dasCore.Daf().HexToArgs(core.DasAddressHex{ - DasAlgorithmId: req.ChainType.ToDasAlgorithmId(true), - AddressHex: req.Address, - IsMulti: false, - ChainType: req.ChainType, - }, core.DasAddressHex{ - DasAlgorithmId: req.ChainType.ToDasAlgorithmId(true), - AddressHex: req.Address, - IsMulti: false, - ChainType: req.ChainType, - }) - txParams.Outputs = append(txParams.Outputs, &types.CellOutput{ - Capacity: res.Transaction.Outputs[builder.Index].Capacity, - Lock: contractDas.ToScript(lockArgs), - Type: contractAcc.ToScript(nil), - }) - newExpiredAt := int64(builder.ExpiredAt) + common.OneYearSec - byteExpiredAt := molecule.Go64ToBytes(newExpiredAt) - accData = append(accData, res.Transaction.OutputsData[builder.Index][32:]...) - accData1 := accData[:common.ExpireTimeEndIndex-common.ExpireTimeLen] - accData2 := accData[common.ExpireTimeEndIndex:] - newAccData := append(accData1, byteExpiredAt...) - newAccData = append(newAccData, accData2...) - txParams.OutputsData = append(txParams.OutputsData, newAccData) // change expired_at //DPCell //oldowner balanceCell oldOwnerAddrHex := core.DasAddressHex{ - DasAlgorithmId: p.account.OwnerChainType.ToDasAlgorithmId(true), - AddressHex: p.account.Owner, + DasAlgorithmId: p.Account.OwnerChainType.ToDasAlgorithmId(true), + AddressHex: p.Account.Owner, IsMulti: false, - ChainType: p.account.OwnerChainType, + ChainType: p.Account.OwnerChainType, } oldOwnerLockArgs, err := h.dasCore.Daf().HexToArgs(oldOwnerAddrHex, oldOwnerAddrHex) txParams.Outputs = append(txParams.Outputs, &types.CellOutput{ - Capacity: res.Transaction.Outputs[builder.Index].Capacity, + Capacity: accCellCapacity, Lock: contractDas.ToScript(oldOwnerLockArgs), - Type: contractAcc.ToScript(nil), + Type: balanceContract.ToScript(nil), }) txParams.OutputsData = append(txParams.OutputsData, []byte{}) diff --git a/http_server/handle/reverse_declare.go b/http_server/handle/reverse_declare.go index 675a44ff..f8586495 100644 --- a/http_server/handle/reverse_declare.go +++ b/http_server/handle/reverse_declare.go @@ -254,7 +254,7 @@ func (h *HttpHandle) buildTx(req *reqBuildTx, txParams *txbuilder.BuildTransacti case common.DasActionConfigSubAccountCustomScript: default: mmJsonObj, err = txBuilder.BuildMMJsonObj(req.EvmChainId) - if req.Action != tables.DasActionTransferBalance && req.Action != common.DasBidExpiredAccountAuction && err != nil { + if req.Action != tables.DasActionTransferBalance && err != nil { return nil, fmt.Errorf("txBuilder.BuildMMJsonObj err: %s", err.Error()) } else { log.Info("BuildTx:", mmJsonObj.String()) diff --git a/tables/t_auction_order.go b/tables/t_auction_order.go index 43756385..38065807 100644 --- a/tables/t_auction_order.go +++ b/tables/t_auction_order.go @@ -21,7 +21,7 @@ type TableAuctionOrder struct { SubAlgorithmId common.DasSubAlgorithmId `json:"sub_algorithm_id" gorm:"column:sub_algorithm_id"` BasicPrice decimal.Decimal `json:"basic_price" gorm:"column:basic_price;type:decimal(60,0) NOT NULL DEFAULT '0' COMMENT ''"` PremiumPrice decimal.Decimal `json:"premium_price" gorm:"column:premium_price;type:decimal(60,0) NOT NULL DEFAULT '0' COMMENT ''"` - Status int `json:"status"` + Status int `json:"status" ` BidTime int64 `json:"bid_time" gorm:"column:bid_time;type:bigint NOT NULL DEFAULT '0'"` Outpoint string `json:"outpoint" gorm:"column:outpoint;type:varchar(255) DEFAULT NULL"` CreatedAt time.Time `json:"created_at" gorm:"column:created_at;type:timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''"` From 56e374f24e609a939558a8a2e8cc16dc9fee2704 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Thu, 9 Nov 2023 17:48:54 +0800 Subject: [PATCH 14/67] update daslib --- go.mod | 4 ++-- go.sum | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/go.mod b/go.mod index 625aefc0..f8553cbf 100644 --- a/go.mod +++ b/go.mod @@ -3,10 +3,10 @@ module das_register_server go 1.18 require ( - github.com/dotbitHQ/das-lib v1.1.1-0.20231106140104-e0342efb3797 + github.com/dotbitHQ/das-lib v1.1.1-0.20231109094712-07018497b856 github.com/ethereum/go-ethereum v1.10.26 github.com/fsnotify/fsnotify v1.5.4 - github.com/getsentry/sentry-go v0.24.0 // indirect + github.com/getsentry/sentry-go v0.25.0 // indirect github.com/gin-gonic/gin v1.9.1 github.com/go-redis/redis v6.15.9+incompatible github.com/minio/blake2b-simd v0.0.0-20160723061019-3f5f724cb5b1 diff --git a/go.sum b/go.sum index 43212fbe..061375c6 100644 --- a/go.sum +++ b/go.sum @@ -145,8 +145,8 @@ github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5O github.com/docker/docker v1.4.2-0.20180625184442-8e610b2b55bf/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/dop251/goja v0.0.0-20211011172007-d99e4b8cbf48/go.mod h1:R9ET47fwRVRPZnOGvHxxhuZcbrMCuiqOz3Rlrh4KSnk= github.com/dop251/goja_nodejs v0.0.0-20210225215109-d91c329300e7/go.mod h1:hn7BA7c8pLvoGndExHudxTDKZ84Pyvv+90pbBjbTz0Y= -github.com/dotbitHQ/das-lib v1.1.1-0.20231106140104-e0342efb3797 h1:yHR+ePURrDQajBkVDbr3UqiOa7MZEFmWifcnfv1r0Dc= -github.com/dotbitHQ/das-lib v1.1.1-0.20231106140104-e0342efb3797/go.mod h1:6zhVMmqpRLq1bR8BqAdh/Nf8GQdJ5pREhBAwnImYQGg= +github.com/dotbitHQ/das-lib v1.1.1-0.20231109094712-07018497b856 h1:K3j0mkvHpAFdUWabYLqzWAsmrUEXNN/1q+fu8I5vfFU= +github.com/dotbitHQ/das-lib v1.1.1-0.20231109094712-07018497b856/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts= github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= github.com/elazarl/goproxy v0.0.0-20221015165544-a0805db90819 h1:RIB4cRk+lBqKK3Oy0r2gRX4ui7tuhiZq2SuTtTCi0/0= @@ -175,8 +175,8 @@ github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9 github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= github.com/getkin/kin-openapi v0.53.0/go.mod h1:7Yn5whZr5kJi6t+kShccXS8ae1APpYTW6yheSwk8Yi4= github.com/getkin/kin-openapi v0.61.0/go.mod h1:7Yn5whZr5kJi6t+kShccXS8ae1APpYTW6yheSwk8Yi4= -github.com/getsentry/sentry-go v0.24.0 h1:02b7qEmJ56EHGe9KFgjArjU/vG/aywm7Efgu+iPc01Y= -github.com/getsentry/sentry-go v0.24.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= +github.com/getsentry/sentry-go v0.25.0 h1:q6Eo+hS+yoJlTO3uu/azhQadsD8V+jQn2D8VvX1eOyI= +github.com/getsentry/sentry-go v0.25.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= From 80c88e449f40f834db7dd3916696177453437229 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Thu, 9 Nov 2023 18:22:03 +0800 Subject: [PATCH 15/67] remove auction test code --- http_server/handle/transaction_send.go | 56 -------------------------- 1 file changed, 56 deletions(-) diff --git a/http_server/handle/transaction_send.go b/http_server/handle/transaction_send.go index 6134f118..14ad7c8c 100644 --- a/http_server/handle/transaction_send.go +++ b/http_server/handle/transaction_send.go @@ -1,7 +1,6 @@ package handle import ( - "crypto/sha256" "das_register_server/tables" "encoding/json" "fmt" @@ -150,61 +149,6 @@ func (h *HttpHandle) doTransactionSend(req *ReqTransactionSend, apiResp *api_cod } } - //test for dutch auction - if sic.Action == common.DasBidExpiredAccountAuction { - // operate limit - _ = h.rc.SetApiLimit(sic.ChainType, sic.Address, sic.Action) - _ = h.rc.SetAccountLimit(sic.Account, time.Minute*2) - - hash := sha256.Sum256([]byte(randStr(10))) - resp.Hash = common.Bytes2Hex(hash[:]) - // cache tx inputs - h.dasCache.AddCellInputByAction("", sic.BuilderTx.Transaction.Inputs) - // pending tx - pending := tables.TableRegisterPendingInfo{ - Account: sic.Account, - Action: sic.Action, - ChainType: sic.ChainType, - Address: sic.Address, - Capacity: sic.Capacity, - Outpoint: common.OutPoint2String(resp.Hash, 0), - BlockTimestamp: uint64(time.Now().UnixNano() / 1e6), - } - if err := h.dbDao.CreatePending(&pending); err != nil { - log.Error("CreatePending err: ", err.Error(), toolib.JsonString(pending)) - } - - if sic.Action == common.DasBidExpiredAccountAuction { - addressHex, err := h.dasCore.Daf().NormalToHex(core.DasAddressNormal{ - ChainType: sic.ChainType, - AddressNormal: sic.Address, - Is712: true, - }) - if err != nil { - apiResp.ApiRespErr(api_code.ApiCodeParamsInvalid, "address NormalToHex err") - return fmt.Errorf("NormalToHex err: %s", err.Error()) - } - auctionOrder := tables.TableAuctionOrder{ - Account: sic.Account, - AccountId: common.Bytes2Hex(common.GetAccountIdByAccount(sic.Account)), - Address: sic.Address, - BasicPrice: sic.AuctionInfo.BasicPrice, - PremiumPrice: sic.AuctionInfo.PremiumPrice, - BidTime: sic.AuctionInfo.BidTime, - AlgorithmId: addressHex.DasAlgorithmId, - SubAlgorithmId: addressHex.DasSubAlgorithmId, - ChainType: sic.ChainType, - Outpoint: pending.Outpoint, - } - if err = h.dbDao.CreateAuctionOrder(auctionOrder); err != nil { - log.Error("CreateAuctionOrder err: ", err.Error(), toolib.JsonString(auctionOrder)) - } - } - - apiResp.ApiRespOK(resp) - return nil - } - // send tx if hash, err := txBuilder.SendTransaction(); err != nil { if strings.Contains(err.Error(), "PoolRejectedDuplicatedTransaction") || From 62df3ee20b27acec43be8c2a26cc9ef2c630e5c1 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Thu, 9 Nov 2023 18:35:34 +0800 Subject: [PATCH 16/67] dutch auction tx --- http_server/handle/auction_bid.go | 35 +------------------------------ 1 file changed, 1 insertion(+), 34 deletions(-) diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index ae828184..7b9e8259 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -122,7 +122,6 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A apiResp.ApiRespErr(http_api.ApiCodeError500, err.Error()) return fmt.Errorf("dasCore.GetDpCells err: ", err.Error()) } - fmt.Println("11111111111111") var reqBuild reqBuildTx reqBuild.Action = common.DasBidExpiredAccountAuction reqBuild.Account = req.Account @@ -157,10 +156,7 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A p.FromLock = fromLock p.ToLock = toLock.Script p.NormalCellLock = normalCellLock.Script - //p.basicPrice = basicPrice - //p.premiumPrice = premiumPrice txParams, err := h.buildAuctionBidTx(&reqBuild, &p) - fmt.Println("2222222222222") if err != nil { apiResp.ApiRespErr(http_api.ApiCodeError500, "build tx err: "+err.Error()) return fmt.Errorf("buildEditManagerTx err: %s", err.Error()) @@ -186,11 +182,6 @@ type auctionBidParams struct { func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*txbuilder.BuildTransactionParams, error) { var txParams txbuilder.BuildTransactionParams - fmt.Println("44444444444") - //contractAcc, err := core.GetDasContractInfo(common.DasContractNameAccountCellType) - //if err != nil { - // return nil, fmt.Errorf("GetDasContractInfo err: %s", err.Error()) - //} contractDas, err := core.GetDasContractInfo(common.DasContractNameDispatchCellType) if err != nil { return nil, fmt.Errorf("GetDasContractInfo err: %s", err.Error()) @@ -221,10 +212,7 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t } accCellCapacity := accTx.Transaction.Outputs[builder.Index].Capacity oldAccOwnerArgs := accTx.Transaction.Outputs[builder.Index].Lock.Args - fmt.Println("55555555555") - // - //witness - //-----witness action + actionWitness, err := witness.GenActionDataWitness(common.DasBidExpiredAccountAuction, nil) if err != nil { return nil, fmt.Errorf("GenActionDataWitness err: %s", err.Error()) @@ -342,26 +330,5 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t txParams.OutputsData = append(txParams.OutputsData, []byte{}) } - //注册商支付older owner的account cell的capacity - - //-----AccountCell - - //DPCell - - //oldowner balanceCell - oldOwnerAddrHex := core.DasAddressHex{ - DasAlgorithmId: p.Account.OwnerChainType.ToDasAlgorithmId(true), - AddressHex: p.Account.Owner, - IsMulti: false, - ChainType: p.Account.OwnerChainType, - } - oldOwnerLockArgs, err := h.dasCore.Daf().HexToArgs(oldOwnerAddrHex, oldOwnerAddrHex) - txParams.Outputs = append(txParams.Outputs, &types.CellOutput{ - Capacity: accCellCapacity, - Lock: contractDas.ToScript(oldOwnerLockArgs), - Type: balanceContract.ToScript(nil), - }) - txParams.OutputsData = append(txParams.OutputsData, []byte{}) - return &txParams, nil } From 5318a83edf4c16bfb08c33db4460829f7ce7b531 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Thu, 9 Nov 2023 19:19:45 +0800 Subject: [PATCH 17/67] update price --- API.md | 3 ++- http_server/handle/auction_info.go | 8 +++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/API.md b/API.md index 38d3ab8a..4a3b911c 100644 --- a/API.md +++ b/API.md @@ -1920,7 +1920,8 @@ curl --location 'http://127.0.0.1:8120/v1/account/auction/info' \ "err_no": 0, "err_msg": "", "data": { - "basic_price": "5.8", + "account_price": "5", + "base_amount": "0.82", "premium_price": 20 } } diff --git a/http_server/handle/auction_info.go b/http_server/handle/auction_info.go index 7adbbd6e..f6aa0250 100644 --- a/http_server/handle/auction_info.go +++ b/http_server/handle/auction_info.go @@ -20,7 +20,9 @@ type ReqAuctionPrice struct { } type RespAuctionPrice struct { - BasicPrice decimal.Decimal `json:"basic_price"` + //BasicPrice decimal.Decimal `json:"basic_price"` + AccountPrice decimal.Decimal `json:"account_price"` + BaseAmount decimal.Decimal `json:"base_amount"` PremiumPrice int64 `json:"premium_price"` } @@ -81,8 +83,8 @@ func (h *HttpHandle) doGetAccountAuctionPrice(req *ReqAuctionPrice, apiResp *htt apiResp.ApiRespErr(http_api.ApiCodeError500, "get account price err") return fmt.Errorf("getAccountPrice err: %s", err.Error()) } - resp.BasicPrice = baseAmount.Add(accountPrice) - fmt.Println(acc.ExpiredAt) + resp.BaseAmount = baseAmount + resp.AccountPrice = accountPrice resp.PremiumPrice = common.Premium(int64(acc.ExpiredAt), int64(nowTime)) apiResp.ApiRespOK(resp) return From 8c289e33994086998bd002ea6b916deab1f289c8 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Thu, 9 Nov 2023 19:29:17 +0800 Subject: [PATCH 18/67] update auction/info --- API.md | 1 + http_server/handle/auction_info.go | 2 ++ 2 files changed, 3 insertions(+) diff --git a/API.md b/API.md index 4a3b911c..b4ca5b45 100644 --- a/API.md +++ b/API.md @@ -1874,6 +1874,7 @@ curl -X POST http://127.0.0.1:8120/v1/node/ckb/rpc -d'{"jsonrpc":"2.0","id":2976 "account_id": "", "account": "", "bid_status": 2, + "hash": "", "start_auction_time": 0, "end_auction_time": 0, "expired_at": 0, diff --git a/http_server/handle/auction_info.go b/http_server/handle/auction_info.go index f6aa0250..388ad7ad 100644 --- a/http_server/handle/auction_info.go +++ b/http_server/handle/auction_info.go @@ -101,6 +101,7 @@ type RespAccountAuctionInfo struct { AccountId string `json:"account_id"` Account string `json:"account"` BidStatus tables.BidStatus `json:"bid_status"` + Hash string `json:"hash"` StartsaleTime uint64 `json:"start_auction_time"` EndSaleTime uint64 `json:"end_auction_time"` ExipiredTime uint64 `json:"expired_at"` @@ -189,6 +190,7 @@ func (h *HttpHandle) doGetAccountAuctionInfo(req *ReqAccountAuctionInfo, apiResp //被自己竞拍 if v.AlgorithmId == addrHex.DasAlgorithmId && v.SubAlgorithmId == addrHex.DasSubAlgorithmId && v.Address == addrHex.AddressHex { resp.BidStatus = tables.BidStatusByMe + resp.Hash, _ = common.String2OutPoint(v.Outpoint) } } apiResp.ApiRespOK(resp) From f8cbb83376117298291f824dc5d20cce3700d0e9 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Thu, 9 Nov 2023 21:32:09 +0800 Subject: [PATCH 19/67] replace server lock --- http_server/handle/auction_bid.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index 7b9e8259..ee3392f6 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -298,7 +298,7 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t //input dp cell capacity > output dp cell capacity : has been return in "h.dasCore.SplitDPCell" normalCells, totalNormal, err := h.dasCore.GetBalanceCells(&core.ParamGetBalanceCells{ DasCache: h.dasCache, - LockScript: p.NormalCellLock, + LockScript: h.serverScript, CapacityNeed: normalCellCapacity + accCellCapacity, CapacityForChange: common.MinCellOccupiedCkb, SearchOrder: indexer.SearchOrderAsc, From ebd83279804f60298b58456ec099937b2104bdd3 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Thu, 9 Nov 2023 21:52:23 +0800 Subject: [PATCH 20/67] update server script --- http_server/handle/auction_bid.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index ee3392f6..9fbfe218 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -324,7 +324,7 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t if change := totalNormal - normalCellCapacity - accCellCapacity; change > 0 { txParams.Outputs = append(txParams.Outputs, &types.CellOutput{ Capacity: change, - Lock: p.NormalCellLock, + Lock: h.serverScript, Type: nil, }) txParams.OutputsData = append(txParams.OutputsData, []byte{}) From fd4ea7100884c3a63528137303e8c983bcc0c46e Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Thu, 9 Nov 2023 22:17:16 +0800 Subject: [PATCH 21/67] add celldeps --- http_server/handle/auction_bid.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index 9fbfe218..407f0aeb 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -190,6 +190,7 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t if err != nil { return nil, fmt.Errorf("GetDasContractInfo err: %s", err.Error()) } + timeCell, err := h.dasCore.GetTimeCell() if err != nil { return nil, fmt.Errorf("GetTimeCell err: %s", err.Error()) @@ -330,5 +331,31 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t txParams.OutputsData = append(txParams.OutputsData, []byte{}) } + // cell deps + accContract, err := core.GetDasContractInfo(common.DasContractNameAccountCellType) + if err != nil { + return nil, fmt.Errorf("GetDasContractInfo err: %s", err.Error()) + } + configCellMain, err := core.GetDasConfigCellInfo(common.ConfigCellTypeArgsMain) + if err != nil { + return nil, fmt.Errorf("GetDasConfigCellInfo err: %s", err.Error()) + } + configCellDP, err := core.GetDasConfigCellInfo(common.ConfigCellTypeArgsDPoint) + if err != nil { + return nil, fmt.Errorf("GetDasConfigCellInfo err: %s", err.Error()) + } + contractDP, err := core.GetDasContractInfo(common.DasContractNameDpCellType) + if err != nil { + return nil, fmt.Errorf("GetDasContractInfo err: %s", err.Error()) + } + txParams.CellDeps = append(txParams.CellDeps, + configCellMain.ToCellDep(), + configCellDP.ToCellDep(), + contractDP.ToCellDep(), + timeCell.ToCellDep(), + accContract.ToCellDep(), + contractDas.ToCellDep(), + + ) return &txParams, nil } From 4e36b2da8f5e9c3caea91d269aa9ce2dc5e22555 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Thu, 9 Nov 2023 23:12:57 +0800 Subject: [PATCH 22/67] update das lib --- go.mod | 2 +- go.sum | 4 ++-- http_server/handle/auction_bid.go | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/go.mod b/go.mod index f8553cbf..bdf0b8bc 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module das_register_server go 1.18 require ( - github.com/dotbitHQ/das-lib v1.1.1-0.20231109094712-07018497b856 + github.com/dotbitHQ/das-lib v1.1.1-0.20231109151152-b4bf37718c83 github.com/ethereum/go-ethereum v1.10.26 github.com/fsnotify/fsnotify v1.5.4 github.com/getsentry/sentry-go v0.25.0 // indirect diff --git a/go.sum b/go.sum index 061375c6..baf02ee5 100644 --- a/go.sum +++ b/go.sum @@ -145,8 +145,8 @@ github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5O github.com/docker/docker v1.4.2-0.20180625184442-8e610b2b55bf/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/dop251/goja v0.0.0-20211011172007-d99e4b8cbf48/go.mod h1:R9ET47fwRVRPZnOGvHxxhuZcbrMCuiqOz3Rlrh4KSnk= github.com/dop251/goja_nodejs v0.0.0-20210225215109-d91c329300e7/go.mod h1:hn7BA7c8pLvoGndExHudxTDKZ84Pyvv+90pbBjbTz0Y= -github.com/dotbitHQ/das-lib v1.1.1-0.20231109094712-07018497b856 h1:K3j0mkvHpAFdUWabYLqzWAsmrUEXNN/1q+fu8I5vfFU= -github.com/dotbitHQ/das-lib v1.1.1-0.20231109094712-07018497b856/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= +github.com/dotbitHQ/das-lib v1.1.1-0.20231109151152-b4bf37718c83 h1:GajWzUk0CcOrbVwVbmoT0tsnJLMezo5sYdmZhbIH+M4= +github.com/dotbitHQ/das-lib v1.1.1-0.20231109151152-b4bf37718c83/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts= github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= github.com/elazarl/goproxy v0.0.0-20221015165544-a0805db90819 h1:RIB4cRk+lBqKK3Oy0r2gRX4ui7tuhiZq2SuTtTCi0/0= diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index 407f0aeb..adbb9e58 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -225,6 +225,7 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t NewIndex: 0, Action: common.DasBidExpiredAccountAuction, LastTransferAccountAt: timeCell.Timestamp(), + RegisterAt: uint64(timeCell.Timestamp()), }) txParams.Witnesses = append(txParams.Witnesses, accWitness) @@ -247,7 +248,7 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t Lock: contractDas.ToScript(lockArgs), Type: accTx.Transaction.Outputs[builder.Index].Type, }) - newExpiredAt := int64(builder.ExpiredAt) + common.OneYearSec + newExpiredAt := timeCell.Timestamp() + common.OneYearSec byteExpiredAt := molecule.Go64ToBytes(newExpiredAt) accData = append(accData, accTx.Transaction.OutputsData[builder.Index][32:]...) accData1 := accData[:common.ExpireTimeEndIndex-common.ExpireTimeLen] @@ -355,7 +356,6 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t timeCell.ToCellDep(), accContract.ToCellDep(), contractDas.ToCellDep(), - ) return &txParams, nil } From f4e6ab4d5ae54c93997ef3cd1f28f19a4dbe72fa Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Fri, 10 Nov 2023 11:21:53 +0800 Subject: [PATCH 23/67] ConfigCellAcccount --- http_server/handle/auction_bid.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index adbb9e58..3eadc1e0 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -333,6 +333,10 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t } // cell deps + configCellAcc, err := core.GetDasConfigCellInfo(common.ConfigCellTypeArgsAccount) + if err != nil { + return nil, fmt.Errorf("GetDasConfigCellInfo err: %s", err.Error()) + } accContract, err := core.GetDasContractInfo(common.DasContractNameAccountCellType) if err != nil { return nil, fmt.Errorf("GetDasContractInfo err: %s", err.Error()) @@ -350,6 +354,7 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t return nil, fmt.Errorf("GetDasContractInfo err: %s", err.Error()) } txParams.CellDeps = append(txParams.CellDeps, + configCellAcc.ToCellDep(), configCellMain.ToCellDep(), configCellDP.ToCellDep(), contractDP.ToCellDep(), From 0a66779314476df2799c592723155e7a2131823b Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Fri, 10 Nov 2023 11:36:22 +0800 Subject: [PATCH 24/67] add priceconfig --- http_server/handle/auction_bid.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index 3eadc1e0..9af84e91 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -353,8 +353,13 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t if err != nil { return nil, fmt.Errorf("GetDasContractInfo err: %s", err.Error()) } + priceConfig, err := core.GetDasConfigCellInfo(common.ConfigCellTypeArgsPrice) + if err != nil { + return nil, fmt.Errorf("GetDasConfigCellInfo err: %s", err.Error()) + } txParams.CellDeps = append(txParams.CellDeps, configCellAcc.ToCellDep(), + priceConfig.ToCellDep(), configCellMain.ToCellDep(), configCellDP.ToCellDep(), contractDP.ToCellDep(), From 83bc45416dd9bbe5998da2581a4089155e402c32 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Fri, 10 Nov 2023 11:45:05 +0800 Subject: [PATCH 25/67] add height cell --- http_server/handle/auction_bid.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index 9af84e91..7b57f7e6 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -190,7 +190,10 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t if err != nil { return nil, fmt.Errorf("GetDasContractInfo err: %s", err.Error()) } - + quoteCell, err := h.dasCore.GetQuoteCell() + if err != nil { + return nil, fmt.Errorf("GetQuoteCell err: %s", err.Error()) + } timeCell, err := h.dasCore.GetTimeCell() if err != nil { return nil, fmt.Errorf("GetTimeCell err: %s", err.Error()) @@ -353,6 +356,10 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t if err != nil { return nil, fmt.Errorf("GetDasContractInfo err: %s", err.Error()) } + heightCell, err := h.dasCore.GetHeightCell() + if err != nil { + return nil, fmt.Errorf("GetHeightCell err: %s", err.Error()) + } priceConfig, err := core.GetDasConfigCellInfo(common.ConfigCellTypeArgsPrice) if err != nil { return nil, fmt.Errorf("GetDasConfigCellInfo err: %s", err.Error()) @@ -366,6 +373,8 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t timeCell.ToCellDep(), accContract.ToCellDep(), contractDas.ToCellDep(), + heightCell.ToCellDep(), + quoteCell.ToCellDep(), ) return &txParams, nil } From 5cd026c068f54944738ca6b648582ac824e827ca Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Fri, 10 Nov 2023 14:39:21 +0800 Subject: [PATCH 26/67] update daslib --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index bdf0b8bc..1a568c1a 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module das_register_server go 1.18 require ( - github.com/dotbitHQ/das-lib v1.1.1-0.20231109151152-b4bf37718c83 + github.com/dotbitHQ/das-lib v1.1.1-0.20231110063759-7f1519db22e7 github.com/ethereum/go-ethereum v1.10.26 github.com/fsnotify/fsnotify v1.5.4 github.com/getsentry/sentry-go v0.25.0 // indirect diff --git a/go.sum b/go.sum index baf02ee5..1ef9e15a 100644 --- a/go.sum +++ b/go.sum @@ -145,8 +145,8 @@ github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5O github.com/docker/docker v1.4.2-0.20180625184442-8e610b2b55bf/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/dop251/goja v0.0.0-20211011172007-d99e4b8cbf48/go.mod h1:R9ET47fwRVRPZnOGvHxxhuZcbrMCuiqOz3Rlrh4KSnk= github.com/dop251/goja_nodejs v0.0.0-20210225215109-d91c329300e7/go.mod h1:hn7BA7c8pLvoGndExHudxTDKZ84Pyvv+90pbBjbTz0Y= -github.com/dotbitHQ/das-lib v1.1.1-0.20231109151152-b4bf37718c83 h1:GajWzUk0CcOrbVwVbmoT0tsnJLMezo5sYdmZhbIH+M4= -github.com/dotbitHQ/das-lib v1.1.1-0.20231109151152-b4bf37718c83/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= +github.com/dotbitHQ/das-lib v1.1.1-0.20231110063759-7f1519db22e7 h1:7bvOXsHCkqbRCER+S51FHxMtHVFReenga+ozvAuq3rE= +github.com/dotbitHQ/das-lib v1.1.1-0.20231110063759-7f1519db22e7/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts= github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= github.com/elazarl/goproxy v0.0.0-20221015165544-a0805db90819 h1:RIB4cRk+lBqKK3Oy0r2gRX4ui7tuhiZq2SuTtTCi0/0= From 7f92ccde0030cb59854bdfd094a6aef45aa7f58b Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Fri, 10 Nov 2023 16:30:29 +0800 Subject: [PATCH 27/67] test price --- http_server/handle/auction_bid.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index 7b57f7e6..4fb4e74f 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -106,7 +106,10 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A return fmt.Errorf("getAccountPrice err: %s", err.Error()) } basicPrice := baseAmount.Add(accountPrice) + fmt.Println("----------expiredat: ", int64(acc.ExpiredAt)) + fmt.Println("----------nowTime: ", int64(nowTime)) premiumPrice := decimal.NewFromInt(common.Premium(int64(acc.ExpiredAt), int64(nowTime))) + fmt.Println("----------premiumPrice:", premiumPrice) //totalPrice := basicPrice.Add(premiumPrice) //check user`s DP amountDP := basicPrice.Add(premiumPrice).BigInt().Uint64() * common.UsdRateBase @@ -227,7 +230,9 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t OldIndex: 0, NewIndex: 0, Action: common.DasBidExpiredAccountAuction, + LastEditRecordsAt: timeCell.Timestamp(), LastTransferAccountAt: timeCell.Timestamp(), + LastEditManagerAt: timeCell.Timestamp(), RegisterAt: uint64(timeCell.Timestamp()), }) txParams.Witnesses = append(txParams.Witnesses, accWitness) From 7db3fee691a53cb03382a87b5868781eed5425e2 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Fri, 10 Nov 2023 17:03:55 +0800 Subject: [PATCH 28/67] auction price --- http_server/handle/auction_bid.go | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index 4fb4e74f..be32eec2 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -106,13 +106,12 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A return fmt.Errorf("getAccountPrice err: %s", err.Error()) } basicPrice := baseAmount.Add(accountPrice) - fmt.Println("----------expiredat: ", int64(acc.ExpiredAt)) - fmt.Println("----------nowTime: ", int64(nowTime)) + + log.Info("expiredat: ", int64(acc.ExpiredAt), "nowTime: ", int64(nowTime)) premiumPrice := decimal.NewFromInt(common.Premium(int64(acc.ExpiredAt), int64(nowTime))) - fmt.Println("----------premiumPrice:", premiumPrice) - //totalPrice := basicPrice.Add(premiumPrice) - //check user`s DP - amountDP := basicPrice.Add(premiumPrice).BigInt().Uint64() * common.UsdRateBase + amountDP := basicPrice.Add(premiumPrice).Mul(decimal.NewFromInt(common.UsdRateBase)).BigInt().Uint64() + log.Info("baseAmount: ", baseAmount, " accountPrice: ", accountPrice, " basicPrice: ", basicPrice, " premiumPrice: ", premiumPrice, " amountDP: ", amountDP) + log.Info("GetDpCells:", common.Bytes2Hex(fromLock.Args), amountDP) _, _, _, err = h.dasCore.GetDpCells(&core.ParamGetDpCells{ DasCache: h.dasCache, From 83dcff91b0ee2ca3685331d179821eb6ccaf2aee Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Fri, 10 Nov 2023 17:26:54 +0800 Subject: [PATCH 29/67] update timecell --- http_server/handle/auction_bid.go | 34 ++++++++++++++++++------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index be32eec2..d5943549 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -18,7 +18,6 @@ import ( "github.com/shopspring/decimal" "gorm.io/gorm" "net/http" - "time" ) type ReqAuctionBid struct { @@ -80,7 +79,12 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A apiResp.ApiRespErr(http_api.ApiCodeDbError, "search account err") return fmt.Errorf("SearchAccount err: %s", err.Error()) } - nowTime := uint64(time.Now().Unix()) + + timeCell, err := h.dasCore.GetTimeCell() + if err != nil { + return fmt.Errorf("GetTimeCell err: %s", err.Error()) + } + nowTime := timeCell.Timestamp() //exp + 90 + 27 +3 //now > exp+117 exp< now - 117 //now< exp+90 exp>now -90 @@ -107,8 +111,8 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A } basicPrice := baseAmount.Add(accountPrice) - log.Info("expiredat: ", int64(acc.ExpiredAt), "nowTime: ", int64(nowTime)) - premiumPrice := decimal.NewFromInt(common.Premium(int64(acc.ExpiredAt), int64(nowTime))) + log.Info("expiredat: ", int64(acc.ExpiredAt), "nowTime: ", nowTime) + premiumPrice := decimal.NewFromInt(common.Premium(int64(acc.ExpiredAt), nowTime)) amountDP := basicPrice.Add(premiumPrice).Mul(decimal.NewFromInt(common.UsdRateBase)).BigInt().Uint64() log.Info("baseAmount: ", baseAmount, " accountPrice: ", accountPrice, " basicPrice: ", basicPrice, " premiumPrice: ", premiumPrice, " amountDP: ", amountDP) @@ -158,6 +162,7 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A p.FromLock = fromLock p.ToLock = toLock.Script p.NormalCellLock = normalCellLock.Script + p.TimeCell = timeCell txParams, err := h.buildAuctionBidTx(&reqBuild, &p) if err != nil { apiResp.ApiRespErr(http_api.ApiCodeError500, "build tx err: "+err.Error()) @@ -180,6 +185,7 @@ type auctionBidParams struct { FromLock *types.Script ToLock *types.Script NormalCellLock *types.Script + TimeCell *core.TimeCell } func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*txbuilder.BuildTransactionParams, error) { @@ -196,10 +202,10 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t if err != nil { return nil, fmt.Errorf("GetQuoteCell err: %s", err.Error()) } - timeCell, err := h.dasCore.GetTimeCell() - if err != nil { - return nil, fmt.Errorf("GetTimeCell err: %s", err.Error()) - } + //timeCell, err := h.dasCore.GetTimeCell() + //if err != nil { + // return nil, fmt.Errorf("GetTimeCell err: %s", err.Error()) + //} accOutPoint := common.String2OutPointStruct(p.Account.Outpoint) // witness account cell @@ -229,10 +235,10 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t OldIndex: 0, NewIndex: 0, Action: common.DasBidExpiredAccountAuction, - LastEditRecordsAt: timeCell.Timestamp(), - LastTransferAccountAt: timeCell.Timestamp(), - LastEditManagerAt: timeCell.Timestamp(), - RegisterAt: uint64(timeCell.Timestamp()), + LastEditRecordsAt: p.TimeCell.Timestamp(), + LastTransferAccountAt: p.TimeCell.Timestamp(), + LastEditManagerAt: p.TimeCell.Timestamp(), + RegisterAt: uint64(p.TimeCell.Timestamp()), }) txParams.Witnesses = append(txParams.Witnesses, accWitness) @@ -255,7 +261,7 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t Lock: contractDas.ToScript(lockArgs), Type: accTx.Transaction.Outputs[builder.Index].Type, }) - newExpiredAt := timeCell.Timestamp() + common.OneYearSec + newExpiredAt := p.TimeCell.Timestamp() + common.OneYearSec byteExpiredAt := molecule.Go64ToBytes(newExpiredAt) accData = append(accData, accTx.Transaction.OutputsData[builder.Index][32:]...) accData1 := accData[:common.ExpireTimeEndIndex-common.ExpireTimeLen] @@ -374,7 +380,7 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t configCellMain.ToCellDep(), configCellDP.ToCellDep(), contractDP.ToCellDep(), - timeCell.ToCellDep(), + p.TimeCell.ToCellDep(), accContract.ToCellDep(), contractDas.ToCellDep(), heightCell.ToCellDep(), From f564ddde983208e552118b13003816a941e03a99 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Mon, 13 Nov 2023 15:02:36 +0800 Subject: [PATCH 30/67] update baseamount --- http_server/handle/account_detail.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/http_server/handle/account_detail.go b/http_server/handle/account_detail.go index 7346de83..719a41e0 100644 --- a/http_server/handle/account_detail.go +++ b/http_server/handle/account_detail.go @@ -136,7 +136,7 @@ func (h *HttpHandle) getAccountPrice(accLen uint8, args, account string, isRenew baseAmount, _ = decimal.NewFromString(fmt.Sprintf("%d", basicCapacity)) decQuote, _ := decimal.NewFromString(fmt.Sprintf("%d", quote)) decUsdRateBase := decimal.NewFromInt(common.UsdRateBase) - baseAmount = baseAmount.Mul(decQuote).DivRound(decUsdRateBase, 2) + baseAmount = baseAmount.Mul(decQuote).DivRound(decUsdRateBase, 6) if isRenew { accountPrice, _ = decimal.NewFromString(fmt.Sprintf("%d", renewPrice)) From dde880b214689422436f6dacf0af0c8f871e98f2 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Mon, 13 Nov 2023 18:09:46 +0800 Subject: [PATCH 31/67] update das-lib --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 1a568c1a..272f23cf 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module das_register_server go 1.18 require ( - github.com/dotbitHQ/das-lib v1.1.1-0.20231110063759-7f1519db22e7 + github.com/dotbitHQ/das-lib v1.1.1-0.20231113100809-ae2914dc576c github.com/ethereum/go-ethereum v1.10.26 github.com/fsnotify/fsnotify v1.5.4 github.com/getsentry/sentry-go v0.25.0 // indirect diff --git a/go.sum b/go.sum index 1ef9e15a..ca2f37e2 100644 --- a/go.sum +++ b/go.sum @@ -145,8 +145,8 @@ github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5O github.com/docker/docker v1.4.2-0.20180625184442-8e610b2b55bf/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/dop251/goja v0.0.0-20211011172007-d99e4b8cbf48/go.mod h1:R9ET47fwRVRPZnOGvHxxhuZcbrMCuiqOz3Rlrh4KSnk= github.com/dop251/goja_nodejs v0.0.0-20210225215109-d91c329300e7/go.mod h1:hn7BA7c8pLvoGndExHudxTDKZ84Pyvv+90pbBjbTz0Y= -github.com/dotbitHQ/das-lib v1.1.1-0.20231110063759-7f1519db22e7 h1:7bvOXsHCkqbRCER+S51FHxMtHVFReenga+ozvAuq3rE= -github.com/dotbitHQ/das-lib v1.1.1-0.20231110063759-7f1519db22e7/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= +github.com/dotbitHQ/das-lib v1.1.1-0.20231113100809-ae2914dc576c h1:+3UOFJwx+ECqQUsQZMVqVXP7zasvHFDxX8hDRHXIS+w= +github.com/dotbitHQ/das-lib v1.1.1-0.20231113100809-ae2914dc576c/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts= github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= github.com/elazarl/goproxy v0.0.0-20221015165544-a0805db90819 h1:RIB4cRk+lBqKK3Oy0r2gRX4ui7tuhiZq2SuTtTCi0/0= From 5f0898a53713ec1b45a5f605129433772b3fe067 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Mon, 13 Nov 2023 18:39:37 +0800 Subject: [PATCH 32/67] update das-lib --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 272f23cf..f605fd70 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module das_register_server go 1.18 require ( - github.com/dotbitHQ/das-lib v1.1.1-0.20231113100809-ae2914dc576c + github.com/dotbitHQ/das-lib v1.1.1-0.20231113103818-0e0ca8ef8bd6 github.com/ethereum/go-ethereum v1.10.26 github.com/fsnotify/fsnotify v1.5.4 github.com/getsentry/sentry-go v0.25.0 // indirect diff --git a/go.sum b/go.sum index ca2f37e2..da205980 100644 --- a/go.sum +++ b/go.sum @@ -145,8 +145,8 @@ github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5O github.com/docker/docker v1.4.2-0.20180625184442-8e610b2b55bf/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/dop251/goja v0.0.0-20211011172007-d99e4b8cbf48/go.mod h1:R9ET47fwRVRPZnOGvHxxhuZcbrMCuiqOz3Rlrh4KSnk= github.com/dop251/goja_nodejs v0.0.0-20210225215109-d91c329300e7/go.mod h1:hn7BA7c8pLvoGndExHudxTDKZ84Pyvv+90pbBjbTz0Y= -github.com/dotbitHQ/das-lib v1.1.1-0.20231113100809-ae2914dc576c h1:+3UOFJwx+ECqQUsQZMVqVXP7zasvHFDxX8hDRHXIS+w= -github.com/dotbitHQ/das-lib v1.1.1-0.20231113100809-ae2914dc576c/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= +github.com/dotbitHQ/das-lib v1.1.1-0.20231113103818-0e0ca8ef8bd6 h1:HhLujs9DKY4IC2w9v14UfxrZZKWGfKm2u0otheFLo2I= +github.com/dotbitHQ/das-lib v1.1.1-0.20231113103818-0e0ca8ef8bd6/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts= github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= github.com/elazarl/goproxy v0.0.0-20221015165544-a0805db90819 h1:RIB4cRk+lBqKK3Oy0r2gRX4ui7tuhiZq2SuTtTCi0/0= From 884c01214e78ca68ee7b019fc326c7ee34de5ba8 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Mon, 13 Nov 2023 23:11:59 +0800 Subject: [PATCH 33/67] renew by did point --- config/config.go | 2 ++ tables/t_das_order_info.go | 1 + 2 files changed, 3 insertions(+) diff --git a/config/config.go b/config/config.go index 58d1476c..2cad444c 100644 --- a/config/config.go +++ b/config/config.go @@ -154,6 +154,8 @@ func GetUnipayAddress(tokenId tables.PayTokenId) string { return Cfg.PayAddressMap["doge"] case tables.TokenIdStripeUSD: return "stripe" + case tables.ToKenIdDidPoint: + return Cfg.PayAddressMap["did_point"] } log.Error("GetUnipayAddress not supported:", tokenId) return "" diff --git a/tables/t_das_order_info.go b/tables/t_das_order_info.go index 124f379f..1020121d 100644 --- a/tables/t_das_order_info.go +++ b/tables/t_das_order_info.go @@ -98,6 +98,7 @@ const ( TokenIdErc20USDT PayTokenId = "eth_erc20_usdt" TokenIdTrc20USDT PayTokenId = "tron_trc20_usdt" TokenIdBep20USDT PayTokenId = "bsc_bep20_usdt" + ToKenIdDidPoint PayTokenId = "did_point" ) func (p PayTokenId) IsTokenIdCkbInternal() bool { From 694a6e745b2f90fd09ad2af62653226d9be291fd Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Tue, 14 Nov 2023 16:58:39 +0800 Subject: [PATCH 34/67] update das-lib --- go.mod | 2 +- go.sum | 4 ++-- http_server/handle/auction_bid.go | 5 ++++- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index f605fd70..9eb5a52e 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module das_register_server go 1.18 require ( - github.com/dotbitHQ/das-lib v1.1.1-0.20231113103818-0e0ca8ef8bd6 + github.com/dotbitHQ/das-lib v1.1.1-0.20231114085018-d9b7193d47b5 github.com/ethereum/go-ethereum v1.10.26 github.com/fsnotify/fsnotify v1.5.4 github.com/getsentry/sentry-go v0.25.0 // indirect diff --git a/go.sum b/go.sum index da205980..34ac45e2 100644 --- a/go.sum +++ b/go.sum @@ -145,8 +145,8 @@ github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5O github.com/docker/docker v1.4.2-0.20180625184442-8e610b2b55bf/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/dop251/goja v0.0.0-20211011172007-d99e4b8cbf48/go.mod h1:R9ET47fwRVRPZnOGvHxxhuZcbrMCuiqOz3Rlrh4KSnk= github.com/dop251/goja_nodejs v0.0.0-20210225215109-d91c329300e7/go.mod h1:hn7BA7c8pLvoGndExHudxTDKZ84Pyvv+90pbBjbTz0Y= -github.com/dotbitHQ/das-lib v1.1.1-0.20231113103818-0e0ca8ef8bd6 h1:HhLujs9DKY4IC2w9v14UfxrZZKWGfKm2u0otheFLo2I= -github.com/dotbitHQ/das-lib v1.1.1-0.20231113103818-0e0ca8ef8bd6/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= +github.com/dotbitHQ/das-lib v1.1.1-0.20231114085018-d9b7193d47b5 h1:jKia7pA+TczMAHKgU4EqGVZcfmSBbZnfUbW5MlfEudY= +github.com/dotbitHQ/das-lib v1.1.1-0.20231114085018-d9b7193d47b5/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts= github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= github.com/elazarl/goproxy v0.0.0-20221015165544-a0805db90819 h1:RIB4cRk+lBqKK3Oy0r2gRX4ui7tuhiZq2SuTtTCi0/0= diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index d5943549..31f9b033 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -79,7 +79,10 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A apiResp.ApiRespErr(http_api.ApiCodeDbError, "search account err") return fmt.Errorf("SearchAccount err: %s", err.Error()) } - + if acc.Status != tables.AccountStatusNormal { + apiResp.ApiRespErr(http_api.ApiCodeAccountStatusNotNormal, "account is not on dutch auction") + return + } timeCell, err := h.dasCore.GetTimeCell() if err != nil { return fmt.Errorf("GetTimeCell err: %s", err.Error()) From b8443d25ff15fcffb22b59de9c834b518af2fe33 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Tue, 14 Nov 2023 17:29:01 +0800 Subject: [PATCH 35/67] update dutchauction endtime --- http_server/handle/auction_info.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/http_server/handle/auction_info.go b/http_server/handle/auction_info.go index 388ad7ad..a80b03c7 100644 --- a/http_server/handle/auction_info.go +++ b/http_server/handle/auction_info.go @@ -214,7 +214,7 @@ func (h *HttpHandle) doGetAccountAuctionInfo(req *ReqAccountAuctionInfo, apiResp resp.AccountId = acc.AccountId resp.Account = req.Account resp.StartsaleTime = acc.ExpiredAt + 90*86400 - resp.EndSaleTime = acc.ExpiredAt + 27*86400 + resp.EndSaleTime = acc.ExpiredAt + 117*86400 resp.AccountPrice = accountPrice resp.BaseAmount = baseAmount resp.ExipiredTime = acc.ExpiredAt From 797997d6472dee66cd1bb912ca49ec742e0b84bf Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Wed, 15 Nov 2023 01:02:02 +0800 Subject: [PATCH 36/67] remove debug --- cmd/main.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index be31bc13..a61c8d37 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -7,6 +7,7 @@ import ( "das_register_server/config" "das_register_server/dao" "das_register_server/http_server" + "das_register_server/prometheus" "das_register_server/timer" "das_register_server/txtool" "das_register_server/unipay" @@ -144,8 +145,8 @@ func runServer(ctx *cli.Context) error { txTool.Run() // prometheus - //prometheus.Init() - //prometheus.Tools.Run() + prometheus.Init() + prometheus.Tools.Run() // block parser bp := block_parser.BlockParser{ From ebff321f849b722708832edbcdcc54ec52ef566d Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Wed, 15 Nov 2023 17:37:47 +0800 Subject: [PATCH 37/67] skip groups --- http_server/handle/reverse_declare.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/http_server/handle/reverse_declare.go b/http_server/handle/reverse_declare.go index f8586495..d218cfae 100644 --- a/http_server/handle/reverse_declare.go +++ b/http_server/handle/reverse_declare.go @@ -236,7 +236,13 @@ func (h *HttpHandle) buildTx(req *reqBuildTx, txParams *txbuilder.BuildTransacti sizeInBlock, _ := txBuilder.Transaction.SizeInBlock() changeCapacity := txBuilder.Transaction.Outputs[len(txBuilder.Transaction.Outputs)-1].Capacity + common.OneCkb - sizeInBlock - 1000 txBuilder.Transaction.Outputs[len(txBuilder.Transaction.Outputs)-1].Capacity = changeCapacity - case common.DasActionEditRecords, common.DasActionEditManager, common.DasActionTransferAccount, common.DasBidExpiredAccountAuction: + case common.DasActionEditRecords, common.DasActionEditManager, common.DasActionTransferAccount: + sizeInBlock, _ := txBuilder.Transaction.SizeInBlock() + changeCapacity := txBuilder.Transaction.Outputs[0].Capacity - sizeInBlock - 1000 + txBuilder.Transaction.Outputs[0].Capacity = changeCapacity + log.Info("buildTx:", req.Action, sizeInBlock, changeCapacity) + case common.DasBidExpiredAccountAuction: + skipGroups = []int{0} sizeInBlock, _ := txBuilder.Transaction.SizeInBlock() changeCapacity := txBuilder.Transaction.Outputs[0].Capacity - sizeInBlock - 1000 txBuilder.Transaction.Outputs[0].Capacity = changeCapacity From a3d9a82c925d9795d5633a1f5e91d4bb53de66c3 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Wed, 15 Nov 2023 17:45:43 +0800 Subject: [PATCH 38/67] update filed --- http_server/handle/account_detail.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/http_server/handle/account_detail.go b/http_server/handle/account_detail.go index 719a41e0..211b6323 100644 --- a/http_server/handle/account_detail.go +++ b/http_server/handle/account_detail.go @@ -45,7 +45,7 @@ type RespAccountDetail struct { CustomScript string `json:"custom_script"` PremiumPercentage decimal.Decimal `json:"premium_percentage"` PremiumBase decimal.Decimal `json:"premium_base"` - ReRegisterTime uint64 `json:"re_registered_time"` + ReRegisterTime uint64 `json:"re_register_time"` } func (h *HttpHandle) RpcAccountDetail(p json.RawMessage, apiResp *api_code.ApiResp) { From c6a77b7c702a335a80ed0ed7efc60441c9918898 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Wed, 15 Nov 2023 17:57:49 +0800 Subject: [PATCH 39/67] remove chaintype verify --- http_server/handle/auction_info.go | 5 ----- 1 file changed, 5 deletions(-) diff --git a/http_server/handle/auction_info.go b/http_server/handle/auction_info.go index a80b03c7..76336894 100644 --- a/http_server/handle/auction_info.go +++ b/http_server/handle/auction_info.go @@ -146,11 +146,6 @@ func (h *HttpHandle) doGetAccountAuctionInfo(req *ReqAccountAuctionInfo, apiResp } fmt.Println(addrHex.DasAlgorithmId, addrHex.DasSubAlgorithmId, addrHex.AddressHex) req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType - if req.chainType != 1 { - apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) - return nil - } - accountId := common.Bytes2Hex(common.GetAccountIdByAccount(req.Account)) acc, err := h.dbDao.GetAccountInfoByAccountId(accountId) if err != nil && err != gorm.ErrRecordNotFound { From efa70e5cbd5f427e5af1bb537b85818c7c74c2cd Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Wed, 15 Nov 2023 18:55:15 +0800 Subject: [PATCH 40/67] update daslib --- go.mod | 2 +- go.sum | 4 ++-- http_server/handle/auction_bid.go | 11 ++++------- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/go.mod b/go.mod index 9eb5a52e..c06ddaca 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module das_register_server go 1.18 require ( - github.com/dotbitHQ/das-lib v1.1.1-0.20231114085018-d9b7193d47b5 + github.com/dotbitHQ/das-lib v1.1.1-0.20231115105106-89a610597894 github.com/ethereum/go-ethereum v1.10.26 github.com/fsnotify/fsnotify v1.5.4 github.com/getsentry/sentry-go v0.25.0 // indirect diff --git a/go.sum b/go.sum index 34ac45e2..e5cc9775 100644 --- a/go.sum +++ b/go.sum @@ -145,8 +145,8 @@ github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5O github.com/docker/docker v1.4.2-0.20180625184442-8e610b2b55bf/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/dop251/goja v0.0.0-20211011172007-d99e4b8cbf48/go.mod h1:R9ET47fwRVRPZnOGvHxxhuZcbrMCuiqOz3Rlrh4KSnk= github.com/dop251/goja_nodejs v0.0.0-20210225215109-d91c329300e7/go.mod h1:hn7BA7c8pLvoGndExHudxTDKZ84Pyvv+90pbBjbTz0Y= -github.com/dotbitHQ/das-lib v1.1.1-0.20231114085018-d9b7193d47b5 h1:jKia7pA+TczMAHKgU4EqGVZcfmSBbZnfUbW5MlfEudY= -github.com/dotbitHQ/das-lib v1.1.1-0.20231114085018-d9b7193d47b5/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= +github.com/dotbitHQ/das-lib v1.1.1-0.20231115105106-89a610597894 h1:jkQXfEZ8y+cHBM4+GIZGwvBRdxhJqFNYbwBvGStItCc= +github.com/dotbitHQ/das-lib v1.1.1-0.20231115105106-89a610597894/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts= github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= github.com/elazarl/goproxy v0.0.0-20221015165544-a0805db90819 h1:RIB4cRk+lBqKK3Oy0r2gRX4ui7tuhiZq2SuTtTCi0/0= diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index 31f9b033..fbbf7bd7 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -235,13 +235,10 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t txParams.Witnesses = append(txParams.Witnesses, actionWitness) //-----acc witness accWitness, accData, err := builder.GenWitness(&witness.AccountCellParam{ - OldIndex: 0, - NewIndex: 0, - Action: common.DasBidExpiredAccountAuction, - LastEditRecordsAt: p.TimeCell.Timestamp(), - LastTransferAccountAt: p.TimeCell.Timestamp(), - LastEditManagerAt: p.TimeCell.Timestamp(), - RegisterAt: uint64(p.TimeCell.Timestamp()), + OldIndex: 0, + NewIndex: 0, + Action: common.DasBidExpiredAccountAuction, + RegisterAt: uint64(p.TimeCell.Timestamp()), }) txParams.Witnesses = append(txParams.Witnesses, accWitness) From 8eb1aa7ead7ea606804beec2decb87250b920c68 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Wed, 15 Nov 2023 19:28:18 +0800 Subject: [PATCH 41/67] dutch auction sign group --- http_server/handle/reverse_declare.go | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/http_server/handle/reverse_declare.go b/http_server/handle/reverse_declare.go index d218cfae..f8586495 100644 --- a/http_server/handle/reverse_declare.go +++ b/http_server/handle/reverse_declare.go @@ -236,13 +236,7 @@ func (h *HttpHandle) buildTx(req *reqBuildTx, txParams *txbuilder.BuildTransacti sizeInBlock, _ := txBuilder.Transaction.SizeInBlock() changeCapacity := txBuilder.Transaction.Outputs[len(txBuilder.Transaction.Outputs)-1].Capacity + common.OneCkb - sizeInBlock - 1000 txBuilder.Transaction.Outputs[len(txBuilder.Transaction.Outputs)-1].Capacity = changeCapacity - case common.DasActionEditRecords, common.DasActionEditManager, common.DasActionTransferAccount: - sizeInBlock, _ := txBuilder.Transaction.SizeInBlock() - changeCapacity := txBuilder.Transaction.Outputs[0].Capacity - sizeInBlock - 1000 - txBuilder.Transaction.Outputs[0].Capacity = changeCapacity - log.Info("buildTx:", req.Action, sizeInBlock, changeCapacity) - case common.DasBidExpiredAccountAuction: - skipGroups = []int{0} + case common.DasActionEditRecords, common.DasActionEditManager, common.DasActionTransferAccount, common.DasBidExpiredAccountAuction: sizeInBlock, _ := txBuilder.Transaction.SizeInBlock() changeCapacity := txBuilder.Transaction.Outputs[0].Capacity - sizeInBlock - 1000 txBuilder.Transaction.Outputs[0].Capacity = changeCapacity From ceccf747c58a31d6e4f8276f7394e343465ca5af Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Wed, 15 Nov 2023 19:58:53 +0800 Subject: [PATCH 42/67] update dutch auction sign group --- dao/dao.go | 15 +++++++-------- http_server/handle/auction_bid.go | 7 +++++-- http_server/handle/common.go | 1 + http_server/handle/reverse_declare.go | 3 +++ 4 files changed, 16 insertions(+), 10 deletions(-) diff --git a/dao/dao.go b/dao/dao.go index c6c782d3..83cccd70 100644 --- a/dao/dao.go +++ b/dao/dao.go @@ -2,7 +2,6 @@ package dao import ( "das_register_server/config" - "das_register_server/tables" "fmt" "github.com/dotbitHQ/das-lib/http_api" "gorm.io/gorm" @@ -28,13 +27,13 @@ func NewGormDB(dbMysql, parserMysql config.DbMysql) (*DbDao, error) { // It will change existing column’s type if its size, precision, nullable changed. // It WON’T delete unused columns to protect your data. if err = db.AutoMigrate( - &tables.TableBlockParserInfo{}, - &tables.TableDasOrderInfo{}, - &tables.TableDasOrderPayInfo{}, - &tables.TableDasOrderTxInfo{}, - &tables.TableRegisterPendingInfo{}, - &tables.TableCoupon{}, - &tables.TableAuctionOrder{}, + //&tables.TableBlockParserInfo{}, + //&tables.TableDasOrderInfo{}, + //&tables.TableDasOrderPayInfo{}, + //&tables.TableDasOrderTxInfo{}, + //&tables.TableRegisterPendingInfo{}, + //&tables.TableCoupon{}, + //&tables.TableAuctionOrder{}, ); err != nil { return nil, err } diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index fbbf7bd7..8a624854 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -18,6 +18,7 @@ import ( "github.com/shopspring/decimal" "gorm.io/gorm" "net/http" + "strings" ) type ReqAuctionBid struct { @@ -140,9 +141,11 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A reqBuild.AuctionInfo = AuctionInfo{ BasicPrice: basicPrice, PremiumPrice: premiumPrice, - BidTime: int64(nowTime), + BidTime: nowTime, + } + if strings.ToLower(req.address) == strings.ToLower(acc.Owner) { + reqBuild.AuctionInfo.IsSelf = true } - // to lock & normal cell lock //转账地址 用于接收荷兰拍竞拍dp的地址 if config.Cfg.Server.TransferWhitelist == "" || config.Cfg.Server.CapacityWhitelist == "" { diff --git a/http_server/handle/common.go b/http_server/handle/common.go index 32b3d4cc..d94b17a3 100644 --- a/http_server/handle/common.go +++ b/http_server/handle/common.go @@ -48,6 +48,7 @@ type AuctionInfo struct { BasicPrice decimal.Decimal `json:"basic_price"` PremiumPrice decimal.Decimal `json:"premium_price"` BidTime int64 `json:"bid_time"` + IsSelf bool `json:"is_self"` } type SignInfoCache struct { diff --git a/http_server/handle/reverse_declare.go b/http_server/handle/reverse_declare.go index f8586495..9fdb9c58 100644 --- a/http_server/handle/reverse_declare.go +++ b/http_server/handle/reverse_declare.go @@ -237,6 +237,9 @@ func (h *HttpHandle) buildTx(req *reqBuildTx, txParams *txbuilder.BuildTransacti changeCapacity := txBuilder.Transaction.Outputs[len(txBuilder.Transaction.Outputs)-1].Capacity + common.OneCkb - sizeInBlock - 1000 txBuilder.Transaction.Outputs[len(txBuilder.Transaction.Outputs)-1].Capacity = changeCapacity case common.DasActionEditRecords, common.DasActionEditManager, common.DasActionTransferAccount, common.DasBidExpiredAccountAuction: + if req.Action == common.DasBidExpiredAccountAuction && !req.AuctionInfo.IsSelf { + skipGroups = []int{1} + } sizeInBlock, _ := txBuilder.Transaction.SizeInBlock() changeCapacity := txBuilder.Transaction.Outputs[0].Capacity - sizeInBlock - 1000 txBuilder.Transaction.Outputs[0].Capacity = changeCapacity From 319157c2da34f9397dcf1ec0c0eec6529b28aa2c Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Wed, 15 Nov 2023 20:27:46 +0800 Subject: [PATCH 43/67] dutch auction sign group --- http_server/handle/reverse_declare.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/http_server/handle/reverse_declare.go b/http_server/handle/reverse_declare.go index 9fdb9c58..4d555206 100644 --- a/http_server/handle/reverse_declare.go +++ b/http_server/handle/reverse_declare.go @@ -237,8 +237,9 @@ func (h *HttpHandle) buildTx(req *reqBuildTx, txParams *txbuilder.BuildTransacti changeCapacity := txBuilder.Transaction.Outputs[len(txBuilder.Transaction.Outputs)-1].Capacity + common.OneCkb - sizeInBlock - 1000 txBuilder.Transaction.Outputs[len(txBuilder.Transaction.Outputs)-1].Capacity = changeCapacity case common.DasActionEditRecords, common.DasActionEditManager, common.DasActionTransferAccount, common.DasBidExpiredAccountAuction: + //其他人拍 if req.Action == common.DasBidExpiredAccountAuction && !req.AuctionInfo.IsSelf { - skipGroups = []int{1} + skipGroups = []int{0} } sizeInBlock, _ := txBuilder.Transaction.SizeInBlock() changeCapacity := txBuilder.Transaction.Outputs[0].Capacity - sizeInBlock - 1000 From 850bff983514347b4d3c0de4d704bad1d0358178 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Wed, 15 Nov 2023 20:50:22 +0800 Subject: [PATCH 44/67] dutchauctoin sign group --- http_server/handle/reverse_declare.go | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/http_server/handle/reverse_declare.go b/http_server/handle/reverse_declare.go index 4d555206..1bb95cf6 100644 --- a/http_server/handle/reverse_declare.go +++ b/http_server/handle/reverse_declare.go @@ -236,9 +236,27 @@ func (h *HttpHandle) buildTx(req *reqBuildTx, txParams *txbuilder.BuildTransacti sizeInBlock, _ := txBuilder.Transaction.SizeInBlock() changeCapacity := txBuilder.Transaction.Outputs[len(txBuilder.Transaction.Outputs)-1].Capacity + common.OneCkb - sizeInBlock - 1000 txBuilder.Transaction.Outputs[len(txBuilder.Transaction.Outputs)-1].Capacity = changeCapacity - case common.DasActionEditRecords, common.DasActionEditManager, common.DasActionTransferAccount, common.DasBidExpiredAccountAuction: + case common.DasActionEditRecords, common.DasActionEditManager, common.DasActionTransferAccount: + sizeInBlock, _ := txBuilder.Transaction.SizeInBlock() + changeCapacity := txBuilder.Transaction.Outputs[0].Capacity - sizeInBlock - 1000 + txBuilder.Transaction.Outputs[0].Capacity = changeCapacity + log.Info("buildTx:", req.Action, sizeInBlock, changeCapacity) + case common.DasBidExpiredAccountAuction: + + //判断是否是自己拍自己(accountcell和dpcell的lock一样) + accTx, err := h.dasCore.Client().GetTransaction(h.ctx, txParams.Inputs[0].PreviousOutput.TxHash) + if err != nil { + return nil, fmt.Errorf("GetTransaction err: %s", err.Error()) + } + accLock := accTx.Transaction.Outputs[txParams.Inputs[0].PreviousOutput.Index].Lock + + dpTx, err := h.dasCore.Client().GetTransaction(h.ctx, txParams.Inputs[1].PreviousOutput.TxHash) + if err != nil { + return nil, fmt.Errorf("GetTransaction err: %s", err.Error()) + } + dpLock := dpTx.Transaction.Outputs[txParams.Inputs[1].PreviousOutput.Index].Lock //其他人拍 - if req.Action == common.DasBidExpiredAccountAuction && !req.AuctionInfo.IsSelf { + if !accLock.Equals(dpLock) { skipGroups = []int{0} } sizeInBlock, _ := txBuilder.Transaction.SizeInBlock() From f4e0450293c85458d71547404d1d2f33d47264ef Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Wed, 15 Nov 2023 20:57:47 +0800 Subject: [PATCH 45/67] update api code --- http_server/handle/auction_bid.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index 8a624854..a293fdda 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -129,8 +129,12 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A SearchOrder: indexer.SearchOrderAsc, }) if err != nil { - apiResp.ApiRespErr(http_api.ApiCodeError500, err.Error()) - return fmt.Errorf("dasCore.GetDpCells err: ", err.Error()) + if err == core.ErrInsufficientFunds { + apiResp.ApiRespErr(http_api.ApiCodeInsufficientBalance, err.Error()) + } else { + apiResp.ApiRespErr(http_api.ApiCodeError500, err.Error()) + return fmt.Errorf("dasCore.GetDpCells err: ", err.Error()) + } } var reqBuild reqBuildTx reqBuild.Action = common.DasBidExpiredAccountAuction From 554a63d30cfa7028a92b20c6302cbbbb819bbf43 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Thu, 16 Nov 2023 10:21:09 +0800 Subject: [PATCH 46/67] dutch auction --- http_server/handle/auction_info.go | 41 +++++++++++++++++------------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/http_server/handle/auction_info.go b/http_server/handle/auction_info.go index 76336894..54ba5287 100644 --- a/http_server/handle/auction_info.go +++ b/http_server/handle/auction_info.go @@ -138,14 +138,17 @@ func (h *HttpHandle) doGetAccountAuctionInfo(req *ReqAccountAuctionInfo, apiResp apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params invalid: account is empty") return } - - addrHex, err := req.FormatChainTypeAddress(config.Cfg.Server.Net, true) - if err != nil { - apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) - return nil + var addrHex *core.DasAddressHex + if req.KeyInfo.Key != "" { + addrHex, err = req.FormatChainTypeAddress(config.Cfg.Server.Net, true) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) + return nil + } + fmt.Println(addrHex.DasAlgorithmId, addrHex.DasSubAlgorithmId, addrHex.AddressHex) + req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType } - fmt.Println(addrHex.DasAlgorithmId, addrHex.DasSubAlgorithmId, addrHex.AddressHex) - req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType + accountId := common.Bytes2Hex(common.GetAccountIdByAccount(req.Account)) acc, err := h.dbDao.GetAccountInfoByAccountId(accountId) if err != nil && err != gorm.ErrRecordNotFound { @@ -177,19 +180,21 @@ func (h *HttpHandle) doGetAccountAuctionInfo(req *ReqAccountAuctionInfo, apiResp } //无人竞拍(有发送中和上链成功的订单) - if len(list) == 0 { - resp.BidStatus = tables.BidStatusNoOne - } else { - resp.BidStatus = tables.BidStatusByOthers //被其他人竞拍 - for _, v := range list { - //被自己竞拍 - if v.AlgorithmId == addrHex.DasAlgorithmId && v.SubAlgorithmId == addrHex.DasSubAlgorithmId && v.Address == addrHex.AddressHex { - resp.BidStatus = tables.BidStatusByMe - resp.Hash, _ = common.String2OutPoint(v.Outpoint) + if addrHex != nil { + if len(list) == 0 { + resp.BidStatus = tables.BidStatusNoOne + } else { + resp.BidStatus = tables.BidStatusByOthers //被其他人竞拍 + for _, v := range list { + //被自己竞拍 + if v.AlgorithmId == addrHex.DasAlgorithmId && v.SubAlgorithmId == addrHex.DasSubAlgorithmId && v.Address == addrHex.AddressHex { + resp.BidStatus = tables.BidStatusByMe + resp.Hash, _ = common.String2OutPoint(v.Outpoint) + } } + apiResp.ApiRespOK(resp) + return } - apiResp.ApiRespOK(resp) - return } //计算长度 From 1701d1df719da216d0235793c5d8f8fdb4167fd6 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Thu, 16 Nov 2023 10:34:41 +0800 Subject: [PATCH 47/67] ApiCodeInsufficientBalance --- http_server/handle/auction_bid.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index a293fdda..e306ebaf 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -128,9 +128,11 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A CurrentBlockNumber: 0, SearchOrder: indexer.SearchOrderAsc, }) + if err != nil { if err == core.ErrInsufficientFunds { apiResp.ApiRespErr(http_api.ApiCodeInsufficientBalance, err.Error()) + return } else { apiResp.ApiRespErr(http_api.ApiCodeError500, err.Error()) return fmt.Errorf("dasCore.GetDpCells err: ", err.Error()) From 900bdb2f23d8959768ec57fc54bd793cd920c87d Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Thu, 16 Nov 2023 15:01:13 +0800 Subject: [PATCH 48/67] test log --- http_server/handle/transaction_send.go | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/http_server/handle/transaction_send.go b/http_server/handle/transaction_send.go index 14ad7c8c..369668b6 100644 --- a/http_server/handle/transaction_send.go +++ b/http_server/handle/transaction_send.go @@ -10,7 +10,6 @@ import ( "github.com/dotbitHQ/das-lib/txbuilder" "github.com/dotbitHQ/das-lib/witness" "github.com/gin-gonic/gin" - "github.com/go-redis/redis" "github.com/scorpiotzh/toolib" "net/http" "strings" @@ -72,17 +71,17 @@ func (h *HttpHandle) doTransactionSend(req *ReqTransactionSend, apiResp *api_cod var sic SignInfoCache // get tx by cache - if txStr, err := h.rc.GetSignTxCache(req.SignKey); err != nil { - if err == redis.Nil { - apiResp.ApiRespErr(api_code.ApiCodeTxExpired, "tx expired err") - } else { - apiResp.ApiRespErr(api_code.ApiCodeCacheError, "cache err") - } - return fmt.Errorf("GetSignTxCache err: %s", err.Error()) - } else if err = json.Unmarshal([]byte(txStr), &sic); err != nil { - apiResp.ApiRespErr(api_code.ApiCodeError500, "json.Unmarshal err") - return fmt.Errorf("json.Unmarshal err: %s", err.Error()) - } + //if txStr, err := h.rc.GetSignTxCache(req.SignKey); err != nil { + // if err == redis.Nil { + // apiResp.ApiRespErr(api_code.ApiCodeTxExpired, "tx expired err") + // } else { + // apiResp.ApiRespErr(api_code.ApiCodeCacheError, "cache err") + // } + // return fmt.Errorf("GetSignTxCache err: %s", err.Error()) + //} else if err = json.Unmarshal([]byte(txStr), &sic); err != nil { + // apiResp.ApiRespErr(api_code.ApiCodeError500, "json.Unmarshal err") + // return fmt.Errorf("json.Unmarshal err: %s", err.Error()) + //} hasWebAuthn := false for _, v := range req.SignList { @@ -105,7 +104,7 @@ func (h *HttpHandle) doTransactionSend(req *ReqTransactionSend, apiResp *api_cod apiResp.ApiRespErr(api_code.ApiCodeParamsInvalid, "SignAddress err") return nil } - + log.Info("req.signaddress: ", req.SignAddress) signAddressHex, err := h.dasCore.Daf().NormalToHex(core.DasAddressNormal{ ChainType: common.ChainTypeWebauthn, AddressNormal: req.SignAddress, From 5d209cdc587c26e934bfd17e2c6781ff126eb3cb Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Thu, 16 Nov 2023 15:02:25 +0800 Subject: [PATCH 49/67] test log --- http_server/handle/transaction_send.go | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/http_server/handle/transaction_send.go b/http_server/handle/transaction_send.go index 369668b6..0ecba65f 100644 --- a/http_server/handle/transaction_send.go +++ b/http_server/handle/transaction_send.go @@ -10,6 +10,7 @@ import ( "github.com/dotbitHQ/das-lib/txbuilder" "github.com/dotbitHQ/das-lib/witness" "github.com/gin-gonic/gin" + "github.com/go-redis/redis" "github.com/scorpiotzh/toolib" "net/http" "strings" @@ -71,17 +72,17 @@ func (h *HttpHandle) doTransactionSend(req *ReqTransactionSend, apiResp *api_cod var sic SignInfoCache // get tx by cache - //if txStr, err := h.rc.GetSignTxCache(req.SignKey); err != nil { - // if err == redis.Nil { - // apiResp.ApiRespErr(api_code.ApiCodeTxExpired, "tx expired err") - // } else { - // apiResp.ApiRespErr(api_code.ApiCodeCacheError, "cache err") - // } - // return fmt.Errorf("GetSignTxCache err: %s", err.Error()) - //} else if err = json.Unmarshal([]byte(txStr), &sic); err != nil { - // apiResp.ApiRespErr(api_code.ApiCodeError500, "json.Unmarshal err") - // return fmt.Errorf("json.Unmarshal err: %s", err.Error()) - //} + if txStr, err := h.rc.GetSignTxCache(req.SignKey); err != nil { + if err == redis.Nil { + apiResp.ApiRespErr(api_code.ApiCodeTxExpired, "tx expired err") + } else { + apiResp.ApiRespErr(api_code.ApiCodeCacheError, "cache err") + } + return fmt.Errorf("GetSignTxCache err: %s", err.Error()) + } else if err = json.Unmarshal([]byte(txStr), &sic); err != nil { + apiResp.ApiRespErr(api_code.ApiCodeError500, "json.Unmarshal err") + return fmt.Errorf("json.Unmarshal err: %s", err.Error()) + } hasWebAuthn := false for _, v := range req.SignList { From 8a8353a5279da80f5caa08edcf6a82786ff6aa8d Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Thu, 16 Nov 2023 16:19:34 +0800 Subject: [PATCH 50/67] transaction send --- dao/dao.go | 15 +++++++------- dao/t_auction_order.go | 8 ++++---- http_server/handle/auction_info.go | 4 ++-- http_server/handle/transaction_send.go | 28 +++++++++----------------- 4 files changed, 23 insertions(+), 32 deletions(-) diff --git a/dao/dao.go b/dao/dao.go index 83cccd70..c6c782d3 100644 --- a/dao/dao.go +++ b/dao/dao.go @@ -2,6 +2,7 @@ package dao import ( "das_register_server/config" + "das_register_server/tables" "fmt" "github.com/dotbitHQ/das-lib/http_api" "gorm.io/gorm" @@ -27,13 +28,13 @@ func NewGormDB(dbMysql, parserMysql config.DbMysql) (*DbDao, error) { // It will change existing column’s type if its size, precision, nullable changed. // It WON’T delete unused columns to protect your data. if err = db.AutoMigrate( - //&tables.TableBlockParserInfo{}, - //&tables.TableDasOrderInfo{}, - //&tables.TableDasOrderPayInfo{}, - //&tables.TableDasOrderTxInfo{}, - //&tables.TableRegisterPendingInfo{}, - //&tables.TableCoupon{}, - //&tables.TableAuctionOrder{}, + &tables.TableBlockParserInfo{}, + &tables.TableDasOrderInfo{}, + &tables.TableDasOrderPayInfo{}, + &tables.TableDasOrderTxInfo{}, + &tables.TableRegisterPendingInfo{}, + &tables.TableCoupon{}, + &tables.TableAuctionOrder{}, ); err != nil { return nil, err } diff --git a/dao/t_auction_order.go b/dao/t_auction_order.go index c925136f..b0bce222 100644 --- a/dao/t_auction_order.go +++ b/dao/t_auction_order.go @@ -6,8 +6,8 @@ import ( "github.com/dotbitHQ/das-lib/common" ) -func (d *DbDao) GetPendingAuctionOrder(algorithmId common.DasAlgorithmId, subAlgithmId common.DasSubAlgorithmId, addr string) (list []tables.TableAuctionOrder, err error) { - sql := fmt.Sprintf(`SELECT o.id,o.account,o.outpoint,o.basic_price,o.premium_price,o.order_id,p.status FROM %s o LEFT JOIN %s p ON o.outpoint=p.outpoint WHERE o.algorithm_id = %d and o.sub_algorithm_id = %d and o.address = "%s" and p.status = 0 order by bid_time desc`, tables.TableNameAuctionOrder, tables.TableNameRegisterPendingInfo, algorithmId, subAlgithmId, addr) +func (d *DbDao) GetPendingAuctionOrder(chainType common.ChainType, addr string) (list []tables.TableAuctionOrder, err error) { + sql := fmt.Sprintf(`SELECT o.id,o.account,o.outpoint,o.basic_price,o.premium_price,o.order_id,p.status FROM %s o LEFT JOIN %s p ON o.outpoint=p.outpoint WHERE o.chain_type = %d and o.address = "%s" and p.status = 0 order by bid_time desc`, tables.TableNameAuctionOrder, tables.TableNameRegisterPendingInfo, chainType, addr) err = d.db.Raw(sql).Find(&list).Error return list, nil } @@ -20,8 +20,8 @@ WHERE o.account= "%s" and p.status != %d`, tables.TableNameAuctionOrder, tables. return list, nil } -func (d *DbDao) GetAuctionOrderStatus(algorithmId common.DasAlgorithmId, subAlgithmId common.DasSubAlgorithmId, addr, hash string) (list tables.TableAuctionOrder, err error) { - sql := fmt.Sprintf(`SELECT o.id,o.account,o.outpoint,o.basic_price,o.premium_price,o.order_id,p.status FROM %s o LEFT JOIN %s p ON o.outpoint=p.outpoint WHERE p.outpoint="%s" and o.algorithm_id = %d and o.sub_algorithm_id = %d and o.address = "%s" order by bid_time desc`, tables.TableNameAuctionOrder, tables.TableNameRegisterPendingInfo, fmt.Sprintf("%s-0", hash), algorithmId, subAlgithmId, addr) +func (d *DbDao) GetAuctionOrderStatus(chainType common.ChainType, addr, hash string) (list tables.TableAuctionOrder, err error) { + sql := fmt.Sprintf(`SELECT o.id,o.account,o.outpoint,o.basic_price,o.premium_price,o.order_id,p.status FROM %s o LEFT JOIN %s p ON o.outpoint=p.outpoint WHERE p.outpoint="%s" and o.chain_type = %d and o.address = "%s" order by bid_time desc`, tables.TableNameAuctionOrder, tables.TableNameRegisterPendingInfo, fmt.Sprintf("%s-0", hash), chainType, addr) fmt.Println(sql) err = d.db.Raw(sql).First(&list).Error return list, nil diff --git a/http_server/handle/auction_info.go b/http_server/handle/auction_info.go index 54ba5287..ba886e83 100644 --- a/http_server/handle/auction_info.go +++ b/http_server/handle/auction_info.go @@ -269,7 +269,7 @@ func (h *HttpHandle) doGetAuctionOrderStatus(req *ReqGetAuctionOrder, apiResp *h return nil } req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType - order, err := h.dbDao.GetAuctionOrderStatus(addrHex.DasAlgorithmId, addrHex.DasSubAlgorithmId, addrHex.AddressHex, req.Hash) + order, err := h.dbDao.GetAuctionOrderStatus(addrHex.ChainType, addrHex.AddressHex, req.Hash) if err != nil { apiResp.ApiRespErr(http_api.ApiCodeDbError, "db error") return @@ -330,7 +330,7 @@ func (h *HttpHandle) doGetPendingAuctionOrder(req *ReqGetGetPendingAuctionOrder, apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) return nil } - list, err := h.dbDao.GetPendingAuctionOrder(addrHex.DasAlgorithmId, addrHex.DasSubAlgorithmId, addrHex.AddressHex) + list, err := h.dbDao.GetPendingAuctionOrder(addrHex.ChainType, addrHex.AddressHex) if err != nil { apiResp.ApiRespErr(http_api.ApiCodeDbError, "db error") return diff --git a/http_server/handle/transaction_send.go b/http_server/handle/transaction_send.go index 0ecba65f..b774ecfe 100644 --- a/http_server/handle/transaction_send.go +++ b/http_server/handle/transaction_send.go @@ -189,26 +189,16 @@ func (h *HttpHandle) doTransactionSend(req *ReqTransactionSend, apiResp *api_cod } if sic.Action == common.DasBidExpiredAccountAuction { - addressHex, err := h.dasCore.Daf().NormalToHex(core.DasAddressNormal{ - ChainType: sic.ChainType, - AddressNormal: sic.Address, - Is712: true, - }) - if err != nil { - apiResp.ApiRespErr(api_code.ApiCodeParamsInvalid, "address NormalToHex err") - return fmt.Errorf("NormalToHex err: %s", err.Error()) - } + auctionOrder := tables.TableAuctionOrder{ - Account: sic.Account, - AccountId: common.Bytes2Hex(common.GetAccountIdByAccount(sic.Account)), - Address: sic.Address, - BasicPrice: sic.AuctionInfo.BasicPrice, - PremiumPrice: sic.AuctionInfo.PremiumPrice, - BidTime: sic.AuctionInfo.BidTime, - AlgorithmId: addressHex.DasAlgorithmId, - SubAlgorithmId: addressHex.DasSubAlgorithmId, - ChainType: sic.ChainType, - Outpoint: pending.Outpoint, + Account: sic.Account, + AccountId: common.Bytes2Hex(common.GetAccountIdByAccount(sic.Account)), + Address: sic.Address, + BasicPrice: sic.AuctionInfo.BasicPrice, + PremiumPrice: sic.AuctionInfo.PremiumPrice, + BidTime: sic.AuctionInfo.BidTime, + ChainType: sic.ChainType, + Outpoint: pending.Outpoint, } if err = h.dbDao.CreateAuctionOrder(auctionOrder); err != nil { log.Error("CreateAuctionOrder err: ", err.Error(), toolib.JsonString(auctionOrder)) From e013cfa73c0627e1108c7210e5bf4526502a6252 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Thu, 16 Nov 2023 16:51:12 +0800 Subject: [PATCH 51/67] search auction order --- http_server/handle/account_detail.go | 11 ++--------- http_server/handle/auction_info.go | 15 ++++----------- http_server/handle/transaction_send.go | 1 + tables/t_account_info.go | 4 ---- tables/t_auction_order.go | 6 +++--- 5 files changed, 10 insertions(+), 27 deletions(-) diff --git a/http_server/handle/account_detail.go b/http_server/handle/account_detail.go index 211b6323..5f878aed 100644 --- a/http_server/handle/account_detail.go +++ b/http_server/handle/account_detail.go @@ -150,38 +150,31 @@ func (h *HttpHandle) getAccountPrice(accLen uint8, args, account string, isRenew func (h *HttpHandle) checkDutchAuction(expiredAt uint64) (status tables.SearchStatus, reRegisterTime uint64, err error) { nowTime := uint64(time.Now().Unix()) - //27 days : watting for bid - //h.dasCore.ConfigCellDataBuilderByTypeArgsList() builderConfigCell, err := h.dasCore.ConfigCellDataBuilderByTypeArgs(common.ConfigCellTypeArgsAccount) if err != nil { err = fmt.Errorf("ConfigCellDataBuilderByTypeArgs err: %s", err.Error()) return } - gracePeriodTime, err := builderConfigCell.ExpirationGracePeriod() if err != nil { err = fmt.Errorf("ExpirationGracePeriod err: %s", err.Error()) return } - auctionPeriodTime, err := builderConfigCell.ExpirationAuctionPeriod() if err != nil { err = fmt.Errorf("ExpirationAuctionPeriod err: %s", err.Error()) return } - deliverPeriodTime, err := builderConfigCell.ExpirationDeliverPeriod() if err != nil { err = fmt.Errorf("ExpirationDeliverPeriod err: %s", err.Error()) return } - // nowTime-117*24*3600 < expiredAt && expiredAt < nowTime-90*24*3600 + if nowTime-uint64(gracePeriodTime)-uint64(auctionPeriodTime) < expiredAt && expiredAt < nowTime-uint64(gracePeriodTime) { status = tables.SearchStatusOnDutchAuction - return } - //3 days : can`t bid or register or renew, watting for recycle by keeper - //nowTime-120*24*3600 < expiredAt && expiredAt < nowTime-117*24*3600 + if nowTime-uint64(gracePeriodTime)-uint64(auctionPeriodTime)-uint64(deliverPeriodTime) < expiredAt && expiredAt < nowTime-uint64(gracePeriodTime)-uint64(auctionPeriodTime) { status = tables.SearchStatusAuctionRecycling reRegisterTime = expiredAt + uint64(gracePeriodTime+auctionPeriodTime+deliverPeriodTime) diff --git a/http_server/handle/auction_info.go b/http_server/handle/auction_info.go index ba886e83..5df8698d 100644 --- a/http_server/handle/auction_info.go +++ b/http_server/handle/auction_info.go @@ -145,7 +145,6 @@ func (h *HttpHandle) doGetAccountAuctionInfo(req *ReqAccountAuctionInfo, apiResp apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) return nil } - fmt.Println(addrHex.DasAlgorithmId, addrHex.DasSubAlgorithmId, addrHex.AddressHex) req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType } @@ -167,27 +166,22 @@ func (h *HttpHandle) doGetAccountAuctionInfo(req *ReqAccountAuctionInfo, apiResp apiResp.ApiRespErr(http_api.ApiCodeAuctionAccountNotFound, "This account has not been in dutch auction") return nil } - //if acc.ExpiredAt > nowTime-90*24*3600 || acc.ExpiredAt < nowTime-117*24*3600 { - // apiResp.ApiRespErr(http_api.ApiCodeAuctionAccountNotFound, "This account has not been in dutch auction") - // return - //} - //查询账号的竞拍状态 + //search bid status of a account list, err := h.dbDao.GetAuctionOrderByAccount(req.Account) if err != nil { apiResp.ApiRespErr(http_api.ApiCodeDbError, "db error") return } - //无人竞拍(有发送中和上链成功的订单) if addrHex != nil { if len(list) == 0 { resp.BidStatus = tables.BidStatusNoOne } else { - resp.BidStatus = tables.BidStatusByOthers //被其他人竞拍 + resp.BidStatus = tables.BidStatusByOthers for _, v := range list { - //被自己竞拍 - if v.AlgorithmId == addrHex.DasAlgorithmId && v.SubAlgorithmId == addrHex.DasSubAlgorithmId && v.Address == addrHex.AddressHex { + + if v.ChainType == addrHex.ChainType && v.Address == addrHex.AddressHex { resp.BidStatus = tables.BidStatusByMe resp.Hash, _ = common.String2OutPoint(v.Outpoint) } @@ -197,7 +191,6 @@ func (h *HttpHandle) doGetAccountAuctionInfo(req *ReqAccountAuctionInfo, apiResp } } - //计算长度 _, accLen, err := common.GetDotBitAccountLength(req.Account) if err != nil { return diff --git a/http_server/handle/transaction_send.go b/http_server/handle/transaction_send.go index b774ecfe..72ea89b9 100644 --- a/http_server/handle/transaction_send.go +++ b/http_server/handle/transaction_send.go @@ -200,6 +200,7 @@ func (h *HttpHandle) doTransactionSend(req *ReqTransactionSend, apiResp *api_cod ChainType: sic.ChainType, Outpoint: pending.Outpoint, } + auctionOrder.CreateOrderId() if err = h.dbDao.CreateAuctionOrder(auctionOrder); err != nil { log.Error("CreateAuctionOrder err: ", err.Error(), toolib.JsonString(auctionOrder)) } diff --git a/tables/t_account_info.go b/tables/t_account_info.go index 6a832d1e..d7f216db 100644 --- a/tables/t_account_info.go +++ b/tables/t_account_info.go @@ -65,10 +65,6 @@ const ( SearchStatusOnCross SearchStatus = 15 SearchStatusOnDutchAuction SearchStatus = 17 SearchStatusAuctionRecycling SearchStatus = 18 - - // 90天之后 三天以内 弹第一个框 dutchAuctionRecycling 18 // 荷兰拍结束的 后三天 :返回可以开始注册的时间 - // 90天之内 第二个弹框取消 - //90天之后 27天以内 荷兰拍阶段 弹第三个框 dutchAuction 17 // ) func (t *TableAccountInfo) IsExpired() bool { diff --git a/tables/t_auction_order.go b/tables/t_auction_order.go index 38065807..8490beed 100644 --- a/tables/t_auction_order.go +++ b/tables/t_auction_order.go @@ -35,9 +35,9 @@ func (t *TableAuctionOrder) TableName() string { type BidStatus int const ( - BidStatusNoOne BidStatus = 0 //账号没有人竞 - BidStatusByOthers BidStatus = 1 //账号被其他人竞拍 - BidStatusByMe BidStatus = 2 //账号被我竞拍 + BidStatusNoOne BidStatus = 0 //No one is bidding + BidStatusByOthers BidStatus = 1 //Being auctioned by others + BidStatusByMe BidStatus = 2 //Being auctioned by me ) func (t *TableAuctionOrder) CreateOrderId() { From a06ef9f8cba3c37a12cb41ac4039757d912ea04a Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Mon, 20 Nov 2023 11:59:35 +0800 Subject: [PATCH 52/67] dutch auction : default record, price --- dao/t_auction_order.go | 5 +- go.mod | 2 +- go.sum | 4 +- http_server/api_code/api_code.go | 41 +++++++----- http_server/handle/account_detail.go | 26 +++----- http_server/handle/auction_bid.go | 98 ++++++++++++++++++++++------ http_server/handle/auction_info.go | 56 +++++++++------- http_server/handle/common.go | 1 - http_server/router.go | 10 +-- 9 files changed, 149 insertions(+), 94 deletions(-) diff --git a/dao/t_auction_order.go b/dao/t_auction_order.go index b0bce222..96b01f60 100644 --- a/dao/t_auction_order.go +++ b/dao/t_auction_order.go @@ -12,17 +12,16 @@ func (d *DbDao) GetPendingAuctionOrder(chainType common.ChainType, addr string) return list, nil } -func (d *DbDao) GetAuctionOrderByAccount(account string) (list []tables.TableAuctionOrder, err error) { +func (d *DbDao) GetAuctionOrderByAccount(account string, createTime int64) (list []tables.TableAuctionOrder, err error) { sql := fmt.Sprintf(`SELECT o.account,o.outpoint,o.address,o.algorithm_id,o.sub_algorithm_id,p.status FROM %s o LEFT JOIN %s p ON o.outpoint=p.outpoint -WHERE o.account= "%s" and p.status != %d`, tables.TableNameAuctionOrder, tables.TableNameRegisterPendingInfo, account, tables.StatusRejected) +WHERE o.account= "%s" and p.status != %d and o.created_at > %d `, tables.TableNameAuctionOrder, tables.TableNameRegisterPendingInfo, account, tables.StatusRejected, createTime) err = d.db.Raw(sql).Find(&list).Error return list, nil } func (d *DbDao) GetAuctionOrderStatus(chainType common.ChainType, addr, hash string) (list tables.TableAuctionOrder, err error) { sql := fmt.Sprintf(`SELECT o.id,o.account,o.outpoint,o.basic_price,o.premium_price,o.order_id,p.status FROM %s o LEFT JOIN %s p ON o.outpoint=p.outpoint WHERE p.outpoint="%s" and o.chain_type = %d and o.address = "%s" order by bid_time desc`, tables.TableNameAuctionOrder, tables.TableNameRegisterPendingInfo, fmt.Sprintf("%s-0", hash), chainType, addr) - fmt.Println(sql) err = d.db.Raw(sql).First(&list).Error return list, nil } diff --git a/go.mod b/go.mod index c06ddaca..4f2dde4c 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module das_register_server go 1.18 require ( - github.com/dotbitHQ/das-lib v1.1.1-0.20231115105106-89a610597894 + github.com/dotbitHQ/das-lib v1.1.1-0.20231120035727-38e3e617a6ca github.com/ethereum/go-ethereum v1.10.26 github.com/fsnotify/fsnotify v1.5.4 github.com/getsentry/sentry-go v0.25.0 // indirect diff --git a/go.sum b/go.sum index e5cc9775..ab592b36 100644 --- a/go.sum +++ b/go.sum @@ -145,8 +145,8 @@ github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5O github.com/docker/docker v1.4.2-0.20180625184442-8e610b2b55bf/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/dop251/goja v0.0.0-20211011172007-d99e4b8cbf48/go.mod h1:R9ET47fwRVRPZnOGvHxxhuZcbrMCuiqOz3Rlrh4KSnk= github.com/dop251/goja_nodejs v0.0.0-20210225215109-d91c329300e7/go.mod h1:hn7BA7c8pLvoGndExHudxTDKZ84Pyvv+90pbBjbTz0Y= -github.com/dotbitHQ/das-lib v1.1.1-0.20231115105106-89a610597894 h1:jkQXfEZ8y+cHBM4+GIZGwvBRdxhJqFNYbwBvGStItCc= -github.com/dotbitHQ/das-lib v1.1.1-0.20231115105106-89a610597894/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= +github.com/dotbitHQ/das-lib v1.1.1-0.20231120035727-38e3e617a6ca h1:iy0IIKbTC35LIDz4jpd/xUCfGanlMC0AgUUog6zx0ew= +github.com/dotbitHQ/das-lib v1.1.1-0.20231120035727-38e3e617a6ca/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts= github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= github.com/elazarl/goproxy v0.0.0-20221015165544-a0805db90819 h1:RIB4cRk+lBqKK3Oy0r2gRX4ui7tuhiZq2SuTtTCi0/0= diff --git a/http_server/api_code/api_code.go b/http_server/api_code/api_code.go index 9744a4e2..cf8d6b32 100644 --- a/http_server/api_code/api_code.go +++ b/http_server/api_code/api_code.go @@ -53,24 +53,28 @@ const ( ) const ( - MethodTokenList = "das_tokenList" - MethodConfigInfo = "das_dasConfig" - MethodAccountList = "das_accountList" - MethodAccountMine = "das_myAccounts" - MethodAccountDetail = "das_accountDetail" - MethodAccountRecords = "das_accountParsingRecords" - MethodReverseLatest = "das_reverseLatest" - MethodReverseList = "das_reverseList" - MethodTransactionStatus = "das_transactionStatus" - MethodBalanceInfo = "das_balanceInfo" - MethodTransactionList = "das_transactionList" - MethodRewardsMine = "das_myRewards" - MethodWithdrawList = "das_withdrawList" - MethodAccountSearch = "das_accountSearch" - MethodRegisteringList = "das_registeringAccounts" - MethodOrderDetail = "das_orderDetail" - MethodAddressDeposit = "das_addressDeposit" - MethodCharacterSetList = "das_characterSetList" + MethodTokenList = "das_tokenList" + MethodConfigInfo = "das_dasConfig" + MethodAccountList = "das_accountList" + MethodAccountMine = "das_myAccounts" + MethodAccountDetail = "das_accountDetail" + MethodAccountRecords = "das_accountParsingRecords" + MethodReverseLatest = "das_reverseLatest" + MethodReverseList = "das_reverseList" + MethodTransactionStatus = "das_transactionStatus" + MethodBalanceInfo = "das_balanceInfo" + MethodTransactionList = "das_transactionList" + MethodRewardsMine = "das_myRewards" + MethodWithdrawList = "das_withdrawList" + MethodAccountSearch = "das_accountSearch" + MethodRegisteringList = "das_registeringAccounts" + MethodOrderDetail = "das_orderDetail" + MethodAddressDeposit = "das_addressDeposit" + MethodCharacterSetList = "das_characterSetList" + MethodAuctionInfo = "das_auctionInfo" + MethodAuctionPrice = "das_auctionPrice" + MethodAuctionOrderStatus = "das_auctionOrderStatus" + MethodAuctionPendingOrder = "das_auctionPendingOrder" MethodReverseDeclare = "das_reverseDeclare" MethodReverseRedeclare = "das_reverseRedeclare" @@ -90,6 +94,7 @@ const ( MethodEditScript = "das_editScript" MethodOrderCheckCoupon = "das_checkCoupon" MethodCkbRpc = "das_ckbRpc" + MethodAuctionBid = "das_auctionBid" ) type ApiResp struct { diff --git a/http_server/handle/account_detail.go b/http_server/handle/account_detail.go index 5f878aed..63aef5bb 100644 --- a/http_server/handle/account_detail.go +++ b/http_server/handle/account_detail.go @@ -3,8 +3,6 @@ package handle import ( "bytes" "das_register_server/config" - "time" - //"das_register_server/http_server/api_code" "das_register_server/tables" "encoding/binary" @@ -149,28 +147,20 @@ func (h *HttpHandle) getAccountPrice(accLen uint8, args, account string, isRenew } func (h *HttpHandle) checkDutchAuction(expiredAt uint64) (status tables.SearchStatus, reRegisterTime uint64, err error) { - nowTime := uint64(time.Now().Unix()) - builderConfigCell, err := h.dasCore.ConfigCellDataBuilderByTypeArgs(common.ConfigCellTypeArgsAccount) - if err != nil { - err = fmt.Errorf("ConfigCellDataBuilderByTypeArgs err: %s", err.Error()) - return - } - gracePeriodTime, err := builderConfigCell.ExpirationGracePeriod() + timeCell, err := h.dasCore.GetTimeCell() if err != nil { - err = fmt.Errorf("ExpirationGracePeriod err: %s", err.Error()) + err = fmt.Errorf("GetTimeCell err: %s", err.Error()) return } - auctionPeriodTime, err := builderConfigCell.ExpirationAuctionPeriod() + nowTime := uint64(timeCell.Timestamp()) + auctionConfig, err := h.GetAuctionConfig(h.dasCore) if err != nil { - err = fmt.Errorf("ExpirationAuctionPeriod err: %s", err.Error()) + err = fmt.Errorf("GetAuctionConfig err: %s", err.Error()) return } - deliverPeriodTime, err := builderConfigCell.ExpirationDeliverPeriod() - if err != nil { - err = fmt.Errorf("ExpirationDeliverPeriod err: %s", err.Error()) - return - } - + gracePeriodTime := auctionConfig.GracePeriodTime + auctionPeriodTime := auctionConfig.AuctionPeriodTime + deliverPeriodTime := auctionConfig.DeliverPeriodTime if nowTime-uint64(gracePeriodTime)-uint64(auctionPeriodTime) < expiredAt && expiredAt < nowTime-uint64(gracePeriodTime) { status = tables.SearchStatusOnDutchAuction } diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index e306ebaf..7398926f 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -18,13 +18,13 @@ import ( "github.com/shopspring/decimal" "gorm.io/gorm" "net/http" - "strings" ) type ReqAuctionBid struct { - Account string `json:"account"` + Account string `json:"account" binding:"required"` address string chainType common.ChainType + CoinType string `json:"coin_type"` //default record core.ChainTypeAddress } @@ -32,7 +32,6 @@ type RespAuctionBid struct { SignInfo } -//查询价格 func (h *HttpHandle) AccountAuctionBid(ctx *gin.Context) { var ( funcName = "AccountAuctionBid" @@ -51,7 +50,7 @@ func (h *HttpHandle) AccountAuctionBid(ctx *gin.Context) { log.Info("ApiReq:", funcName, clientIp, toolib.JsonString(req)) if err = h.doAccountAuctionBid(&req, &apiResp); err != nil { - log.Error("GetAccountAuctionInfo err:", err.Error(), funcName, clientIp) + log.Error("doAccountAuctionBid err:", err.Error(), funcName, clientIp) } ctx.JSON(http.StatusOK, apiResp) } @@ -70,10 +69,6 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A } req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType - if req.Account == "" { - apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params invalid: account is empty") - return - } accountId := common.Bytes2Hex(common.GetAccountIdByAccount(req.Account)) acc, err := h.dbDao.GetAccountInfoByAccountId(accountId) if err != nil && err != gorm.ErrRecordNotFound { @@ -116,7 +111,13 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A basicPrice := baseAmount.Add(accountPrice) log.Info("expiredat: ", int64(acc.ExpiredAt), "nowTime: ", nowTime) - premiumPrice := decimal.NewFromInt(common.Premium(int64(acc.ExpiredAt), nowTime)) + + auctionConfig, err := h.GetAuctionConfig(h.dasCore) + if err != nil { + err = fmt.Errorf("GetAuctionConfig err: %s", err.Error()) + return + } + premiumPrice := decimal.NewFromFloat(common.Premium(int64(acc.ExpiredAt+uint64(auctionConfig.GracePeriodTime)), nowTime)) amountDP := basicPrice.Add(premiumPrice).Mul(decimal.NewFromInt(common.UsdRateBase)).BigInt().Uint64() log.Info("baseAmount: ", baseAmount, " accountPrice: ", accountPrice, " basicPrice: ", basicPrice, " premiumPrice: ", premiumPrice, " amountDP: ", amountDP) @@ -149,11 +150,8 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A PremiumPrice: premiumPrice, BidTime: nowTime, } - if strings.ToLower(req.address) == strings.ToLower(acc.Owner) { - reqBuild.AuctionInfo.IsSelf = true - } + // to lock & normal cell lock - //转账地址 用于接收荷兰拍竞拍dp的地址 if config.Cfg.Server.TransferWhitelist == "" || config.Cfg.Server.CapacityWhitelist == "" { return fmt.Errorf("TransferWhitelist or CapacityWhitelist is empty") } @@ -162,12 +160,36 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A apiResp.ApiRespErr(http_api.ApiCodeError500, err.Error()) return fmt.Errorf("address.Parse err: %s", err.Error()) } - //回收地址(接收dpcell 释放的capacity) + normalCellLock, err := address.Parse(config.Cfg.Server.CapacityWhitelist) if err != nil { apiResp.ApiRespErr(http_api.ApiCodeError500, err.Error()) return fmt.Errorf("address.Parse err: %s", err.Error()) } + + //default record + var initialRecords []witness.Record + coinType := req.CoinType + if coinType == "" { + switch req.chainType { + case common.ChainTypeEth: + coinType = string(common.CoinTypeEth) + case common.ChainTypeTron: + coinType = string(common.CoinTypeTrx) + } + } + if addr, err := common.FormatAddressByCoinType(coinType, req.address); err == nil { + initialRecords = append(initialRecords, witness.Record{ + Key: coinType, + Type: "address", + Label: "", + Value: addr, + TTL: 300, + }) + } else { + log.Error("buildOrderPreRegisterTx FormatAddressByCoinType err: ", err.Error()) + } + var p auctionBidParams p.Account = &acc p.AmountDP = amountDP @@ -175,6 +197,7 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A p.ToLock = toLock.Script p.NormalCellLock = normalCellLock.Script p.TimeCell = timeCell + p.DefaultRecord = initialRecords txParams, err := h.buildAuctionBidTx(&reqBuild, &p) if err != nil { apiResp.ApiRespErr(http_api.ApiCodeError500, "build tx err: "+err.Error()) @@ -193,6 +216,7 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A type auctionBidParams struct { Account *tables.TableAccountInfo + DefaultRecord []witness.Record AmountDP uint64 FromLock *types.Script ToLock *types.Script @@ -214,12 +238,9 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t if err != nil { return nil, fmt.Errorf("GetQuoteCell err: %s", err.Error()) } - //timeCell, err := h.dasCore.GetTimeCell() - //if err != nil { - // return nil, fmt.Errorf("GetTimeCell err: %s", err.Error()) - //} accOutPoint := common.String2OutPointStruct(p.Account.Outpoint) + // witness account cell accTx, err := h.dasCore.Client().GetTransaction(h.ctx, accOutPoint.TxHash) if err != nil { @@ -248,6 +269,7 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t NewIndex: 0, Action: common.DasBidExpiredAccountAuction, RegisterAt: uint64(p.TimeCell.Timestamp()), + Records: p.DefaultRecord, }) txParams.Witnesses = append(txParams.Witnesses, accWitness) @@ -270,6 +292,7 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t Lock: contractDas.ToScript(lockArgs), Type: accTx.Transaction.Outputs[builder.Index].Type, }) + newExpiredAt := p.TimeCell.Timestamp() + common.OneYearSec byteExpiredAt := molecule.Go64ToBytes(newExpiredAt) accData = append(accData, accTx.Transaction.OutputsData[builder.Index][32:]...) @@ -277,8 +300,7 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t accData2 := accData[common.ExpireTimeEndIndex:] newAccData := append(accData1, byteExpiredAt...) newAccData = append(newAccData, accData2...) - fmt.Println("newAccData: ", newAccData) - txParams.OutputsData = append(txParams.OutputsData, newAccData) // change expired_at + txParams.OutputsData = append(txParams.OutputsData, newAccData) //dp liveCell, totalDP, totalCapacity, err := h.dasCore.GetDpCells(&core.ParamGetDpCells{ @@ -335,6 +357,7 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t PreviousOutput: v.OutPoint, }) } + //返还给旧账户的 capacity txParams.Outputs = append(txParams.Outputs, &types.CellOutput{ Capacity: accCellCapacity, @@ -344,7 +367,7 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t txParams.OutputsData = append(txParams.OutputsData, []byte{}) log.Info("normalCellCapacity:", normalCellCapacity, common.Bytes2Hex(p.NormalCellLock.Args)) - //找零 + //change if change := totalNormal - normalCellCapacity - accCellCapacity; change > 0 { txParams.Outputs = append(txParams.Outputs, &types.CellOutput{ Capacity: change, @@ -397,3 +420,36 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t ) return &txParams, nil } + +type AuctionConfig struct { + GracePeriodTime, AuctionPeriodTime, DeliverPeriodTime uint32 +} + +func (h *HttpHandle) GetAuctionConfig(dasCore *core.DasCore) (res *AuctionConfig, err error) { + builderConfigCell, err := dasCore.ConfigCellDataBuilderByTypeArgs(common.ConfigCellTypeArgsAccount) + if err != nil { + err = fmt.Errorf("ConfigCellDataBuilderByTypeArgs err: %s", err.Error()) + return + } + gracePeriodTime, err := builderConfigCell.ExpirationGracePeriod() + if err != nil { + err = fmt.Errorf("ExpirationGracePeriod err: %s", err.Error()) + return + } + auctionPeriodTime, err := builderConfigCell.ExpirationAuctionPeriod() + if err != nil { + err = fmt.Errorf("ExpirationAuctionPeriod err: %s", err.Error()) + return + } + deliverPeriodTime, err := builderConfigCell.ExpirationDeliverPeriod() + if err != nil { + err = fmt.Errorf("ExpirationDeliverPeriod err: %s", err.Error()) + return + } + res = &AuctionConfig{ + GracePeriodTime: gracePeriodTime, + AuctionPeriodTime: auctionPeriodTime, + DeliverPeriodTime: deliverPeriodTime, + } + return +} diff --git a/http_server/handle/auction_info.go b/http_server/handle/auction_info.go index 5df8698d..574e19c4 100644 --- a/http_server/handle/auction_info.go +++ b/http_server/handle/auction_info.go @@ -16,14 +16,14 @@ import ( ) type ReqAuctionPrice struct { - Account string `json:"account"` + Account string `json:"account" binding:"required"` } type RespAuctionPrice struct { //BasicPrice decimal.Decimal `json:"basic_price"` AccountPrice decimal.Decimal `json:"account_price"` BaseAmount decimal.Decimal `json:"base_amount"` - PremiumPrice int64 `json:"premium_price"` + PremiumPrice decimal.Decimal `json:"premium_price"` } //查询价格 @@ -45,16 +45,12 @@ func (h *HttpHandle) GetAccountAuctionPrice(ctx *gin.Context) { log.Info("ApiReq:", funcName, clientIp, toolib.JsonString(req)) if err = h.doGetAccountAuctionPrice(&req, &apiResp); err != nil { - log.Error("GetAccountAuctionInfo err:", err.Error(), funcName, clientIp) + log.Error("doGetAccountAuctionPrice err:", err.Error(), funcName, clientIp) } ctx.JSON(http.StatusOK, apiResp) } func (h *HttpHandle) doGetAccountAuctionPrice(req *ReqAuctionPrice, apiResp *http_api.ApiResp) (err error) { var resp RespAuctionPrice - if req.Account == "" { - apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params invalid: account is empty") - return - } accountId := common.Bytes2Hex(common.GetAccountIdByAccount(req.Account)) acc, err := h.dbDao.GetAccountInfoByAccountId(accountId) if err != nil && err != gorm.ErrRecordNotFound { @@ -62,13 +58,18 @@ func (h *HttpHandle) doGetAccountAuctionPrice(req *ReqAuctionPrice, apiResp *htt return fmt.Errorf("SearchAccount err: %s", err.Error()) } nowTime := uint64(time.Now().Unix()) + //exp + 90 + 27 +3 //now > exp+117 exp< now - 117 //now< exp+90 exp>now -90 - if acc.ExpiredAt > nowTime-90*24*3600 || acc.ExpiredAt < nowTime-117*24*3600 { + if status, _, err := h.checkDutchAuction(acc.ExpiredAt); err != nil { + apiResp.ApiRespErr(http_api.ApiCodeError500, "checkDutchAuction err") + return fmt.Errorf("checkDutchAuction err: %s", err.Error()) + } else if status != tables.SearchStatusOnDutchAuction { apiResp.ApiRespErr(http_api.ApiCodeAuctionAccountNotFound, "This account has not been in dutch auction") - return + return nil } + //计算长度 _, accLen, err := common.GetDotBitAccountLength(req.Account) if err != nil { @@ -83,15 +84,20 @@ func (h *HttpHandle) doGetAccountAuctionPrice(req *ReqAuctionPrice, apiResp *htt apiResp.ApiRespErr(http_api.ApiCodeError500, "get account price err") return fmt.Errorf("getAccountPrice err: %s", err.Error()) } + auctionConfig, err := h.GetAuctionConfig(h.dasCore) + if err != nil { + err = fmt.Errorf("GetAuctionConfig err: %s", err.Error()) + return + } resp.BaseAmount = baseAmount resp.AccountPrice = accountPrice - resp.PremiumPrice = common.Premium(int64(acc.ExpiredAt), int64(nowTime)) + resp.PremiumPrice = decimal.NewFromFloat(common.Premium(int64(acc.ExpiredAt+uint64(auctionConfig.GracePeriodTime)), int64(nowTime))) apiResp.ApiRespOK(resp) return } type ReqAccountAuctionInfo struct { - Account string `json:"account"` + Account string `json:"account" binding:"required"` core.ChainTypeAddress address string chainType common.ChainType @@ -134,10 +140,6 @@ func (h *HttpHandle) GetAccountAuctionInfo(ctx *gin.Context) { func (h *HttpHandle) doGetAccountAuctionInfo(req *ReqAccountAuctionInfo, apiResp *http_api.ApiResp) (err error) { var resp RespAccountAuctionInfo - if req.Account == "" { - apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params invalid: account is empty") - return - } var addrHex *core.DasAddressHex if req.KeyInfo.Key != "" { addrHex, err = req.FormatChainTypeAddress(config.Cfg.Server.Net, true) @@ -168,7 +170,8 @@ func (h *HttpHandle) doGetAccountAuctionInfo(req *ReqAccountAuctionInfo, apiResp } //search bid status of a account - list, err := h.dbDao.GetAuctionOrderByAccount(req.Account) + createTime := time.Now().Unix() - 365*86400 + list, err := h.dbDao.GetAuctionOrderByAccount(req.Account, createTime) if err != nil { apiResp.ApiRespErr(http_api.ApiCodeDbError, "db error") return @@ -180,7 +183,6 @@ func (h *HttpHandle) doGetAccountAuctionInfo(req *ReqAccountAuctionInfo, apiResp } else { resp.BidStatus = tables.BidStatusByOthers for _, v := range list { - if v.ChainType == addrHex.ChainType && v.Address == addrHex.AddressHex { resp.BidStatus = tables.BidStatusByMe resp.Hash, _ = common.String2OutPoint(v.Outpoint) @@ -204,10 +206,18 @@ func (h *HttpHandle) doGetAccountAuctionInfo(req *ReqAccountAuctionInfo, apiResp apiResp.ApiRespErr(http_api.ApiCodeError500, "get account price err") return fmt.Errorf("getAccountPrice err: %s", err.Error()) } + auctionConfig, err := h.GetAuctionConfig(h.dasCore) + if err != nil { + err = fmt.Errorf("GetAuctionConfig err: %s", err.Error()) + return + } + gracePeriodTime := auctionConfig.GracePeriodTime + auctionPeriodTime := auctionConfig.AuctionPeriodTime + resp.AccountId = acc.AccountId resp.Account = req.Account - resp.StartsaleTime = acc.ExpiredAt + 90*86400 - resp.EndSaleTime = acc.ExpiredAt + 117*86400 + resp.StartsaleTime = acc.ExpiredAt + uint64(gracePeriodTime)*86400 + resp.EndSaleTime = acc.ExpiredAt + uint64(gracePeriodTime+auctionPeriodTime)*86400 resp.AccountPrice = accountPrice resp.BaseAmount = baseAmount resp.ExipiredTime = acc.ExpiredAt @@ -231,7 +241,7 @@ type RepReqGetAuctionOrder struct { func (h *HttpHandle) GetAuctionOrderStatus(ctx *gin.Context) { var ( - funcName = "GetAuctionOrder" + funcName = "GetAuctionOrderStatus" clientIp = GetClientIp(ctx) req ReqGetAuctionOrder apiResp http_api.ApiResp @@ -248,7 +258,7 @@ func (h *HttpHandle) GetAuctionOrderStatus(ctx *gin.Context) { log.Info("ApiReq:", funcName, clientIp, toolib.JsonString(req)) if err = h.doGetAuctionOrderStatus(&req, &apiResp); err != nil { - log.Error("GetBidStatus err:", err.Error(), funcName, clientIp) + log.Error("doGetAuctionOrderStatus err:", err.Error(), funcName, clientIp) } ctx.JSON(http.StatusOK, apiResp) } @@ -319,10 +329,6 @@ func (h *HttpHandle) doGetPendingAuctionOrder(req *ReqGetGetPendingAuctionOrder, return nil } req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType - if req.chainType != 1 { - apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) - return nil - } list, err := h.dbDao.GetPendingAuctionOrder(addrHex.ChainType, addrHex.AddressHex) if err != nil { apiResp.ApiRespErr(http_api.ApiCodeDbError, "db error") diff --git a/http_server/handle/common.go b/http_server/handle/common.go index d94b17a3..32b3d4cc 100644 --- a/http_server/handle/common.go +++ b/http_server/handle/common.go @@ -48,7 +48,6 @@ type AuctionInfo struct { BasicPrice decimal.Decimal `json:"basic_price"` PremiumPrice decimal.Decimal `json:"premium_price"` BidTime int64 `json:"bid_time"` - IsSelf bool `json:"is_self"` } type SignInfoCache struct { diff --git a/http_server/router.go b/http_server/router.go index 06aaa5ed..bf3286e9 100644 --- a/http_server/router.go +++ b/http_server/router.go @@ -59,10 +59,10 @@ func (h *HttpServer) initRouter() { v1.POST("/account/order/detail", api_code.DoMonitorLog(api_code.MethodOrderDetail), h.h.OrderDetail) v1.POST("/address/deposit", api_code.DoMonitorLog(api_code.MethodAddressDeposit), cacheHandleLong, h.h.AddressDeposit) v1.POST("/character/set/list", api_code.DoMonitorLog(api_code.MethodCharacterSetList), cacheHandleLong, h.h.CharacterSetList) - v1.POST("/account/auction/info", api_code.DoMonitorLog(api_code.MethodCharacterSetList), cacheHandleLong, h.h.GetAccountAuctionInfo) - v1.POST("/account/auction/price", api_code.DoMonitorLog(api_code.MethodCharacterSetList), cacheHandleLong, h.h.GetAccountAuctionPrice) - v1.POST("/account/auction/order-status", api_code.DoMonitorLog(api_code.MethodCharacterSetList), cacheHandleLong, h.h.GetAuctionOrderStatus) - v1.POST("/account/auction/pending-order", api_code.DoMonitorLog(api_code.MethodCharacterSetList), cacheHandleLong, h.h.GetPendingAuctionOrder) + v1.POST("/account/auction/info", api_code.DoMonitorLog(api_code.MethodAuctionInfo), cacheHandleLong, h.h.GetAccountAuctionInfo) + v1.POST("/account/auction/price", api_code.DoMonitorLog(api_code.MethodAuctionPrice), cacheHandleLong, h.h.GetAccountAuctionPrice) + v1.POST("/account/auction/order-status", api_code.DoMonitorLog(api_code.MethodAuctionOrderStatus), cacheHandleLong, h.h.GetAuctionOrderStatus) + v1.POST("/account/auction/pending-order", api_code.DoMonitorLog(api_code.MethodAuctionPendingOrder), cacheHandleLong, h.h.GetPendingAuctionOrder) // operate //v1.POST("/reverse/declare", api_code.DoMonitorLog(api_code.MethodReverseDeclare), h.h.ReverseDeclare) @@ -82,7 +82,7 @@ func (h *HttpServer) initRouter() { v1.POST("/account/order/pay/hash", api_code.DoMonitorLog(api_code.MethodOrderPayHash), h.h.OrderPayHash) v1.POST("/account/coupon/check", api_code.DoMonitorLog(api_code.MethodOrderCheckCoupon), cacheHandleShort, h.h.CheckCoupon) //v1.POST("/account/edit/script", api_code.DoMonitorLog(api_code.MethodEditScript), h.h.EditScript) - v1.POST("/account/auction/bid", api_code.DoMonitorLog(api_code.MethodCharacterSetList), cacheHandleLong, h.h.AccountAuctionBid) + v1.POST("/account/auction/bid", api_code.DoMonitorLog(api_code.MethodAuctionBid), h.h.AccountAuctionBid) // node rpc v1.POST("/node/ckb/rpc", api_code.DoMonitorLog(api_code.MethodCkbRpc), h.h.CkbRpc) From 5ed05e8d661803757b1d25c821d79bf3f1fa3e06 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Mon, 20 Nov 2023 13:45:59 +0800 Subject: [PATCH 53/67] auction time --- http_server/handle/auction_info.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/http_server/handle/auction_info.go b/http_server/handle/auction_info.go index 574e19c4..f8491c89 100644 --- a/http_server/handle/auction_info.go +++ b/http_server/handle/auction_info.go @@ -216,8 +216,8 @@ func (h *HttpHandle) doGetAccountAuctionInfo(req *ReqAccountAuctionInfo, apiResp resp.AccountId = acc.AccountId resp.Account = req.Account - resp.StartsaleTime = acc.ExpiredAt + uint64(gracePeriodTime)*86400 - resp.EndSaleTime = acc.ExpiredAt + uint64(gracePeriodTime+auctionPeriodTime)*86400 + resp.StartsaleTime = acc.ExpiredAt + uint64(gracePeriodTime) + resp.EndSaleTime = acc.ExpiredAt + uint64(gracePeriodTime+auctionPeriodTime) resp.AccountPrice = accountPrice resp.BaseAmount = baseAmount resp.ExipiredTime = acc.ExpiredAt From 14d6c7806d9b8b63f4af713ae10155ddc39b0fae Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Mon, 20 Nov 2023 16:20:14 +0800 Subject: [PATCH 54/67] update das-lib --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 4f2dde4c..77dc4b05 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module das_register_server go 1.18 require ( - github.com/dotbitHQ/das-lib v1.1.1-0.20231120035727-38e3e617a6ca + github.com/dotbitHQ/das-lib v1.1.1-0.20231120081120-5108962d4429 github.com/ethereum/go-ethereum v1.10.26 github.com/fsnotify/fsnotify v1.5.4 github.com/getsentry/sentry-go v0.25.0 // indirect diff --git a/go.sum b/go.sum index ab592b36..352e94df 100644 --- a/go.sum +++ b/go.sum @@ -145,8 +145,8 @@ github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5O github.com/docker/docker v1.4.2-0.20180625184442-8e610b2b55bf/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/dop251/goja v0.0.0-20211011172007-d99e4b8cbf48/go.mod h1:R9ET47fwRVRPZnOGvHxxhuZcbrMCuiqOz3Rlrh4KSnk= github.com/dop251/goja_nodejs v0.0.0-20210225215109-d91c329300e7/go.mod h1:hn7BA7c8pLvoGndExHudxTDKZ84Pyvv+90pbBjbTz0Y= -github.com/dotbitHQ/das-lib v1.1.1-0.20231120035727-38e3e617a6ca h1:iy0IIKbTC35LIDz4jpd/xUCfGanlMC0AgUUog6zx0ew= -github.com/dotbitHQ/das-lib v1.1.1-0.20231120035727-38e3e617a6ca/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= +github.com/dotbitHQ/das-lib v1.1.1-0.20231120081120-5108962d4429 h1:t9UfILQlbQ5UnBaGaQJwjPYI86zizkoPpoylSp1CvPs= +github.com/dotbitHQ/das-lib v1.1.1-0.20231120081120-5108962d4429/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts= github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= github.com/elazarl/goproxy v0.0.0-20221015165544-a0805db90819 h1:RIB4cRk+lBqKK3Oy0r2gRX4ui7tuhiZq2SuTtTCi0/0= From e5428e7ba5c35ebd10a230ef0ad1df50862594f2 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Mon, 20 Nov 2023 16:31:43 +0800 Subject: [PATCH 55/67] update daslib --- go.mod | 2 +- go.sum | 4 ++-- http_server/handle/auction_bid.go | 6 +++--- http_server/handle/reverse_declare.go | 7 ++----- 4 files changed, 8 insertions(+), 11 deletions(-) diff --git a/go.mod b/go.mod index 77dc4b05..3fabbea1 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module das_register_server go 1.18 require ( - github.com/dotbitHQ/das-lib v1.1.1-0.20231120081120-5108962d4429 + github.com/dotbitHQ/das-lib v1.1.1-0.20231120082857-bb42b035f35a github.com/ethereum/go-ethereum v1.10.26 github.com/fsnotify/fsnotify v1.5.4 github.com/getsentry/sentry-go v0.25.0 // indirect diff --git a/go.sum b/go.sum index 352e94df..b9c3a502 100644 --- a/go.sum +++ b/go.sum @@ -145,8 +145,8 @@ github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5O github.com/docker/docker v1.4.2-0.20180625184442-8e610b2b55bf/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/dop251/goja v0.0.0-20211011172007-d99e4b8cbf48/go.mod h1:R9ET47fwRVRPZnOGvHxxhuZcbrMCuiqOz3Rlrh4KSnk= github.com/dop251/goja_nodejs v0.0.0-20210225215109-d91c329300e7/go.mod h1:hn7BA7c8pLvoGndExHudxTDKZ84Pyvv+90pbBjbTz0Y= -github.com/dotbitHQ/das-lib v1.1.1-0.20231120081120-5108962d4429 h1:t9UfILQlbQ5UnBaGaQJwjPYI86zizkoPpoylSp1CvPs= -github.com/dotbitHQ/das-lib v1.1.1-0.20231120081120-5108962d4429/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= +github.com/dotbitHQ/das-lib v1.1.1-0.20231120082857-bb42b035f35a h1:A002DpBz13Q1FgsXymLi27QbRyw28cL/huL+XAVNAOY= +github.com/dotbitHQ/das-lib v1.1.1-0.20231120082857-bb42b035f35a/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts= github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= github.com/elazarl/goproxy v0.0.0-20221015165544-a0805db90819 h1:RIB4cRk+lBqKK3Oy0r2gRX4ui7tuhiZq2SuTtTCi0/0= diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index 7398926f..c20db531 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -140,7 +140,7 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A } } var reqBuild reqBuildTx - reqBuild.Action = common.DasBidExpiredAccountAuction + reqBuild.Action = common.DasActionBidExpiredAccountAuction reqBuild.Account = req.Account reqBuild.ChainType = req.chainType reqBuild.Address = req.address @@ -258,7 +258,7 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t accCellCapacity := accTx.Transaction.Outputs[builder.Index].Capacity oldAccOwnerArgs := accTx.Transaction.Outputs[builder.Index].Lock.Args - actionWitness, err := witness.GenActionDataWitness(common.DasBidExpiredAccountAuction, nil) + actionWitness, err := witness.GenActionDataWitness(common.DasActionBidExpiredAccountAuction, nil) if err != nil { return nil, fmt.Errorf("GenActionDataWitness err: %s", err.Error()) } @@ -267,7 +267,7 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t accWitness, accData, err := builder.GenWitness(&witness.AccountCellParam{ OldIndex: 0, NewIndex: 0, - Action: common.DasBidExpiredAccountAuction, + Action: common.DasActionBidExpiredAccountAuction, RegisterAt: uint64(p.TimeCell.Timestamp()), Records: p.DefaultRecord, }) diff --git a/http_server/handle/reverse_declare.go b/http_server/handle/reverse_declare.go index 1bb95cf6..0181f955 100644 --- a/http_server/handle/reverse_declare.go +++ b/http_server/handle/reverse_declare.go @@ -241,9 +241,7 @@ func (h *HttpHandle) buildTx(req *reqBuildTx, txParams *txbuilder.BuildTransacti changeCapacity := txBuilder.Transaction.Outputs[0].Capacity - sizeInBlock - 1000 txBuilder.Transaction.Outputs[0].Capacity = changeCapacity log.Info("buildTx:", req.Action, sizeInBlock, changeCapacity) - case common.DasBidExpiredAccountAuction: - - //判断是否是自己拍自己(accountcell和dpcell的lock一样) + case common.DasActionBidExpiredAccountAuction: accTx, err := h.dasCore.Client().GetTransaction(h.ctx, txParams.Inputs[0].PreviousOutput.TxHash) if err != nil { return nil, fmt.Errorf("GetTransaction err: %s", err.Error()) @@ -255,7 +253,6 @@ func (h *HttpHandle) buildTx(req *reqBuildTx, txParams *txbuilder.BuildTransacti return nil, fmt.Errorf("GetTransaction err: %s", err.Error()) } dpLock := dpTx.Transaction.Outputs[txParams.Inputs[1].PreviousOutput.Index].Lock - //其他人拍 if !accLock.Equals(dpLock) { skipGroups = []int{0} } @@ -292,7 +289,7 @@ func (h *HttpHandle) buildTx(req *reqBuildTx, txParams *txbuilder.BuildTransacti sic.BuilderTx = txBuilder.DasTxBuilderTransaction //dutch auction - if req.Action == common.DasBidExpiredAccountAuction { + if req.Action == common.DasActionBidExpiredAccountAuction { sic.AuctionInfo = req.AuctionInfo } From ef765064e32d3607a1d738cc72eec4888dfffe53 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Mon, 20 Nov 2023 16:36:14 +0800 Subject: [PATCH 56/67] update auction action --- tables/t_auction_order.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tables/t_auction_order.go b/tables/t_auction_order.go index 8490beed..1c47c879 100644 --- a/tables/t_auction_order.go +++ b/tables/t_auction_order.go @@ -41,5 +41,5 @@ const ( ) func (t *TableAuctionOrder) CreateOrderId() { - t.OrderId = CreateOrderId(1, t.AccountId, common.DasBidExpiredAccountAuction, t.ChainType, t.Address, t.BidTime) + t.OrderId = CreateOrderId(1, t.AccountId, common.DasActionBidExpiredAccountAuction, t.ChainType, t.Address, t.BidTime) } From 10e63f21fd3839f3b843090f861ebb84eb248e45 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Mon, 20 Nov 2023 16:37:17 +0800 Subject: [PATCH 57/67] auction action --- http_server/handle/transaction_send.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/http_server/handle/transaction_send.go b/http_server/handle/transaction_send.go index 72ea89b9..0c20d262 100644 --- a/http_server/handle/transaction_send.go +++ b/http_server/handle/transaction_send.go @@ -188,7 +188,7 @@ func (h *HttpHandle) doTransactionSend(req *ReqTransactionSend, apiResp *api_cod log.Error("CreatePending err: ", err.Error(), toolib.JsonString(pending)) } - if sic.Action == common.DasBidExpiredAccountAuction { + if sic.Action == common.DasActionBidExpiredAccountAuction { auctionOrder := tables.TableAuctionOrder{ Account: sic.Account, From baf7212fe511155744ee76a627e9ad74e48ed791 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Mon, 20 Nov 2023 18:16:09 +0800 Subject: [PATCH 58/67] parse dutch auction tx --- block_parser/action_dutch_auction.go | 23 +++++++++++++++++++++++ block_parser/block_parser_handle.go | 1 + 2 files changed, 24 insertions(+) create mode 100644 block_parser/action_dutch_auction.go diff --git a/block_parser/action_dutch_auction.go b/block_parser/action_dutch_auction.go new file mode 100644 index 00000000..2b56ceaa --- /dev/null +++ b/block_parser/action_dutch_auction.go @@ -0,0 +1,23 @@ +package block_parser + +import ( + "fmt" + "github.com/dotbitHQ/das-lib/common" +) + +func (b *BlockParser) ActionBidExpiredAccountAuction(req FuncTransactionHandleReq) (resp FuncTransactionHandleResp) { + if isCV, err := isCurrentVersionTx(req.Tx, common.DasContractNameAccountCellType); err != nil { + resp.Err = fmt.Errorf("isCurrentVersion err: %s", err.Error()) + return + } else if !isCV { + return + } + + outpoint := common.OutPoint2String(req.TxHash, 0) + if err := b.DbDao.UpdatePendingStatusToConfirm(req.Action, outpoint, req.BlockNumber, req.BlockTimestamp); err != nil { + resp.Err = fmt.Errorf("UpdatePendingStatusToConfirm err: %s", err.Error()) + return + } + + return +} diff --git a/block_parser/block_parser_handle.go b/block_parser/block_parser_handle.go index f8391e52..de598d20 100644 --- a/block_parser/block_parser_handle.go +++ b/block_parser/block_parser_handle.go @@ -26,6 +26,7 @@ func (b *BlockParser) registerTransactionHandle() { b.mapTransactionHandle[common.DasActionEditRecords] = b.ActionEditRecords b.mapTransactionHandle[common.DasActionEditManager] = b.ActionEditManager b.mapTransactionHandle[common.DasActionTransferAccount] = b.ActionTransferAccount + b.mapTransactionHandle[common.DasActionBidExpiredAccountAuction] = b.ActionBidExpiredAccountAuction // //b.mapTransactionHandle[common.DasActionDeclareReverseRecord] = b.ActionDeclareReverseRecord //b.mapTransactionHandle[common.DasActionRedeclareReverseRecord] = b.ActionRedeclareReverseRecord From 832769b8447a38f53458f854a23c8f9d6990eacf Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Mon, 20 Nov 2023 20:58:15 +0800 Subject: [PATCH 59/67] update webauthn default records --- go.mod | 2 +- go.sum | 4 ++-- http_server/handle/auction_bid.go | 15 ++++----------- 3 files changed, 7 insertions(+), 14 deletions(-) diff --git a/go.mod b/go.mod index 3fabbea1..8a1aa2d3 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module das_register_server go 1.18 require ( - github.com/dotbitHQ/das-lib v1.1.1-0.20231120082857-bb42b035f35a + github.com/dotbitHQ/das-lib v1.1.1-0.20231120125536-8d1e4fbda8f4 github.com/ethereum/go-ethereum v1.10.26 github.com/fsnotify/fsnotify v1.5.4 github.com/getsentry/sentry-go v0.25.0 // indirect diff --git a/go.sum b/go.sum index b9c3a502..ae8073c4 100644 --- a/go.sum +++ b/go.sum @@ -145,8 +145,8 @@ github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5O github.com/docker/docker v1.4.2-0.20180625184442-8e610b2b55bf/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/dop251/goja v0.0.0-20211011172007-d99e4b8cbf48/go.mod h1:R9ET47fwRVRPZnOGvHxxhuZcbrMCuiqOz3Rlrh4KSnk= github.com/dop251/goja_nodejs v0.0.0-20210225215109-d91c329300e7/go.mod h1:hn7BA7c8pLvoGndExHudxTDKZ84Pyvv+90pbBjbTz0Y= -github.com/dotbitHQ/das-lib v1.1.1-0.20231120082857-bb42b035f35a h1:A002DpBz13Q1FgsXymLi27QbRyw28cL/huL+XAVNAOY= -github.com/dotbitHQ/das-lib v1.1.1-0.20231120082857-bb42b035f35a/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= +github.com/dotbitHQ/das-lib v1.1.1-0.20231120125536-8d1e4fbda8f4 h1:8jxgmCThIDkThnwPzWd2XGAMQvCR6SGbk0OygzA5ATo= +github.com/dotbitHQ/das-lib v1.1.1-0.20231120125536-8d1e4fbda8f4/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts= github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= github.com/elazarl/goproxy v0.0.0-20221015165544-a0805db90819 h1:RIB4cRk+lBqKK3Oy0r2gRX4ui7tuhiZq2SuTtTCi0/0= diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index c20db531..99ac5a8a 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -169,18 +169,11 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A //default record var initialRecords []witness.Record - coinType := req.CoinType - if coinType == "" { - switch req.chainType { - case common.ChainTypeEth: - coinType = string(common.CoinTypeEth) - case common.ChainTypeTron: - coinType = string(common.CoinTypeTrx) - } - } - if addr, err := common.FormatAddressByCoinType(coinType, req.address); err == nil { + coinType := req.KeyInfo.CoinType + + if addr, err := common.FormatAddressByCoinType(string(coinType), req.address); err == nil { initialRecords = append(initialRecords, witness.Record{ - Key: coinType, + Key: string(coinType), Type: "address", Label: "", Value: addr, From 5cd0551d509a8e19664af9062eed202651bc6ee1 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Mon, 20 Nov 2023 22:35:42 +0800 Subject: [PATCH 60/67] dutch auction order info --- dao/t_auction_order.go | 2 +- http_server/router.go | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/dao/t_auction_order.go b/dao/t_auction_order.go index 96b01f60..5b0c56d1 100644 --- a/dao/t_auction_order.go +++ b/dao/t_auction_order.go @@ -13,7 +13,7 @@ func (d *DbDao) GetPendingAuctionOrder(chainType common.ChainType, addr string) } func (d *DbDao) GetAuctionOrderByAccount(account string, createTime int64) (list []tables.TableAuctionOrder, err error) { - sql := fmt.Sprintf(`SELECT o.account,o.outpoint,o.address,o.algorithm_id,o.sub_algorithm_id,p.status FROM %s o + sql := fmt.Sprintf(`SELECT o.account,o.outpoint,o.address,o.chain_type,p.status FROM %s o LEFT JOIN %s p ON o.outpoint=p.outpoint WHERE o.account= "%s" and p.status != %d and o.created_at > %d `, tables.TableNameAuctionOrder, tables.TableNameRegisterPendingInfo, account, tables.StatusRejected, createTime) err = d.db.Raw(sql).Find(&list).Error diff --git a/http_server/router.go b/http_server/router.go index bf3286e9..8e968e4e 100644 --- a/http_server/router.go +++ b/http_server/router.go @@ -59,9 +59,9 @@ func (h *HttpServer) initRouter() { v1.POST("/account/order/detail", api_code.DoMonitorLog(api_code.MethodOrderDetail), h.h.OrderDetail) v1.POST("/address/deposit", api_code.DoMonitorLog(api_code.MethodAddressDeposit), cacheHandleLong, h.h.AddressDeposit) v1.POST("/character/set/list", api_code.DoMonitorLog(api_code.MethodCharacterSetList), cacheHandleLong, h.h.CharacterSetList) - v1.POST("/account/auction/info", api_code.DoMonitorLog(api_code.MethodAuctionInfo), cacheHandleLong, h.h.GetAccountAuctionInfo) - v1.POST("/account/auction/price", api_code.DoMonitorLog(api_code.MethodAuctionPrice), cacheHandleLong, h.h.GetAccountAuctionPrice) - v1.POST("/account/auction/order-status", api_code.DoMonitorLog(api_code.MethodAuctionOrderStatus), cacheHandleLong, h.h.GetAuctionOrderStatus) + v1.POST("/account/auction/info", api_code.DoMonitorLog(api_code.MethodAuctionInfo), h.h.GetAccountAuctionInfo) + v1.POST("/account/auction/price", api_code.DoMonitorLog(api_code.MethodAuctionPrice), h.h.GetAccountAuctionPrice) + v1.POST("/account/auction/order-status", api_code.DoMonitorLog(api_code.MethodAuctionOrderStatus), h.h.GetAuctionOrderStatus) v1.POST("/account/auction/pending-order", api_code.DoMonitorLog(api_code.MethodAuctionPendingOrder), cacheHandleLong, h.h.GetPendingAuctionOrder) // operate From 2a9ccaf7dfb97e28f1891746890de18544cda860 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Tue, 21 Nov 2023 12:23:40 +0800 Subject: [PATCH 61/67] update price with timecell --- http_server/handle/account_detail.go | 19 ++++++++++--------- http_server/handle/auction_bid.go | 3 ++- http_server/handle/auction_info.go | 18 +++++++++++++++--- 3 files changed, 27 insertions(+), 13 deletions(-) diff --git a/http_server/handle/account_detail.go b/http_server/handle/account_detail.go index 63aef5bb..2415215a 100644 --- a/http_server/handle/account_detail.go +++ b/http_server/handle/account_detail.go @@ -146,13 +146,7 @@ func (h *HttpHandle) getAccountPrice(accLen uint8, args, account string, isRenew return } -func (h *HttpHandle) checkDutchAuction(expiredAt uint64) (status tables.SearchStatus, reRegisterTime uint64, err error) { - timeCell, err := h.dasCore.GetTimeCell() - if err != nil { - err = fmt.Errorf("GetTimeCell err: %s", err.Error()) - return - } - nowTime := uint64(timeCell.Timestamp()) +func (h *HttpHandle) checkDutchAuction(expiredAt, nowTime uint64) (status tables.SearchStatus, reRegisterTime uint64, err error) { auctionConfig, err := h.GetAuctionConfig(h.dasCore) if err != nil { err = fmt.Errorf("GetAuctionConfig err: %s", err.Error()) @@ -175,6 +169,7 @@ func (h *HttpHandle) checkDutchAuction(expiredAt uint64) (status tables.SearchSt func (h *HttpHandle) doAccountDetail(req *ReqAccountDetail, apiResp *api_code.ApiResp) error { var resp RespAccountDetail + var err error resp.Account = req.Account resp.Status = tables.SearchStatusRegisterAble resp.PremiumPercentage = config.Cfg.Stripe.PremiumPercentage @@ -195,7 +190,14 @@ func (h *HttpHandle) doAccountDetail(req *ReqAccountDetail, apiResp *api_code.Ap //expired_at+90 < now => expired_at < now - 90 //now > expired_at+90+27 //now < expired_at+90+30 - if status, reRegisterTime, err := h.checkDutchAuction(acc.ExpiredAt); err != nil { + timeCell, err := h.dasCore.GetTimeCell() + if err != nil { + err = fmt.Errorf("GetTimeCell err: %s", err.Error()) + apiResp.ApiRespErr(api_code.ApiCodeError500, "GetTimeCell err") + return err + } + nowTime := uint64(timeCell.Timestamp()) + if status, reRegisterTime, err := h.checkDutchAuction(acc.ExpiredAt, nowTime); err != nil { apiResp.ApiRespErr(api_code.ApiCodeError500, "checkDutchAuction err") return fmt.Errorf("checkDutchAuction err: %s", err.Error()) } else if status != 0 { @@ -223,7 +225,6 @@ func (h *HttpHandle) doAccountDetail(req *ReqAccountDetail, apiResp *api_code.Ap } // price - var err error resp.BaseAmount, resp.AccountPrice, err = h.getAccountPrice(uint8(accBuilder.AccountChars.Len()), "", req.Account, true) if err != nil { apiResp.ApiRespErr(api_code.ApiCodeError500, "get account price err") diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index 99ac5a8a..73399e91 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -81,13 +81,14 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A } timeCell, err := h.dasCore.GetTimeCell() if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeError500, "GetTimeCell err") return fmt.Errorf("GetTimeCell err: %s", err.Error()) } nowTime := timeCell.Timestamp() //exp + 90 + 27 +3 //now > exp+117 exp< now - 117 //now< exp+90 exp>now -90 - if status, _, err := h.checkDutchAuction(acc.ExpiredAt); err != nil { + if status, _, err := h.checkDutchAuction(acc.ExpiredAt, uint64(nowTime)); err != nil { apiResp.ApiRespErr(http_api.ApiCodeError500, "checkDutchAuction err") return fmt.Errorf("checkDutchAuction err: %s", err.Error()) } else if status != tables.SearchStatusOnDutchAuction { diff --git a/http_server/handle/auction_info.go b/http_server/handle/auction_info.go index f8491c89..7047455a 100644 --- a/http_server/handle/auction_info.go +++ b/http_server/handle/auction_info.go @@ -57,12 +57,18 @@ func (h *HttpHandle) doGetAccountAuctionPrice(req *ReqAuctionPrice, apiResp *htt apiResp.ApiRespErr(http_api.ApiCodeDbError, "search account err") return fmt.Errorf("SearchAccount err: %s", err.Error()) } - nowTime := uint64(time.Now().Unix()) + //nowTime := uint64(time.Now().Unix()) + timeCell, err := h.dasCore.GetTimeCell() + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeError500, "GetTimeCell err") + return fmt.Errorf("GetTimeCell err: %s", err.Error()) + } + nowTime := timeCell.Timestamp() //exp + 90 + 27 +3 //now > exp+117 exp< now - 117 //now< exp+90 exp>now -90 - if status, _, err := h.checkDutchAuction(acc.ExpiredAt); err != nil { + if status, _, err := h.checkDutchAuction(acc.ExpiredAt, uint64(nowTime)); err != nil { apiResp.ApiRespErr(http_api.ApiCodeError500, "checkDutchAuction err") return fmt.Errorf("checkDutchAuction err: %s", err.Error()) } else if status != tables.SearchStatusOnDutchAuction { @@ -161,7 +167,13 @@ func (h *HttpHandle) doGetAccountAuctionInfo(req *ReqAccountAuctionInfo, apiResp return } - if status, _, err := h.checkDutchAuction(acc.ExpiredAt); err != nil { + timeCell, err := h.dasCore.GetTimeCell() + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeError500, "GetTimeCell err") + return fmt.Errorf("GetTimeCell err: %s", err.Error()) + } + nowTime := timeCell.Timestamp() + if status, _, err := h.checkDutchAuction(acc.ExpiredAt, uint64(nowTime)); err != nil { apiResp.ApiRespErr(http_api.ApiCodeError500, "checkDutchAuction err") return fmt.Errorf("checkDutchAuction err: %s", err.Error()) } else if status != tables.SearchStatusOnDutchAuction { From a96ed00f590b1f37ebbed804ce93bd3fa7ed3dcf Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Tue, 21 Nov 2023 20:21:36 +0800 Subject: [PATCH 62/67] Code of dutch auction structure adjustment --- http_server/handle/auction_bid.go | 24 +-- http_server/handle/auction_info.go | 210 -------------------- http_server/handle/auction_order_status.go | 78 ++++++++ http_server/handle/auction_pending_order.go | 68 +++++++ http_server/handle/auction_price.go | 100 ++++++++++ 5 files changed, 256 insertions(+), 224 deletions(-) create mode 100644 http_server/handle/auction_order_status.go create mode 100644 http_server/handle/auction_pending_order.go create mode 100644 http_server/handle/auction_price.go diff --git a/http_server/handle/auction_bid.go b/http_server/handle/auction_bid.go index 73399e91..cb216fb6 100644 --- a/http_server/handle/auction_bid.go +++ b/http_server/handle/auction_bid.go @@ -85,9 +85,7 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A return fmt.Errorf("GetTimeCell err: %s", err.Error()) } nowTime := timeCell.Timestamp() - //exp + 90 + 27 +3 - //now > exp+117 exp< now - 117 - //now< exp+90 exp>now -90 + if status, _, err := h.checkDutchAuction(acc.ExpiredAt, uint64(nowTime)); err != nil { apiResp.ApiRespErr(http_api.ApiCodeError500, "checkDutchAuction err") return fmt.Errorf("checkDutchAuction err: %s", err.Error()) @@ -95,7 +93,7 @@ func (h *HttpHandle) doAccountAuctionBid(req *ReqAuctionBid, apiResp *http_api.A apiResp.ApiRespErr(http_api.ApiCodeAuctionAccountNotFound, "This account has not been in dutch auction") return nil } - //计算长度 + _, accLen, err := common.GetDotBitAccountLength(req.Account) if err != nil { return @@ -316,15 +314,15 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t // outputs outputs, outputsData, normalCellCapacity, err := h.dasCore.SplitDPCell(&core.ParamSplitDPCell{ - FromLock: p.FromLock, //发送dp方的lock - ToLock: p.ToLock, //接收dp方的lock - DPLiveCell: liveCell, //发送方的dp cell - DPLiveCellCapacity: totalCapacity, //发送方dp的capacity - DPTotalAmount: totalDP, //总的dp金额 - DPTransferAmount: p.AmountDP, //要转账的dp金额 + FromLock: p.FromLock, + ToLock: p.ToLock, + DPLiveCell: liveCell, + DPLiveCellCapacity: totalCapacity, + DPTotalAmount: totalDP, + DPTransferAmount: p.AmountDP, DPSplitCount: config.Cfg.Server.SplitCount, DPSplitAmount: config.Cfg.Server.SplitAmount, - NormalCellLock: p.NormalCellLock, //回收dp cell的ckb的接收地址 + NormalCellLock: p.NormalCellLock, }) if err != nil { return nil, fmt.Errorf("SplitDPCell err: %s", err.Error()) @@ -334,8 +332,6 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t txParams.OutputsData = append(txParams.OutputsData, outputsData[i]) } - //input dp cell capacity < output dp cell capacity 需要用注册商的nomal cell 来垫付 - //input dp cell capacity > output dp cell capacity : has been return in "h.dasCore.SplitDPCell" normalCells, totalNormal, err := h.dasCore.GetBalanceCells(&core.ParamGetBalanceCells{ DasCache: h.dasCache, LockScript: h.serverScript, @@ -352,7 +348,7 @@ func (h *HttpHandle) buildAuctionBidTx(req *reqBuildTx, p *auctionBidParams) (*t }) } - //返还给旧账户的 capacity + //old owner capacity txParams.Outputs = append(txParams.Outputs, &types.CellOutput{ Capacity: accCellCapacity, Lock: contractDas.ToScript(oldAccOwnerArgs), diff --git a/http_server/handle/auction_info.go b/http_server/handle/auction_info.go index 7047455a..867f07ac 100644 --- a/http_server/handle/auction_info.go +++ b/http_server/handle/auction_info.go @@ -15,93 +15,6 @@ import ( "time" ) -type ReqAuctionPrice struct { - Account string `json:"account" binding:"required"` -} - -type RespAuctionPrice struct { - //BasicPrice decimal.Decimal `json:"basic_price"` - AccountPrice decimal.Decimal `json:"account_price"` - BaseAmount decimal.Decimal `json:"base_amount"` - PremiumPrice decimal.Decimal `json:"premium_price"` -} - -//查询价格 -func (h *HttpHandle) GetAccountAuctionPrice(ctx *gin.Context) { - var ( - funcName = "GetAccountAuctionPrice" - clientIp = GetClientIp(ctx) - req ReqAuctionPrice - apiResp http_api.ApiResp - err error - ) - - if err := ctx.ShouldBindJSON(&req); err != nil { - log.Error("ShouldBindJSON err: ", err.Error(), funcName, clientIp) - apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params invalid") - ctx.JSON(http.StatusOK, apiResp) - return - } - log.Info("ApiReq:", funcName, clientIp, toolib.JsonString(req)) - - if err = h.doGetAccountAuctionPrice(&req, &apiResp); err != nil { - log.Error("doGetAccountAuctionPrice err:", err.Error(), funcName, clientIp) - } - ctx.JSON(http.StatusOK, apiResp) -} -func (h *HttpHandle) doGetAccountAuctionPrice(req *ReqAuctionPrice, apiResp *http_api.ApiResp) (err error) { - var resp RespAuctionPrice - accountId := common.Bytes2Hex(common.GetAccountIdByAccount(req.Account)) - acc, err := h.dbDao.GetAccountInfoByAccountId(accountId) - if err != nil && err != gorm.ErrRecordNotFound { - apiResp.ApiRespErr(http_api.ApiCodeDbError, "search account err") - return fmt.Errorf("SearchAccount err: %s", err.Error()) - } - //nowTime := uint64(time.Now().Unix()) - timeCell, err := h.dasCore.GetTimeCell() - if err != nil { - apiResp.ApiRespErr(http_api.ApiCodeError500, "GetTimeCell err") - - return fmt.Errorf("GetTimeCell err: %s", err.Error()) - } - nowTime := timeCell.Timestamp() - //exp + 90 + 27 +3 - //now > exp+117 exp< now - 117 - //now< exp+90 exp>now -90 - if status, _, err := h.checkDutchAuction(acc.ExpiredAt, uint64(nowTime)); err != nil { - apiResp.ApiRespErr(http_api.ApiCodeError500, "checkDutchAuction err") - return fmt.Errorf("checkDutchAuction err: %s", err.Error()) - } else if status != tables.SearchStatusOnDutchAuction { - apiResp.ApiRespErr(http_api.ApiCodeAuctionAccountNotFound, "This account has not been in dutch auction") - return nil - } - - //计算长度 - _, accLen, err := common.GetDotBitAccountLength(req.Account) - if err != nil { - return - } - if accLen == 0 { - err = fmt.Errorf("accLen is 0") - return - } - baseAmount, accountPrice, err := h.getAccountPrice(uint8(accLen), "", req.Account, false) - if err != nil { - apiResp.ApiRespErr(http_api.ApiCodeError500, "get account price err") - return fmt.Errorf("getAccountPrice err: %s", err.Error()) - } - auctionConfig, err := h.GetAuctionConfig(h.dasCore) - if err != nil { - err = fmt.Errorf("GetAuctionConfig err: %s", err.Error()) - return - } - resp.BaseAmount = baseAmount - resp.AccountPrice = accountPrice - resp.PremiumPrice = decimal.NewFromFloat(common.Premium(int64(acc.ExpiredAt+uint64(auctionConfig.GracePeriodTime)), int64(nowTime))) - apiResp.ApiRespOK(resp) - return -} - type ReqAccountAuctionInfo struct { Account string `json:"account" binding:"required"` core.ChainTypeAddress @@ -236,126 +149,3 @@ func (h *HttpHandle) doGetAccountAuctionInfo(req *ReqAccountAuctionInfo, apiResp apiResp.ApiRespOK(resp) return } - -type ReqGetAuctionOrder struct { - Hash string `json:"hash" binding:"required"` - core.ChainTypeAddress - address string - chainType common.ChainType -} -type RepReqGetAuctionOrder struct { - Account string `json:"account"` - Hash string `json:"hash"` - Status int `json:"status"` - BasicPrice decimal.Decimal `json:"basic_price" gorm:"column:basic_price;type:decimal(60,0) NOT NULL DEFAULT '0' COMMENT ''"` - PremiumPrice decimal.Decimal `json:"premium_price" gorm:"column:premium_price;type:decimal(60,0) NOT NULL DEFAULT '0' COMMENT ''"` -} - -func (h *HttpHandle) GetAuctionOrderStatus(ctx *gin.Context) { - var ( - funcName = "GetAuctionOrderStatus" - clientIp = GetClientIp(ctx) - req ReqGetAuctionOrder - apiResp http_api.ApiResp - err error - ) - - if err := ctx.ShouldBindJSON(&req); err != nil { - log.Error("ShouldBindJSON err: ", err.Error(), funcName, clientIp) - apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params invalid") - ctx.JSON(http.StatusOK, apiResp) - return - } - - log.Info("ApiReq:", funcName, clientIp, toolib.JsonString(req)) - - if err = h.doGetAuctionOrderStatus(&req, &apiResp); err != nil { - log.Error("doGetAuctionOrderStatus err:", err.Error(), funcName, clientIp) - } - ctx.JSON(http.StatusOK, apiResp) -} - -func (h *HttpHandle) doGetAuctionOrderStatus(req *ReqGetAuctionOrder, apiResp *http_api.ApiResp) (err error) { - var resp RepReqGetAuctionOrder - - addrHex, err := req.FormatChainTypeAddress(config.Cfg.Server.Net, true) - if err != nil { - apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) - return nil - } - req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType - order, err := h.dbDao.GetAuctionOrderStatus(addrHex.ChainType, addrHex.AddressHex, req.Hash) - if err != nil { - apiResp.ApiRespErr(http_api.ApiCodeDbError, "db error") - return - } - if order.Id == 0 { - apiResp.ApiRespErr(http_api.ApiCodeAuctionOrderNotFound, "order not found") - return - } - - resp.Account = order.Account - resp.PremiumPrice = order.PremiumPrice - resp.BasicPrice = order.BasicPrice - resp.Hash, _ = common.String2OutPoint(order.Outpoint) - resp.Status = order.Status - apiResp.ApiRespOK(resp) - return -} - -type ReqGetGetPendingAuctionOrder struct { - core.ChainTypeAddress - address string - chainType common.ChainType -} - -func (h *HttpHandle) GetPendingAuctionOrder(ctx *gin.Context) { - var ( - funcName = "GetPendingAuctionOrder" - clientIp = GetClientIp(ctx) - req ReqGetGetPendingAuctionOrder - apiResp http_api.ApiResp - err error - ) - - if err := ctx.ShouldBindJSON(&req); err != nil { - log.Error("ShouldBindJSON err: ", err.Error(), funcName, clientIp) - apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params invalid") - ctx.JSON(http.StatusOK, apiResp) - return - } - - log.Info("ApiReq:", funcName, clientIp, toolib.JsonString(req)) - - if err = h.doGetPendingAuctionOrder(&req, &apiResp); err != nil { - log.Error("GetBidStatus err:", err.Error(), funcName, clientIp) - } - ctx.JSON(http.StatusOK, apiResp) -} - -func (h *HttpHandle) doGetPendingAuctionOrder(req *ReqGetGetPendingAuctionOrder, apiResp *http_api.ApiResp) (err error) { - resp := make([]RepReqGetAuctionOrder, 0) - addrHex, err := req.FormatChainTypeAddress(config.Cfg.Server.Net, true) - if err != nil { - apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) - return nil - } - req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType - list, err := h.dbDao.GetPendingAuctionOrder(addrHex.ChainType, addrHex.AddressHex) - if err != nil { - apiResp.ApiRespErr(http_api.ApiCodeDbError, "db error") - return - } - for _, v := range list { - hash, _ := common.String2OutPoint(v.Outpoint) - resp = append(resp, RepReqGetAuctionOrder{ - Account: v.Account, - PremiumPrice: v.PremiumPrice, - BasicPrice: v.BasicPrice, - Hash: hash, - Status: v.Status, - }) - } - apiResp.ApiRespOK(resp) - return -} diff --git a/http_server/handle/auction_order_status.go b/http_server/handle/auction_order_status.go new file mode 100644 index 00000000..632044c9 --- /dev/null +++ b/http_server/handle/auction_order_status.go @@ -0,0 +1,78 @@ +package handle + +import ( + "das_register_server/config" + "github.com/dotbitHQ/das-lib/common" + "github.com/dotbitHQ/das-lib/core" + "github.com/dotbitHQ/das-lib/http_api" + "github.com/gin-gonic/gin" + "github.com/scorpiotzh/toolib" + "github.com/shopspring/decimal" + "net/http" +) + +type ReqAuctionOrderStatus struct { + Hash string `json:"hash" binding:"required"` + core.ChainTypeAddress + address string + chainType common.ChainType +} +type RepReqGetAuctionOrder struct { + Account string `json:"account"` + Hash string `json:"hash"` + Status int `json:"status"` + BasicPrice decimal.Decimal `json:"basic_price" gorm:"column:basic_price;type:decimal(60,0) NOT NULL DEFAULT '0' COMMENT ''"` + PremiumPrice decimal.Decimal `json:"premium_price" gorm:"column:premium_price;type:decimal(60,0) NOT NULL DEFAULT '0' COMMENT ''"` +} + +func (h *HttpHandle) GetAuctionOrderStatus(ctx *gin.Context) { + var ( + funcName = "GetAuctionOrderStatus" + clientIp = GetClientIp(ctx) + req ReqAuctionOrderStatus + apiResp http_api.ApiResp + err error + ) + + if err := ctx.ShouldBindJSON(&req); err != nil { + log.Error("ShouldBindJSON err: ", err.Error(), funcName, clientIp) + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params invalid") + ctx.JSON(http.StatusOK, apiResp) + return + } + + log.Info("ApiReq:", funcName, clientIp, toolib.JsonString(req)) + + if err = h.doGetAuctionOrderStatus(&req, &apiResp); err != nil { + log.Error("doGetAuctionOrderStatus err:", err.Error(), funcName, clientIp) + } + ctx.JSON(http.StatusOK, apiResp) +} + +func (h *HttpHandle) doGetAuctionOrderStatus(req *ReqAuctionOrderStatus, apiResp *http_api.ApiResp) (err error) { + var resp RepReqGetAuctionOrder + + addrHex, err := req.FormatChainTypeAddress(config.Cfg.Server.Net, true) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) + return nil + } + req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType + order, err := h.dbDao.GetAuctionOrderStatus(addrHex.ChainType, addrHex.AddressHex, req.Hash) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeDbError, "db error") + return + } + if order.Id == 0 { + apiResp.ApiRespErr(http_api.ApiCodeAuctionOrderNotFound, "order not found") + return + } + + resp.Account = order.Account + resp.PremiumPrice = order.PremiumPrice + resp.BasicPrice = order.BasicPrice + resp.Hash, _ = common.String2OutPoint(order.Outpoint) + resp.Status = order.Status + apiResp.ApiRespOK(resp) + return +} diff --git a/http_server/handle/auction_pending_order.go b/http_server/handle/auction_pending_order.go new file mode 100644 index 00000000..d338cd44 --- /dev/null +++ b/http_server/handle/auction_pending_order.go @@ -0,0 +1,68 @@ +package handle + +import ( + "das_register_server/config" + "github.com/dotbitHQ/das-lib/common" + "github.com/dotbitHQ/das-lib/core" + "github.com/dotbitHQ/das-lib/http_api" + "github.com/gin-gonic/gin" + "github.com/scorpiotzh/toolib" + "net/http" +) + +type ReqGetPendingAuctionOrder struct { + core.ChainTypeAddress + address string + chainType common.ChainType +} + +func (h *HttpHandle) GetPendingAuctionOrder(ctx *gin.Context) { + var ( + funcName = "GetPendingAuctionOrder" + clientIp = GetClientIp(ctx) + req ReqGetPendingAuctionOrder + apiResp http_api.ApiResp + err error + ) + + if err := ctx.ShouldBindJSON(&req); err != nil { + log.Error("ShouldBindJSON err: ", err.Error(), funcName, clientIp) + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params invalid") + ctx.JSON(http.StatusOK, apiResp) + return + } + + log.Info("ApiReq:", funcName, clientIp, toolib.JsonString(req)) + + if err = h.doGetPendingAuctionOrder(&req, &apiResp); err != nil { + log.Error("doGetPendingAuctionOrder err:", err.Error(), funcName, clientIp) + } + ctx.JSON(http.StatusOK, apiResp) +} + +func (h *HttpHandle) doGetPendingAuctionOrder(req *ReqGetPendingAuctionOrder, apiResp *http_api.ApiResp) (err error) { + resp := make([]RepReqGetAuctionOrder, 0) + addrHex, err := req.FormatChainTypeAddress(config.Cfg.Server.Net, true) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params is invalid: "+err.Error()) + return nil + } + req.address, req.chainType = addrHex.AddressHex, addrHex.ChainType + list, err := h.dbDao.GetPendingAuctionOrder(addrHex.ChainType, addrHex.AddressHex) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeDbError, "db error") + return + } + for _, v := range list { + hash, _ := common.String2OutPoint(v.Outpoint) + resp = append(resp, RepReqGetAuctionOrder{ + Account: v.Account, + PremiumPrice: v.PremiumPrice, + BasicPrice: v.BasicPrice, + Hash: hash, + Status: v.Status, + }) + } + apiResp.ApiRespOK(resp) + return +} diff --git a/http_server/handle/auction_price.go b/http_server/handle/auction_price.go new file mode 100644 index 00000000..d57039a7 --- /dev/null +++ b/http_server/handle/auction_price.go @@ -0,0 +1,100 @@ +package handle + +import ( + "das_register_server/tables" + "fmt" + "github.com/dotbitHQ/das-lib/common" + "github.com/dotbitHQ/das-lib/http_api" + "github.com/gin-gonic/gin" + "github.com/scorpiotzh/toolib" + "github.com/shopspring/decimal" + "gorm.io/gorm" + "net/http" +) + +type ReqAuctionPrice struct { + Account string `json:"account" binding:"required"` +} + +type RespAuctionPrice struct { + //BasicPrice decimal.Decimal `json:"basic_price"` + AccountPrice decimal.Decimal `json:"account_price"` + BaseAmount decimal.Decimal `json:"base_amount"` + PremiumPrice decimal.Decimal `json:"premium_price"` +} + +//查询价格 +func (h *HttpHandle) GetAccountAuctionPrice(ctx *gin.Context) { + var ( + funcName = "GetAccountAuctionPrice" + clientIp = GetClientIp(ctx) + req ReqAuctionPrice + apiResp http_api.ApiResp + err error + ) + + if err := ctx.ShouldBindJSON(&req); err != nil { + log.Error("ShouldBindJSON err: ", err.Error(), funcName, clientIp) + apiResp.ApiRespErr(http_api.ApiCodeParamsInvalid, "params invalid") + ctx.JSON(http.StatusOK, apiResp) + return + } + log.Info("ApiReq:", funcName, clientIp, toolib.JsonString(req)) + + if err = h.doGetAccountAuctionPrice(&req, &apiResp); err != nil { + log.Error("doGetAccountAuctionPrice err:", err.Error(), funcName, clientIp) + } + ctx.JSON(http.StatusOK, apiResp) +} +func (h *HttpHandle) doGetAccountAuctionPrice(req *ReqAuctionPrice, apiResp *http_api.ApiResp) (err error) { + var resp RespAuctionPrice + accountId := common.Bytes2Hex(common.GetAccountIdByAccount(req.Account)) + acc, err := h.dbDao.GetAccountInfoByAccountId(accountId) + if err != nil && err != gorm.ErrRecordNotFound { + apiResp.ApiRespErr(http_api.ApiCodeDbError, "search account err") + return fmt.Errorf("SearchAccount err: %s", err.Error()) + } + //nowTime := uint64(time.Now().Unix()) + timeCell, err := h.dasCore.GetTimeCell() + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeError500, "GetTimeCell err") + + return fmt.Errorf("GetTimeCell err: %s", err.Error()) + } + nowTime := timeCell.Timestamp() + //exp + 90 + 27 +3 + //now > exp+117 exp< now - 117 + //now< exp+90 exp>now -90 + if status, _, err := h.checkDutchAuction(acc.ExpiredAt, uint64(nowTime)); err != nil { + apiResp.ApiRespErr(http_api.ApiCodeError500, "checkDutchAuction err") + return fmt.Errorf("checkDutchAuction err: %s", err.Error()) + } else if status != tables.SearchStatusOnDutchAuction { + apiResp.ApiRespErr(http_api.ApiCodeAuctionAccountNotFound, "This account has not been in dutch auction") + return nil + } + + //计算长度 + _, accLen, err := common.GetDotBitAccountLength(req.Account) + if err != nil { + return + } + if accLen == 0 { + err = fmt.Errorf("accLen is 0") + return + } + baseAmount, accountPrice, err := h.getAccountPrice(uint8(accLen), "", req.Account, false) + if err != nil { + apiResp.ApiRespErr(http_api.ApiCodeError500, "get account price err") + return fmt.Errorf("getAccountPrice err: %s", err.Error()) + } + auctionConfig, err := h.GetAuctionConfig(h.dasCore) + if err != nil { + err = fmt.Errorf("GetAuctionConfig err: %s", err.Error()) + return + } + resp.BaseAmount = baseAmount + resp.AccountPrice = accountPrice + resp.PremiumPrice = decimal.NewFromFloat(common.Premium(int64(acc.ExpiredAt+uint64(auctionConfig.GracePeriodTime)), int64(nowTime))) + apiResp.ApiRespOK(resp) + return +} From 27fdea6e53884bfb87bd56ebff350983306ee601 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Wed, 22 Nov 2023 10:29:25 +0800 Subject: [PATCH 63/67] update tx list --- tables/t_transaction_info.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tables/t_transaction_info.go b/tables/t_transaction_info.go index adb626ca..dc89c55c 100644 --- a/tables/t_transaction_info.go +++ b/tables/t_transaction_info.go @@ -69,6 +69,7 @@ const ( ActionCrossRefund TxAction = 28 ActionCollectSubAccountProfit TxAction = 29 ActionRenewSubAccount TxAction = 30 + ActionAuctionRefundCapacity TxAction = 31 DasActionTransferBalance = "transfer_balance" DasActionBalanceDeposit = "balance_deposit" @@ -145,6 +146,8 @@ func FormatTxAction(action string) TxAction { return ActionCollectSubAccountProfit case common.DasActionRenewSubAccount: return ActionRenewSubAccount + case common.DasActionBidExpiredAccountAuction: + return ActionAuctionRefundCapacity } return ActionUndefined } From 9d82433a2eb2e1458cc0d4eedd91aecba437801b Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Wed, 22 Nov 2023 16:08:59 +0800 Subject: [PATCH 64/67] sentry --- http_server/router.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/http_server/router.go b/http_server/router.go index 8e968e4e..5ac12b44 100644 --- a/http_server/router.go +++ b/http_server/router.go @@ -5,6 +5,7 @@ import ( "das_register_server/http_server/api_code" "encoding/json" "github.com/dotbitHQ/das-lib/common" + sentrygin "github.com/getsentry/sentry-go/gin" "github.com/gin-gonic/gin" "github.com/scorpiotzh/toolib" "net/http" @@ -25,9 +26,9 @@ func (h *HttpServer) initRouter() { toolib.AllowOriginList = append(toolib.AllowOriginList, originList...) } h.engine.Use(toolib.MiddlewareCors()) - //h.engine.Use(sentrygin.New(sentrygin.Options{ - // Repanic: true, - //})) + h.engine.Use(sentrygin.New(sentrygin.Options{ + Repanic: true, + })) v1 := h.engine.Group("v1") { // cache From 7187048f5d65f267f4fb0f3a191406a889a2e531 Mon Sep 17 00:00:00 2001 From: michael <457813723@qq.com> Date: Wed, 22 Nov 2023 19:10:46 +0800 Subject: [PATCH 65/67] update das-lib --- go.mod | 4 ++-- go.sum | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index 8a1aa2d3..6338d491 100644 --- a/go.mod +++ b/go.mod @@ -3,10 +3,10 @@ module das_register_server go 1.18 require ( - github.com/dotbitHQ/das-lib v1.1.1-0.20231120125536-8d1e4fbda8f4 + github.com/dotbitHQ/das-lib v1.1.1-0.20231122093514-f0d954363c30 github.com/ethereum/go-ethereum v1.10.26 github.com/fsnotify/fsnotify v1.5.4 - github.com/getsentry/sentry-go v0.25.0 // indirect + github.com/getsentry/sentry-go v0.25.0 github.com/gin-gonic/gin v1.9.1 github.com/go-redis/redis v6.15.9+incompatible github.com/minio/blake2b-simd v0.0.0-20160723061019-3f5f724cb5b1 diff --git a/go.sum b/go.sum index ae8073c4..5043a1bb 100644 --- a/go.sum +++ b/go.sum @@ -145,8 +145,8 @@ github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5O github.com/docker/docker v1.4.2-0.20180625184442-8e610b2b55bf/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/dop251/goja v0.0.0-20211011172007-d99e4b8cbf48/go.mod h1:R9ET47fwRVRPZnOGvHxxhuZcbrMCuiqOz3Rlrh4KSnk= github.com/dop251/goja_nodejs v0.0.0-20210225215109-d91c329300e7/go.mod h1:hn7BA7c8pLvoGndExHudxTDKZ84Pyvv+90pbBjbTz0Y= -github.com/dotbitHQ/das-lib v1.1.1-0.20231120125536-8d1e4fbda8f4 h1:8jxgmCThIDkThnwPzWd2XGAMQvCR6SGbk0OygzA5ATo= -github.com/dotbitHQ/das-lib v1.1.1-0.20231120125536-8d1e4fbda8f4/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= +github.com/dotbitHQ/das-lib v1.1.1-0.20231122093514-f0d954363c30 h1:oWdw0Nqf3Qrq8OUftfsj5SDLrNtr5r0CtztPNEU/DVk= +github.com/dotbitHQ/das-lib v1.1.1-0.20231122093514-f0d954363c30/go.mod h1:CvkrfnYLnKjEFTmlz70wssdkRxGvTPnAR5fcAikfu7s= github.com/eclipse/paho.mqtt.golang v1.2.0/go.mod h1:H9keYFcgq3Qr5OUJm/JZI/i6U7joQ8SYLhZwfeOo6Ts= github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= github.com/elazarl/goproxy v0.0.0-20221015165544-a0805db90819 h1:RIB4cRk+lBqKK3Oy0r2gRX4ui7tuhiZq2SuTtTCi0/0= From b625e6d59512b4fef84b0d73ac72626cb800d0ce Mon Sep 17 00:00:00 2001 From: scorpiotzh <835598264@qq.com> Date: Wed, 22 Nov 2023 20:40:19 +0800 Subject: [PATCH 66/67] feat: Fix nil refund list --- unipay/refund.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/unipay/refund.go b/unipay/refund.go index 4f7715ca..5b180dd8 100644 --- a/unipay/refund.go +++ b/unipay/refund.go @@ -75,6 +75,9 @@ func (t *ToolUniPay) doRefund() error { PayHash: v.Hash, }) } + if len(req.RefundList) == 0 { + return nil + } _, err = RefundOrder(req) if err != nil { From e38d8913ac3baffdc9a6699ddd42498cc15593bc Mon Sep 17 00:00:00 2001 From: scorpiotzh <835598264@qq.com> Date: Wed, 22 Nov 2023 21:13:30 +0800 Subject: [PATCH 67/67] feat: Fix refund status --- dao/t_das_order_pay_info.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dao/t_das_order_pay_info.go b/dao/t_das_order_pay_info.go index 5aad0fa5..40d4f002 100644 --- a/dao/t_das_order_pay_info.go +++ b/dao/t_das_order_pay_info.go @@ -121,7 +121,7 @@ func (d *DbDao) UpdateRefundStatusToRefundIng(ids []uint64) error { Where("id IN(?) AND `status`=? AND uni_pay_refund_status=?", ids, tables.OrderTxStatusConfirm, tables.UniPayRefundStatusUnRefund). Updates(map[string]interface{}{ - "uni_pay_refund_status": tables.UniPayRefundStatusRefunded, + "uni_pay_refund_status": tables.UniPayRefundStatusRefunding, }).Error }