sale.go 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  1. package sale
  2. import (
  3. "encoding/hex"
  4. "errors"
  5. "fmt"
  6. "math/big"
  7. "net/http"
  8. "strconv"
  9. "time"
  10. "github.com/ethereum/go-ethereum/core/types"
  11. "github.com/gin-gonic/gin"
  12. "github.com/guregu/null"
  13. "github.com/metarare/metarare_api/api/constant"
  14. "github.com/metarare/metarare_api/common"
  15. "github.com/metarare/metarare_api/helpers"
  16. "github.com/metarare/metarare_api/helpers/gauth"
  17. "github.com/metarare/metarare_api/helpers/gerror"
  18. "github.com/metarare/metarare_api/models"
  19. "github.com/metarare/metarare_api/util"
  20. "github.com/metarare/metarare_api/view"
  21. "gorm.io/gorm"
  22. )
  23. type SaleV1Router struct {
  24. group *gin.RouterGroup
  25. mDB *gorm.DB
  26. rDB *gorm.DB
  27. awsConf util.AWSConfs
  28. metaAwsConf util.AWSConfs
  29. }
  30. type TargetID struct {
  31. ID uint64 `json:"id"`
  32. }
  33. type BidData struct {
  34. SaleID uint64 `json:"sale_id"`
  35. BidPrice float64 `json:"bid_price"`
  36. Currency string `json:"currency"`
  37. }
  38. type RegisterResaleData struct {
  39. TokenID uint64 `json:"token_id" binding:"required"`
  40. SaleType string `json:"sale_type" binding:"required"`
  41. Price float64 `json:"price"`
  42. StartPrice float64 `json:"start_price"`
  43. StartAt time.Time `json:"start_at"`
  44. EndAt time.Time `json:"end_at"`
  45. Currency string `json:"currency" binding:"required"`
  46. }
  47. func NewSaleV1Router(r common.Router, basePath string) SaleV1Router {
  48. s := SaleV1Router{
  49. group: r.Version.Group(basePath),
  50. mDB: r.Db.MasterDB,
  51. rDB: r.Db.ReadDB,
  52. awsConf: util.AWSConfs{
  53. Region: r.Env.GetString("storage.region"),
  54. BucketName: r.Env.GetString("storage.assets_buket_name"),
  55. Access_key_id: r.Env.GetString("storage.access_key_id"),
  56. Access_key: r.Env.GetString("storage.access_key"),
  57. },
  58. metaAwsConf: util.AWSConfs{
  59. Region: r.Env.GetString("storage.region"),
  60. BucketName: r.Env.GetString("storage.nftinfo_buket_name"),
  61. Access_key_id: r.Env.GetString("storage.access_key_id"),
  62. Access_key: r.Env.GetString("storage.access_key"),
  63. },
  64. }
  65. s.group.GET(":sale_id", s.getDetailSaleInfo)
  66. s.group.PATCH("status", s.updateStatus)
  67. s.group.POST("bid", s.bidAuction)
  68. s.group.PATCH("bid", s.cancelBid)
  69. s.group.GET("bid/:sale_id", s.getBidHistory)
  70. s.group.POST("buy", s.buyNow)
  71. s.group.POST("auction", s.sellHighestPrice)
  72. s.group.POST("resale", s.registerResale)
  73. s.group.GET("ranking", s.rankningSale)
  74. return s
  75. }
  76. // getDetailSaleInfo godoc
  77. // @Summary get detail sale data
  78. // @Description NFT 판매 상세페이지 데이터 가져오기
  79. // @Schemes
  80. // @Tags sale
  81. // @name get-string-by-int
  82. // @Accept json
  83. // @Produce json
  84. // @Success 200 {obejct} view.DetailSaleData
  85. // @Param sale_id path string true "sale id"
  86. // @Router /sale/{sale_id} [get]
  87. func (s SaleV1Router) getDetailSaleInfo(c *gin.Context) {
  88. userID, _ := gauth.GetCurrentUserIDToInt64(c)
  89. saleID := c.Param("sale_id")
  90. intScaleID, _ := strconv.Atoi(saleID)
  91. if helpers.Contains(constant.HideFromListIds, intScaleID) {
  92. return
  93. }
  94. if saleID == "" {
  95. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, errors.New("invalid parameter value"))
  96. return
  97. }
  98. wallet := models.UserWallet{}
  99. if userID != 0 {
  100. if err := s.rDB.Where("user_id = ?", userID).Find(&wallet).Error; err != nil {
  101. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  102. return
  103. }
  104. }
  105. response := view.DetailSaleData{}
  106. if err := view.GetSaleData(s.rDB, wallet.Address, wallet.UserID, saleID).Where("sale.id = ?", saleID).Find(&response.Sale).Error; err != nil {
  107. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  108. return
  109. }
  110. // t := []models.Traits{}
  111. if err := s.rDB.Select("traits.*").Table("sale").
  112. Joins("INNER JOIN traits ON traits.token_id = sale.token_id").
  113. Where("sale.id = ?", saleID).Find(&response.Traits).Error; err != nil {
  114. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  115. return
  116. }
  117. gerror.IntegratedResponseToRequest(c, http.StatusOK, gerror.OK, response, nil)
  118. return
  119. }
  120. // updateStatus godoc
  121. // @Summary update sale statue for cancel
  122. // @Description 등록한 오너인 경우에만 실행가능, 판매하지 않고 판매를 강제 종료시킨다.
  123. // @Schemes
  124. // @security ApiKeyAuth
  125. // @Tags sale
  126. // @Accept json
  127. // @Produce json
  128. // @Param TargetID body TargetID true "selected target id"
  129. // @Success 200 {string} OK
  130. // @Router /sale/status [patch]
  131. func (s SaleV1Router) updateStatus(c *gin.Context) {
  132. userID, err := gauth.GetCurrentUserIDToInt64(c)
  133. if err != nil || userID == 0 {
  134. gerror.IntegratedResponseToRequest(c, http.StatusUnauthorized, gerror.Unauthorized, nil, err)
  135. return
  136. }
  137. request := TargetID{}
  138. if err := c.ShouldBindJSON(&request); err != nil {
  139. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  140. return
  141. }
  142. isOwner := view.Owner{}
  143. if err := view.IsOwner(s.rDB, userID).Where("sale.id = ?", request.ID).Find(&isOwner).Error; err != nil {
  144. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  145. return
  146. } else if !isOwner.IsOwner {
  147. gerror.IntegratedResponseToRequest(c, http.StatusUnauthorized, gerror.Unauthorized, nil, errors.New("permission not found "))
  148. return
  149. }
  150. //NOTE x fixed, time인경우 취소가능, time인 경우 경매기록이 있으면 취소가 안된다.
  151. sale := models.Sale{}
  152. _err := s.rDB.Where("id = ?", request.ID).Find(&sale).Error
  153. if errors.Is(_err, gorm.ErrRecordNotFound) {
  154. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, _err)
  155. return
  156. }
  157. //NOTE x auction인경우 판매취소 불가, time인 경우 비딩 되어있는 값이 있으면 불가
  158. if sale.SaleType == "auction" {
  159. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, errors.New("can't cancel the sale"))
  160. return
  161. } else if sale.SaleType == "time" {
  162. bidLog := []models.BidLog{}
  163. _err := s.rDB.Where("sale_id = ?", sale.ID).Find(&bidLog).Error
  164. if errors.Is(_err, gorm.ErrRecordNotFound) {
  165. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, _err)
  166. return
  167. }
  168. if len(bidLog) > 0 {
  169. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, errors.New("can't cancel the sale"))
  170. return
  171. }
  172. }
  173. if err := s.mDB.Model(&models.Sale{}).Where("id = ?", request.ID).Update("status", "cancel").Error; err != nil {
  174. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  175. return
  176. }
  177. gerror.IntegratedResponseToRequest(c, http.StatusOK, gerror.OK, nil, nil)
  178. return
  179. }
  180. // bidAuction godoc
  181. // @Summary create bid
  182. // @Description 입찰하기
  183. // @Schemes
  184. // @security ApiKeyAuth
  185. // @Tags sale
  186. // @Accept json
  187. // @Produce json
  188. // @Param BidData body BidData true "body struct"
  189. // @Success 200 {string} OK
  190. // @Router /sale/bid [post]
  191. func (s SaleV1Router) bidAuction(c *gin.Context) {
  192. userID, _err := gauth.GetCurrentUserIDToInt64(c)
  193. if _err != nil || userID == 0 {
  194. gerror.IntegratedResponseToRequest(c, http.StatusUnauthorized, gerror.Unauthorized, nil, _err)
  195. return
  196. }
  197. request := BidData{}
  198. if err := c.ShouldBindJSON(&request); err != nil {
  199. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  200. return
  201. }
  202. sale := models.Sale{}
  203. err := s.rDB.Where("id = ?", request.SaleID).Find(&sale).Error
  204. if errors.Is(err, gorm.ErrRecordNotFound) {
  205. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  206. return
  207. }
  208. if sale.SaleType == "time" && sale.StartPrice.Float64 >= request.BidPrice {
  209. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, errors.New("please check the minimum bid amount"))
  210. return
  211. }
  212. wallet := models.UserWallet{}
  213. err = s.rDB.Where("user_id = ?", userID).Find(&wallet).Error
  214. if errors.Is(err, gorm.ErrRecordNotFound) {
  215. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  216. return
  217. }
  218. bidLog := models.BidLog{}
  219. if err := s.rDB.Where("sale_id = ? AND address = ? AND is_cancel = 0", request.SaleID, wallet.Address).Find(&bidLog).Error; err != nil {
  220. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  221. return
  222. } else if bidLog.ID != 0 {
  223. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, errors.New("already participating in the bidding"))
  224. return
  225. }
  226. setting := models.Setting{}
  227. if err := s.rDB.Find(&setting).Error; err != nil {
  228. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  229. return
  230. } else if setting.ID == 0 {
  231. gerror.IntegratedResponseToRequest(c, http.StatusNotFound, gerror.NotFoundRecord, nil, errors.New("not found recored"))
  232. return
  233. }
  234. //NOTE x 사용 가능 금액 검증
  235. if request.Currency == "eth" {
  236. _, availableBalance := helpers.GetSelectedBalance(s.rDB, userID, request.Currency, wallet.Address)
  237. if (request.BidPrice + setting.GasDeposit) > availableBalance {
  238. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, errors.New("lack of holding balance"))
  239. return
  240. }
  241. } else {
  242. _, availableBalance := helpers.GetSelectedBalance(s.rDB, userID, request.Currency, wallet.Address)
  243. if request.BidPrice > availableBalance {
  244. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, errors.New("lack of holding balance"))
  245. return
  246. }
  247. _, availableEthBalance := helpers.GetSelectedBalance(s.rDB, userID, "eth", wallet.Address)
  248. if setting.GasDeposit > availableEthBalance {
  249. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, errors.New("lack of holding balance"))
  250. return
  251. }
  252. }
  253. tx := s.mDB.Begin()
  254. defer common.DBTransaction(tx)
  255. _bidLog := models.BidLog{
  256. SaleID: request.SaleID,
  257. IsCancel: 0,
  258. Price: request.BidPrice,
  259. Address: wallet.Address,
  260. }
  261. if err := tx.Save(&_bidLog).Error; err != nil {
  262. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  263. tx.Rollback()
  264. return
  265. }
  266. deposit := models.Deposit{
  267. UserID: userID,
  268. SaleID: request.SaleID,
  269. Type: request.Currency,
  270. EthPrice: null.FloatFrom(setting.GasDeposit),
  271. Status: "deposit",
  272. }
  273. if request.Currency == "eth" {
  274. deposit.EthPrice = null.FloatFrom(deposit.EthPrice.Float64 + request.BidPrice)
  275. } else if request.Currency == "mr" {
  276. deposit.MrPrice = null.FloatFrom(request.BidPrice)
  277. } else if request.Currency == "mf1" {
  278. deposit.Mf1Price = null.FloatFrom(request.BidPrice)
  279. }
  280. if err := tx.Save(&deposit).Error; err != nil {
  281. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  282. tx.Rollback()
  283. return
  284. }
  285. if err := tx.Commit().Error; err != nil {
  286. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  287. tx.Rollback()
  288. return
  289. }
  290. gerror.IntegratedResponseToRequest(c, http.StatusOK, gerror.OK, nil, nil)
  291. return
  292. }
  293. // cancelBid godoc
  294. // @Summary cancel bid
  295. // @Description 입찰 취소하기, 입찰을 다시하려면 취소 후 다시 해야한다.
  296. // @Schemes
  297. // @security ApiKeyAuth
  298. // @Tags sale
  299. // @Accept json
  300. // @Produce json
  301. // @Param TargetID body TargetID true "body struct"
  302. // @Success 200 {string} OK
  303. // @Router /sale/bid [patch]
  304. func (s SaleV1Router) cancelBid(c *gin.Context) {
  305. userID, err := gauth.GetCurrentUserIDToInt64(c)
  306. if err != nil || userID == 0 {
  307. gerror.IntegratedResponseToRequest(c, http.StatusUnauthorized, gerror.Unauthorized, nil, err)
  308. return
  309. }
  310. request := TargetID{}
  311. if err := c.ShouldBindJSON(&request); err != nil {
  312. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  313. return
  314. }
  315. wallet := models.UserWallet{}
  316. if err := s.rDB.Where("user_id = ?", userID).Find(&wallet).Error; err != nil {
  317. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  318. return
  319. } else if wallet.ID == 0 {
  320. gerror.IntegratedResponseToRequest(c, http.StatusNotFound, gerror.NotFoundRecord, nil, errors.New("not found recored"))
  321. return
  322. }
  323. bidLog := models.BidLog{}
  324. if err := s.rDB.Where("sale_id = ? AND address = ? AND is_cancel = 0", request.ID, wallet.Address).Find(&bidLog).Error; err != nil {
  325. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  326. return
  327. } else if bidLog.ID == 0 {
  328. gerror.IntegratedResponseToRequest(c, http.StatusNotFound, gerror.NotFoundRecord, nil, errors.New("not found recored"))
  329. return
  330. }
  331. deposit := models.Deposit{}
  332. if err := s.rDB.Where("user_id = ? AND sale_id = ? AND status = 'deposit'", userID, request.ID).Find(&deposit).Error; err != nil {
  333. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  334. return
  335. } else if deposit.ID == 0 {
  336. gerror.IntegratedResponseToRequest(c, http.StatusNotFound, gerror.NotFoundRecord, nil, errors.New("not found recored"))
  337. return
  338. }
  339. tx := s.mDB.Begin()
  340. defer common.DBTransaction(tx)
  341. if err := tx.Model(&bidLog).Update("is_cancel", 1).Error; err != nil {
  342. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  343. tx.Rollback()
  344. return
  345. }
  346. if err := tx.Model(&deposit).Update("status", "withdrawal").Error; err != nil {
  347. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  348. tx.Rollback()
  349. return
  350. }
  351. if err := tx.Commit().Error; err != nil {
  352. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  353. tx.Rollback()
  354. return
  355. }
  356. gerror.IntegratedResponseToRequest(c, http.StatusOK, gerror.OK, nil, nil)
  357. return
  358. }
  359. // getBidHistory godoc
  360. // @Summary get bid history
  361. // @Description NFT 판매 상세페이지 경매 기록 탭
  362. // @Schemes
  363. // @security ApiKeyAuth
  364. // @Tags sale
  365. // @name get-string-by-int
  366. // @Accept json
  367. // @Produce json
  368. // @Success 200 {obejct} []view.BidList
  369. // @Param sale_id path string true "sale id"
  370. // @Router /sale/bid/{sale_id} [get]
  371. func (s SaleV1Router) getBidHistory(c *gin.Context) {
  372. saleID := c.Param("sale_id")
  373. if saleID == "" {
  374. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, errors.New("invalid parameter value"))
  375. return
  376. }
  377. response := []view.BidList{}
  378. if err := view.GetBidList(s.rDB).Where("sale.id = ?", saleID).Order("bid_log.id desc").Find(&response).Error; err != nil {
  379. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  380. return
  381. }
  382. gerror.IntegratedResponseToRequest(c, http.StatusOK, gerror.OK, response, nil)
  383. return
  384. }
  385. // buyNow godoc
  386. // @Summary buy now item
  387. // @Description 아이템 즉시 구매
  388. // @Schemes
  389. // @security ApiKeyAuth
  390. // @Tags sale
  391. // @Accept json
  392. // @Produce json
  393. // @Param BidData body BidData true "body struct"
  394. // @Success 200 {string} OK
  395. // @Router /sale/buy [post]
  396. func (s SaleV1Router) buyNow(c *gin.Context) {
  397. userID, err := gauth.GetCurrentUserIDToInt64(c)
  398. if err != nil || userID == 0 {
  399. gerror.IntegratedResponseToRequest(c, http.StatusUnauthorized, gerror.Unauthorized, nil, err)
  400. return
  401. }
  402. request := BidData{}
  403. if err := c.ShouldBindJSON(&request); err != nil {
  404. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  405. return
  406. }
  407. sale := models.Sale{}
  408. if err := s.rDB.Where("id = ?", request.SaleID).Find(&sale).Error; err != nil {
  409. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  410. return
  411. } else if sale.ID == 0 {
  412. gerror.IntegratedResponseToRequest(c, http.StatusNotFound, gerror.NotFoundRecord, nil, err)
  413. return
  414. }
  415. //NOTE x 요청 한 값과 실제 NFT 가격이 맞는지 비교 (필요한가 ..?)
  416. if request.BidPrice != sale.Price.Float64 {
  417. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  418. return
  419. }
  420. wallet := models.UserWallet{}
  421. if err := s.rDB.Where("user_id = ?", userID).Find(&wallet).Error; err != nil {
  422. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  423. return
  424. } else if wallet.ID == 0 {
  425. gerror.IntegratedResponseToRequest(c, http.StatusNotFound, gerror.NotFoundRecord, nil, err)
  426. return
  427. }
  428. token := models.Token{}
  429. if err := s.rDB.Where("id = ?", sale.TokenID).Find(&token).Error; err != nil {
  430. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  431. return
  432. } else if token.ID == 0 {
  433. gerror.IntegratedResponseToRequest(c, http.StatusNotFound, gerror.NotFoundRecord, nil, err)
  434. return
  435. }
  436. var firstOrder bool
  437. if sale.IsResale == 1 && (token.LastestCurrency.String != "") {
  438. firstOrder = false
  439. } else if sale.IsResale == 0 || (sale.IsResale == 1 && token.LastestCurrency.String == "") {
  440. firstOrder = true
  441. }
  442. var _official bool
  443. ownerWallet := models.UserWallet{}
  444. _err := s.rDB.Where("address = ?", token.OwnerAddress).Find(&ownerWallet).Error
  445. if errors.Is(_err, gorm.ErrRecordNotFound) {
  446. gerror.IntegratedResponseToRequest(c, http.StatusNotFound, gerror.NotFoundRecord, nil, err)
  447. return
  448. }
  449. collection := models.Collection{}
  450. _err = s.rDB.Where("id = ?", token.CollectionID).Find(&collection).Error
  451. if errors.Is(_err, gorm.ErrRecordNotFound) {
  452. gerror.IntegratedResponseToRequest(c, http.StatusNotFound, gerror.NotFoundRecord, nil, err)
  453. return
  454. }
  455. setting := models.Setting{}
  456. _err = s.rDB.Find(&setting).Error
  457. if errors.Is(_err, gorm.ErrRecordNotFound) {
  458. gerror.IntegratedResponseToRequest(c, http.StatusNotFound, gerror.NotFoundRecord, nil, err)
  459. return
  460. }
  461. if collection.IsOfficial == 1 {
  462. _official = true
  463. } else {
  464. _official = false
  465. }
  466. fmt.Println("---------------------------------------------------------")
  467. fmt.Printf("first_order: %t\n", firstOrder)
  468. fmt.Printf("official: %t\n", _official)
  469. //NOTE x 사용 가능 금액 검증
  470. if request.Currency == "eth" {
  471. _, availableBalance := helpers.GetSelectedBalance(s.rDB, userID, request.Currency, wallet.Address)
  472. if (sale.Price.Float64 + setting.GasDeposit) > availableBalance {
  473. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, errors.New("lack of holding balance"))
  474. return
  475. }
  476. } else {
  477. _, availableBalance := helpers.GetSelectedBalance(s.rDB, userID, request.Currency, wallet.Address)
  478. if sale.Price.Float64 > availableBalance {
  479. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, errors.New("lack of holding balance"))
  480. return
  481. }
  482. _, availableEthBalance := helpers.GetSelectedBalance(s.rDB, userID, "eth", wallet.Address)
  483. if setting.GasDeposit > availableEthBalance {
  484. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, errors.New("lack of holding balance"))
  485. return
  486. }
  487. var allowanceAmount *big.Int
  488. var err error
  489. var _currency helpers.ContractType
  490. if request.Currency == "mf" {
  491. _currency = helpers.MetaFinance
  492. allowanceAmount, err = helpers.GetAllowance(helpers.MetaFinance, wallet.Address)
  493. } else if request.Currency == "mr" {
  494. _currency = helpers.MetaRare
  495. allowanceAmount, err = helpers.GetAllowance(helpers.MetaRare, wallet.Address)
  496. }
  497. if request.BidPrice > helpers.TypeCastingToFloat64(allowanceAmount) {
  498. fmt.Println("excution approve")
  499. _, _, _, err = helpers.ApproveForERC20(_currency, wallet.PrivateKey, common.MaxBig256)
  500. if err != nil {
  501. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  502. return
  503. }
  504. }
  505. }
  506. tx := s.mDB.Begin()
  507. defer common.DBTransaction(tx)
  508. if err := tx.Model(&sale).Update("status", "end").Error; err != nil {
  509. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  510. tx.Rollback()
  511. return
  512. }
  513. if err := tx.Model(&token).Updates(models.Token{OwnerAddress: wallet.Address, LastestPrice: null.FloatFrom(request.BidPrice), LastestCurrency: null.StringFrom(request.Currency)}).Error; err != nil {
  514. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  515. tx.Rollback()
  516. return
  517. }
  518. _v := common.MakeHashData{
  519. OwnerAddress: ownerWallet.Address,
  520. CollectionAddress: collection.ContractAddress,
  521. TokenType: token.Type,
  522. TokenID: int64(token.ID),
  523. Currency: sale.Currency,
  524. Price: sale.Price.Float64,
  525. Index: int64(token.Index.Int64),
  526. TotalIndex: int64(token.TotalCount.Int64),
  527. CreationTax: int64(token.Royalties * 100),
  528. PrevTreasuryTax: int64(sale.TreasuryTax * 100),
  529. TreasuryAddress: setting.TreasuryAddress,
  530. }
  531. _vv, err := common.MakeSining(tx, _v)
  532. if err != nil {
  533. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  534. tx.Rollback()
  535. return
  536. }
  537. _sigData, _hashData, err := helpers.Signing(_vv, ownerWallet.PrivateKey)
  538. if err != nil {
  539. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  540. tx.Rollback()
  541. return
  542. }
  543. fmt.Printf("sig_data: %s \n", hex.EncodeToString(_sigData))
  544. fmt.Printf("hash_data: %s \n", hex.EncodeToString(_hashData))
  545. var txHash *types.Transaction
  546. _hash, _ := hex.DecodeString(sale.HashData)
  547. _sig, _ := hex.DecodeString(sale.Signature)
  548. var _hashedData [32]byte
  549. var _signature [65]byte
  550. copy(_hashedData[:], _hash)
  551. copy(_signature[:], _sig)
  552. //NOTE x resale인 경우와 첫 판매인 경우 분기
  553. if sale.IsResale == 1 && !firstOrder {
  554. if token.Type == "erc721" {
  555. _txHash, _, err := helpers.Order721OnlyTransfer(_vv, _hashedData, wallet.PrivateKey, _signature)
  556. if err != nil {
  557. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  558. tx.Rollback()
  559. return
  560. }
  561. txHash = _txHash
  562. } else if token.Type == "erc1155" {
  563. _txHash, _, err := helpers.Order1155OnlyTransfer(_vv, _hashedData, wallet.PrivateKey, _signature)
  564. if err != nil {
  565. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  566. tx.Rollback()
  567. return
  568. }
  569. txHash = _txHash
  570. }
  571. } else if sale.IsResale == 0 || firstOrder {
  572. fmt.Println("excution minting function")
  573. if token.Type == "erc721" {
  574. fmt.Println("excution Order721WithMinting")
  575. _txHash, _, err := helpers.Order721WithMinting(_vv, _hashedData, wallet.PrivateKey, _signature, _official)
  576. if err != nil {
  577. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  578. tx.Rollback()
  579. return
  580. }
  581. txHash = _txHash
  582. } else if token.Type == "erc1155" {
  583. fmt.Println("excution Order1155WithMinting")
  584. _txHash, _, err := helpers.Order1155WithMinting(_vv, _hashedData, wallet.PrivateKey, _signature, _official)
  585. if err != nil {
  586. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  587. tx.Rollback()
  588. return
  589. }
  590. txHash = _txHash
  591. }
  592. //NOTE x 메타데이터 넣어주는 작업 ( 최초 한번만 넣어 준다 )
  593. err = util.MakeMetaData(s.metaAwsConf, tx, sale.TokenID, txHash.Hash().String(), token.Name, token.Description, token.AssetsImageURL)
  594. if err != nil {
  595. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.GoContextError, nil, err)
  596. tx.Rollback()
  597. return
  598. }
  599. fmt.Println("finish")
  600. } else {
  601. fmt.Println("else")
  602. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.GoContextError, nil, err)
  603. tx.Rollback()
  604. return
  605. }
  606. fmt.Println("commit")
  607. if err := tx.Commit().Error; err != nil {
  608. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  609. tx.Rollback()
  610. return
  611. }
  612. // HAVE TO DISCUS WITH S.M Park
  613. tx = s.mDB.Begin()
  614. defer common.DBTransaction(tx)
  615. // index 0 upper row : seller
  616. // index 1 lower row : purchaser
  617. log := []models.Log{}
  618. if err := s.rDB.Where("sale_uid =(?) AND type in (?)", sale.UID, []string{"purchase", "sell"}).Order("id desc").Limit(2).Find(&log).Error; err != nil {
  619. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  620. return
  621. }
  622. lr := []models.LogRelation{}
  623. if err := s.rDB.Where("id in (?)", []uint64{log[0].LogRelationID, log[1].LogRelationID}).Order("id desc").Find(&lr).Error; err != nil {
  624. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  625. return
  626. }
  627. log[0].FromAddress = null.StringFrom(wallet.Address)
  628. log[0].Price = null.FloatFrom(request.BidPrice)
  629. log[0].ToAddress = null.StringFrom(ownerWallet.Address)
  630. log[1].FromAddress = null.StringFrom(ownerWallet.Address)
  631. lr[1].UserID = null.IntFrom(int64(userID))
  632. log[1].Price = null.FloatFrom(request.BidPrice)
  633. log[1].ToAddress = null.StringFrom(wallet.Address)
  634. if err := tx.Updates(&log[0]).Error; err != nil {
  635. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  636. tx.Rollback()
  637. return
  638. }
  639. if err := tx.Updates(&log[1]).Error; err != nil {
  640. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  641. tx.Rollback()
  642. return
  643. }
  644. if err := tx.Updates(&lr[1]).Error; err != nil {
  645. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  646. tx.Rollback()
  647. return
  648. }
  649. if err := tx.Commit().Error; err != nil {
  650. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  651. tx.Rollback()
  652. return
  653. }
  654. gerror.IntegratedResponseToRequest(c, http.StatusOK, gerror.OK, txHash.Hash().String(), nil)
  655. return
  656. }
  657. // sellHighestPrice godoc
  658. // @Summary highest price sell
  659. // @Description 최고가 판매
  660. // @Schemes
  661. // @security ApiKeyAuth
  662. // @Tags sale
  663. // @Accept json
  664. // @Produce json
  665. // @Param BidData body BidData true "body struct"
  666. // @Success 200 {string} OK
  667. // @Router /sale/auction [post]
  668. func (s SaleV1Router) sellHighestPrice(c *gin.Context) {
  669. userID, err := gauth.GetCurrentUserIDToInt64(c)
  670. if err != nil || userID == 0 {
  671. gerror.IntegratedResponseToRequest(c, http.StatusUnauthorized, gerror.Unauthorized, nil, err)
  672. return
  673. }
  674. request := BidData{}
  675. if err := c.ShouldBindJSON(&request); err != nil {
  676. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  677. return
  678. }
  679. wallet := models.UserWallet{}
  680. _err := s.rDB.Where("user_id = ?", userID).Find(&wallet).Error
  681. if errors.Is(_err, gorm.ErrRecordNotFound) {
  682. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.NotFoundRecord, nil, err)
  683. return
  684. }
  685. sale := models.Sale{}
  686. _err = s.rDB.Where("id = ?", request.SaleID).Find(&sale).Error
  687. if errors.Is(_err, gorm.ErrRecordNotFound) {
  688. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.NotFoundRecord, nil, err)
  689. return
  690. }
  691. token := models.Token{}
  692. _err = s.rDB.Where("id = ?", sale.TokenID).Find(&token).Error
  693. if errors.Is(_err, gorm.ErrRecordNotFound) {
  694. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.NotFoundRecord, nil, err)
  695. return
  696. }
  697. var firstOrder bool
  698. if sale.IsResale == 1 && (token.LastestCurrency.String != "") {
  699. firstOrder = false
  700. } else if sale.IsResale == 0 || (sale.IsResale == 1 && token.LastestCurrency.String == "") {
  701. firstOrder = true
  702. }
  703. collection := models.Collection{}
  704. _err = s.rDB.Where("id = ?", token.CollectionID).Find(&collection).Error
  705. if errors.Is(_err, gorm.ErrRecordNotFound) {
  706. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.NotFoundRecord, nil, err)
  707. return
  708. }
  709. setting := models.Setting{}
  710. _err = s.rDB.Find(&setting).Error
  711. if errors.Is(_err, gorm.ErrRecordNotFound) {
  712. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.NotFoundRecord, nil, err)
  713. return
  714. }
  715. var _official bool
  716. if collection.IsOfficial == 1 {
  717. _official = true
  718. } else {
  719. _official = false
  720. }
  721. //NOTE 자기가 판매하는 물품이 맞는건지 확인
  722. if wallet.Address != token.OwnerAddress {
  723. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, errors.New("no matching rights"))
  724. return
  725. }
  726. highestBid := models.BidLog{}
  727. if err := s.rDB.Where("sale_id = ? AND is_cancel = 0", request.SaleID).Order("price desc").Limit(1).Find(&highestBid).Error; err != nil {
  728. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  729. return
  730. }
  731. buyUser := models.UserWallet{}
  732. if err := s.rDB.Where("address = ?", highestBid.Address).Find(&buyUser).Error; err != nil {
  733. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  734. return
  735. }
  736. UserDepositList := []models.Deposit{}
  737. if err := s.rDB.Where("sale_id = ? AND status = 'deposit'", request.SaleID).Find(&UserDepositList).Error; err != nil {
  738. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  739. return
  740. }
  741. //NOTE x 사용 가능 금액 검증 (구매자의 정보를 가져와서 금액이 있는지 확인한다)
  742. if request.Currency == "eth" {
  743. _, availableBalance := helpers.GetSelectedBalance(s.rDB, buyUser.UserID, request.Currency, buyUser.Address)
  744. if (highestBid.Price + setting.GasDeposit) > availableBalance {
  745. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, errors.New("lack of holding balance"))
  746. return
  747. }
  748. } else {
  749. _, availableBalance := helpers.GetSelectedBalance(s.rDB, userID, request.Currency, buyUser.Address)
  750. if highestBid.Price > availableBalance {
  751. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, errors.New("lack of holding balance"))
  752. return
  753. }
  754. _, availableEthBalance := helpers.GetSelectedBalance(s.rDB, userID, "eth", buyUser.Address)
  755. if setting.GasDeposit > availableEthBalance {
  756. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, errors.New("lack of holding balance"))
  757. return
  758. }
  759. var allowanceAmount *big.Int
  760. var err error
  761. var _currency helpers.ContractType
  762. if request.Currency == "mf" {
  763. _currency = helpers.MetaFinance
  764. allowanceAmount, err = helpers.GetAllowance(helpers.MetaFinance, buyUser.Address)
  765. } else if request.Currency == "mr" {
  766. _currency = helpers.MetaRare
  767. allowanceAmount, err = helpers.GetAllowance(helpers.MetaRare, buyUser.Address)
  768. }
  769. if request.BidPrice > helpers.TypeCastingToFloat64(allowanceAmount) {
  770. _, _, _, err = helpers.ApproveForERC20(_currency, buyUser.PrivateKey, common.MaxBig256)
  771. if err != nil {
  772. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  773. return
  774. }
  775. }
  776. }
  777. tx := s.mDB.Begin()
  778. defer common.DBTransaction(tx)
  779. if err := tx.Model(&sale).Update("status", "end").Error; err != nil {
  780. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  781. tx.Rollback()
  782. return
  783. }
  784. if err := tx.Model(&token).Updates(models.Token{OwnerAddress: buyUser.Address,
  785. LastestPrice: null.FloatFrom(highestBid.Price),
  786. LastestCurrency: null.StringFrom(request.Currency)}).Error; err != nil {
  787. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  788. tx.Rollback()
  789. return
  790. }
  791. //FIXME a 해당 경매에 묶여있는 모든 deposit을 제거해줘야 한다!
  792. for idx, _ := range UserDepositList {
  793. if err := tx.Model(&UserDepositList[idx]).Updates(models.Deposit{Status: "withdrawal", DeletedAt: null.TimeFrom(time.Now())}).Error; err != nil {
  794. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  795. tx.Rollback()
  796. return
  797. }
  798. }
  799. /*
  800. NOTE x
  801. sale 의 hashdata, signature 를 만들어주고 업데이트, 이후 바로 동일하게 다시 만들어서 검증
  802. */
  803. _v := common.MakeHashData{
  804. OwnerAddress: wallet.Address,
  805. CollectionAddress: collection.ContractAddress,
  806. TokenType: token.Type,
  807. TokenID: int64(token.ID),
  808. Currency: sale.Currency,
  809. Price: highestBid.Price,
  810. Index: int64(token.Index.Int64),
  811. TotalIndex: int64(token.TotalCount.Int64),
  812. CreationTax: int64(token.Royalties * 100),
  813. PrevTreasuryTax: int64(sale.TreasuryTax * 100),
  814. TreasuryAddress: setting.TreasuryAddress,
  815. }
  816. _vv, err := common.MakeSining(tx, _v)
  817. if err != nil {
  818. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  819. tx.Rollback()
  820. return
  821. }
  822. _sigData, _hashData, err := helpers.Signing(_vv, wallet.PrivateKey)
  823. if err != nil {
  824. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  825. tx.Rollback()
  826. return
  827. }
  828. if err := tx.Model(&sale).Updates(&models.Sale{HashData: hex.EncodeToString(_hashData), Signature: hex.EncodeToString(_sigData)}).Error; err != nil {
  829. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.InvalidParameterValue, nil, err)
  830. tx.Rollback()
  831. return
  832. }
  833. var txHash *types.Transaction
  834. _hash, _ := hex.DecodeString(sale.HashData)
  835. _sig, _ := hex.DecodeString(sale.Signature)
  836. var _hashedData [32]byte
  837. var _signature [65]byte
  838. copy(_hashedData[:], _hash)
  839. copy(_signature[:], _sig)
  840. if sale.IsResale == 1 && !firstOrder {
  841. if token.Type == "erc721" {
  842. _txHash, _, err := helpers.Order721OnlyTransfer(_vv, _hashedData, buyUser.PrivateKey, _signature)
  843. if err != nil {
  844. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  845. tx.Rollback()
  846. return
  847. }
  848. txHash = _txHash
  849. } else if token.Type == "erc1155" {
  850. _txHash, _, err := helpers.Order1155OnlyTransfer(_vv, _hashedData, buyUser.PrivateKey, _signature)
  851. if err != nil {
  852. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  853. tx.Rollback()
  854. return
  855. }
  856. txHash = _txHash
  857. }
  858. } else if sale.IsResale == 0 || firstOrder {
  859. if token.Type == "erc721" {
  860. _txHash, _, err := helpers.Order721WithMinting(_vv, _hashedData, buyUser.PrivateKey, _signature, _official)
  861. if err != nil {
  862. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  863. tx.Rollback()
  864. return
  865. }
  866. txHash = _txHash
  867. } else if token.Type == "erc1155" {
  868. _txHash, _, err := helpers.Order1155WithMinting(_vv, _hashedData, buyUser.PrivateKey, _signature, _official)
  869. if err != nil {
  870. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  871. tx.Rollback()
  872. return
  873. }
  874. txHash = _txHash
  875. }
  876. //NOTE x 메타데이터 넣어주는 작업 ( 최초 한번만 넣어 준다 )
  877. err = util.MakeMetaData(s.metaAwsConf, tx, sale.TokenID, txHash.Hash().String(), token.Name, token.Description, token.AssetsImageURL)
  878. if err != nil {
  879. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.GoContextError, nil, err)
  880. tx.Rollback()
  881. return
  882. }
  883. } else {
  884. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.GoContextError, nil, err)
  885. tx.Rollback()
  886. return
  887. }
  888. if err := tx.Commit().Error; err != nil {
  889. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  890. tx.Rollback()
  891. return
  892. }
  893. gerror.IntegratedResponseToRequest(c, http.StatusOK, gerror.OK, txHash.Hash().String(), nil)
  894. return
  895. }
  896. // registerResale godoc
  897. // @Summary create resale
  898. // @Description NFT 구입 후 재등록 API
  899. // @Schemes
  900. // @security ApiKeyAuth
  901. // @Tags sale
  902. // @Accept json
  903. // @Produce json
  904. // @Param RegisterResaleData body RegisterResaleData true "body struct"
  905. // @Success 200 {string} OK
  906. // @Router /sale/resale [post]
  907. func (s SaleV1Router) registerResale(c *gin.Context) {
  908. userID, err := gauth.GetCurrentUserIDToInt64(c)
  909. if err != nil || userID == 0 {
  910. gerror.IntegratedResponseToRequest(c, http.StatusUnauthorized, gerror.Unauthorized, nil, err)
  911. return
  912. }
  913. request := RegisterResaleData{}
  914. if err := c.ShouldBindJSON(&request); err != nil {
  915. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, err)
  916. return
  917. }
  918. wallet := models.UserWallet{}
  919. _err := s.rDB.Where("user_id = ?", userID).Find(&wallet).Error
  920. if errors.Is(_err, gorm.ErrRecordNotFound) {
  921. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, _err)
  922. return
  923. }
  924. token := models.Token{}
  925. _err = s.rDB.Where("id = ?", request.TokenID).Find(&token).Error
  926. if errors.Is(_err, gorm.ErrRecordNotFound) {
  927. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, _err)
  928. return
  929. }
  930. if wallet.Address != token.OwnerAddress {
  931. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, c, errors.New("no maching rights"))
  932. }
  933. collection := models.Collection{}
  934. _err = s.rDB.Where("id = ?", token.CollectionID).Find(&collection).Error
  935. if errors.Is(_err, gorm.ErrRecordNotFound) {
  936. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, _err)
  937. return
  938. }
  939. setting := models.Setting{}
  940. _err = s.rDB.Find(&setting).Error
  941. if errors.Is(_err, gorm.ErrRecordNotFound) {
  942. gerror.IntegratedResponseToRequest(c, http.StatusBadRequest, gerror.InvalidParameterValue, nil, _err)
  943. return
  944. }
  945. sale := models.Sale{
  946. TokenID: request.TokenID,
  947. IsResale: 1,
  948. SaleType: request.SaleType,
  949. UID: common.GenerateSaleUID(s.mDB, "sale_"),
  950. Currency: request.Currency,
  951. Status: "ongoing",
  952. TreasuryTax: setting.Commission,
  953. }
  954. if request.SaleType == "fixed" {
  955. sale.Price = null.FloatFrom(request.Price)
  956. _v := common.MakeHashData{
  957. OwnerAddress: wallet.Address,
  958. CollectionAddress: collection.ContractAddress,
  959. TokenType: token.Type,
  960. TokenID: int64(token.ID),
  961. Currency: sale.Currency,
  962. Price: request.Price,
  963. Index: int64(token.Index.Int64),
  964. TotalIndex: int64(token.TotalCount.Int64),
  965. CreationTax: int64(token.Royalties * 100),
  966. PrevTreasuryTax: int64(setting.Commission * 100),
  967. TreasuryAddress: setting.TreasuryAddress,
  968. }
  969. _vv, err := common.MakeSining(s.rDB, _v)
  970. if err != nil {
  971. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  972. return
  973. }
  974. _signature, _hashData, err := helpers.Signing(_vv, wallet.PrivateKey)
  975. if err != nil {
  976. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  977. return
  978. }
  979. sale.HashData = hex.EncodeToString(_hashData)
  980. sale.Signature = hex.EncodeToString(_signature)
  981. } else if request.SaleType == "time" {
  982. sale.StartPrice = null.FloatFrom(request.StartPrice)
  983. sale.StartAt = null.TimeFrom(request.StartAt)
  984. sale.EndAt = null.TimeFrom(request.EndAt)
  985. }
  986. if err := s.mDB.Save(&sale).Error; err != nil {
  987. gerror.IntegratedResponseToRequest(c, http.StatusInternalServerError, gerror.MysqlSaveError, nil, err)
  988. return
  989. }
  990. gerror.IntegratedResponseToRequest(c, http.StatusOK, gerror.OK, sale, nil)
  991. }
  992. func getQuery(c *gin.Context, name string, def interface{}) (r interface{}) {
  993. g, has := c.GetQuery(name)
  994. if has {
  995. r = g
  996. } else {
  997. r = def
  998. }
  999. return
  1000. }
  1001. func (s SaleV1Router) rankningSale(c *gin.Context) {
  1002. ranking := []common.TopSales{}
  1003. start, _ := strconv.Atoi(fmt.Sprintf("%v", getQuery(c, "start", 0)))
  1004. end, _ := strconv.Atoi(fmt.Sprintf("%v", getQuery(c, "end", 0)))
  1005. limited, _ := strconv.Atoi(fmt.Sprintf("%v", getQuery(c, "limit", 20)))
  1006. if start == 0 || end == 0 {
  1007. ranking = view.GetRankingSaleByArtist(s.rDB, limited)
  1008. } else {
  1009. startdate := time.UnixMilli(int64(start))
  1010. endDate := time.UnixMilli(int64(end))
  1011. ranking = view.GetRankingSaleByArtist(s.rDB, limited, startdate, endDate)
  1012. }
  1013. gerror.IntegratedResponseToRequest(c, http.StatusOK, gerror.OK, ranking, nil)
  1014. }