This commit is contained in:
yangduo 2024-12-24 13:22:22 +08:00
parent 2ca0d9e5e7
commit 04a2e716fe
94 changed files with 835 additions and 55846 deletions

View File

@ -1,12 +0,0 @@
[
{
"currency_name": "USDC",
"contract_name": "BEUSDC",
"currency_decimal": 6
},
{
"currency_name": "USDT",
"contract_name": "BEUSDT",
"currency_decimal": 6
}
]

View File

@ -1,7 +0,0 @@
[
{
"currency_name": "USDC",
"contract_name": "BEUSDC",
"currency_decimal": 6
}
]

View File

@ -1,12 +0,0 @@
[
{
"currency_name": "USDC",
"contract_name": "BEUSDC",
"currency_decimal": 6
},
{
"currency_name": "USDT",
"contract_name": "BEUSDT",
"currency_decimal": 6
}
]

View File

@ -1,12 +0,0 @@
[
{
"currency_name": "USDC",
"contract_name": "BEUSDC",
"currency_decimal": 18
},
{
"currency_name": "USDT",
"contract_name": "BEUSDT",
"currency_decimal": 18
}
]

View File

@ -0,0 +1,8 @@
{
"host": "127.0.0.1",
"port": 6379,
"passwd": "",
"database": 0,
"max_open_conns": 1,
"max_idle_conns": 1
}

View File

@ -1 +0,0 @@
../../backtask/config/nets/

View File

@ -1 +0,0 @@
../../backtask/config/nets.json

View File

@ -1,9 +0,0 @@
{
"host": "login-test.kingsome.cn",
"port": 3306,
"user": "root",
"passwd": "keji178",
"database": "bcnft_dev",
"max_open_conns": 1,
"max_idle_conns": 1
}

View File

@ -1,5 +0,0 @@
[
{
"url": "http://127.0.0.1:7682"
}
]

View File

@ -1,5 +0,0 @@
[
{
"url": "http://127.0.0.1:7672"
}
]

View File

@ -0,0 +1,50 @@
[
{
"id": 100001,
"name": "60钻石",
"icon": "10_101",
"type": 1,
"price": 6,
"count": 60
},
{
"id": 100002,
"name": "300钻石",
"icon": "10_102",
"type": 1,
"price": 30,
"count": 300
},
{
"id": 100003,
"name": "680钻石",
"icon": "10_103",
"type": 1,
"price": 68,
"count": 680
},
{
"id": 100004,
"name": "1280钻石",
"icon": "10_104",
"type": 1,
"price": 128,
"count": 1280
},
{
"id": 100005,
"name": "3280钻石",
"icon": "10_105",
"type": 1,
"price": 328,
"count": 3280
},
{
"id": 100006,
"name": "6480钻石",
"icon": "10_106",
"type": 1,
"price": 648,
"count": 6480
}
]

View File

@ -0,0 +1,50 @@
[
{
"id": 1,
"name": "60钻石",
"icon": "10_101",
"type": 1,
"price": 6,
"count": 60
},
{
"id": 2,
"name": "300钻石",
"icon": "10_102",
"type": 1,
"price": 30,
"count": 300
},
{
"id": 3,
"name": "680钻石",
"icon": "10_103",
"type": 1,
"price": 68,
"count": 680
},
{
"id": 4,
"name": "1280钻石",
"icon": "10_104",
"type": 1,
"price": 128,
"count": 1280
},
{
"id": 5,
"name": "3280钻石",
"icon": "10_105",
"type": 1,
"price": 328,
"count": 3280
},
{
"id": 6,
"name": "6480钻石",
"icon": "10_106",
"type": 1,
"price": 648,
"count": 6480
}
]

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,42 +0,0 @@
[
{
"id": 1001,
"diamond": 600,
"present_diamond": 66,
"price": 6,
"can_email_buy": 0,
"max_buy_times": 1
},
{
"id": 1002,
"diamond": 6800,
"present_diamond": 1200,
"price": 68,
"can_email_buy": 0,
"max_buy_times": 1
},
{
"id": 1003,
"diamond": 16800,
"present_diamond": 3200,
"price": 168,
"can_email_buy": 0,
"max_buy_times": 1
},
{
"id": 1004,
"diamond": 26800,
"present_diamond": 6200,
"price": 268,
"can_email_buy": 0,
"max_buy_times": 1
},
{
"id": 1006,
"diamond": 100,
"present_diamond": 0,
"price": 1,
"can_email_buy": 1,
"max_buy_times": 9999
}
]

View File

@ -1 +0,0 @@
../../light_backtask/res/stakingVip@stakingVip.json

View File

@ -0,0 +1,16 @@
[
{
"gameid": "1004",
"appid": "wx1e89277247304160",
"appkey": "CBP5uFcZP0S2PlcgkBTHxfZEXJft9wMK",
"zoneid": "1",
"offerid": "1450310463"
},
{
"gameid": "2004",
"appid": "wx327f44630205dcd2",
"appkey": "CrIjLw1wiExEnNBVqBQqWGMy0yToREC7",
"zoneid": "1",
"offerid": "1450318181"
}
]

View File

@ -1,61 +0,0 @@
package activity
import (
"f5"
"fmt"
"main/constant"
"main/service"
"q5"
"strings"
"github.com/gin-gonic/gin"
)
type BitGetApi struct {
}
func (this *BitGetApi) NewUserMission(c *gin.Context) {
email := strings.ToLower(c.DefaultQuery("email", ""))
rspObj := struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
CP string `json:"contributionPoint"`
Missions []struct {
MissionId int32 `json:"mission_id"`
Current int32 `json:"current"`
Target int32 `json:"target"`
} `json:"missions"`
}{}
q5.NewSlice(&rspObj.Missions, 0, 10)
p := q5.NewSliceElement(&rspObj.Missions)
p.MissionId = 1
p.Target = 5
if email != "" {
mycp, accountid, _ := service.Contribution.GetEmailContributionAccountid(email)
rspObj.CP = fmt.Sprintf("%.2f", mycp)
if accountid != "" {
sql := `SELECT count(idx) FROM t_battle_settlement_single WHERE idx > 0 AND account_id = ?`
f5.GetGoStyleDb().RawQuery(
constant.GAME_DB,
sql,
[]string{accountid},
func(err error, ds *f5.DataSet) {
if err != nil {
return
}
if ds.Next() {
p.Current = q5.SafeToInt32(ds.GetByIndex(0))
if p.Current > p.Target {
p.Current = p.Target
}
}
})
}
}
c.JSON(200, rspObj)
}

View File

@ -1,148 +0,0 @@
package activity
import (
"f5"
"fmt"
"main/constant"
"main/service"
"q5"
"strings"
"github.com/gin-gonic/gin"
)
type ContriApi struct {
}
func (cta *ContriApi) HistoryQuery(c *gin.Context) {
account := strings.ToLower(c.Param("account_address"))
if account == "" {
f5.RspErr(c, 2, "empty account")
return
}
type info struct {
Type int32 `json:"type"`
Time int32 `json:"give_time"`
CP string `json:"contribution_point"`
}
rspObj := struct {
Errcode int32 `json:"errcode"`
Msg int32 `json:"errmsg"`
CP string `json:"contributionPoint"`
Rows []*info `json:"rows"`
}{}
mycp, _ := service.Contribution.GetAddressContribution(account, false)
rspObj.CP = fmt.Sprintf("%.2f", mycp)
q5.NewSlice(&rspObj.Rows, 0, 10)
if mycp > 0.000001 {
sql := `SELECT * FROM t_staking_daily_settlement WHERE idx > 0 and account_address = ?`
f5.GetGoStyleDb().RawQuery(
constant.BCNFT_DB,
sql,
[]string{account},
func(err error, ds *f5.DataSet) {
if err != nil {
return
}
for ds.Next() {
p := new(info)
p.Type = 1
p.Time = q5.SafeToInt32(ds.GetByName("settle_date"))
p.CP = fmt.Sprintf("%.2f", q5.ToFloat64(ds.GetByName("contribution")))
q5.AppendSlice(&rspObj.Rows, p)
}
})
{
loweremail, accountid := service.Contribution.GetEmailAccountId(account)
if accountid != "" {
sql = `SELECT * FROM t_contribution_history WHERE idx > 0 AND account_id = ?`
f5.GetGoStyleDb().RawQuery(
constant.GAME_DB,
sql,
[]string{accountid},
func(err error, ds *f5.DataSet) {
if err != nil {
return
}
for ds.Next() {
p := new(info)
p.Type = 2
p.Time = q5.SafeToInt32(ds.GetByName("createtime"))
p.CP = fmt.Sprintf("%.2f", q5.ToFloat64(ds.GetByName("contribution")))
q5.AppendSlice(&rspObj.Rows, p)
}
})
}
sql = `SELECT * FROM t_recharge_return_contribution WHERE idx > 0 AND user_identity IN (?`
params := []string{account}
if loweremail != "" {
sql += ", ?"
params = append(params, loweremail)
}
sql += ")"
f5.GetGoStyleDb().RawQuery(
constant.BCNFT_DB,
sql,
params,
func(err error, ds *f5.DataSet) {
if err != nil {
return
}
for ds.Next() {
p := new(info)
p.Type = 3
p.Time = q5.SafeToInt32(ds.GetByName("pay_time"))
p.CP = fmt.Sprintf("%.2f", q5.ToFloat64(ds.GetByName("return_contribution")))
q5.AppendSlice(&rspObj.Rows, p)
}
})
}
}
q5.Sort(rspObj.Rows, func(a *info, b *info) bool {
return a.Time > b.Time
})
c.JSON(200, rspObj)
}
func (cta *ContriApi) CECQuery(c *gin.Context) {
account := strings.ToLower(c.Param("account_address"))
if account == "" {
f5.RspErr(c, 2, "empty account")
return
}
rspObj := struct {
Errcode int32 `json:"errcode"`
Msg int32 `json:"errmsg"`
CP string `json:"contributionPoint"`
Info struct {
MyCP string `json:"my_contribution"`
GCP string `json:"global_contribution"`
GCEC int64 `json:"total_cec_pool"`
MyCEC int64 `json:"my_expected_cec"`
} `json:"info"`
}{}
mycp, _ := service.Contribution.GetAddressContribution(account, false)
totalgcp, _ := service.Contribution.GetGlobalContribution(false)
rspObj.CP = fmt.Sprintf("%.2f", mycp)
rspObj.Info.MyCP = rspObj.CP
rspObj.Info.GCP = fmt.Sprintf("%.2f", totalgcp)
rspObj.Info.GCEC = 500000
rspObj.Info.MyCEC = q5.SafeToInt64(float64(rspObj.Info.GCEC) * (mycp) / totalgcp)
c.JSON(200, rspObj)
}

View File

@ -1,6 +0,0 @@
package activity
type ApiGroup struct {
BitGetApi
ContriApi
}

View File

@ -1,105 +0,0 @@
package asset
import (
"f5"
"fmt"
"jccommon"
"main/common"
"main/constant"
. "main/global"
"main/mt"
"q5"
"strings"
"github.com/gin-gonic/gin"
)
type AssetApi struct {
}
/*
filterType: 0:全部 1:已上架 2:未上架 3:质押中
*/
func (this *AssetApi) AccountAsset(c *gin.Context) {
c.JSON(200, nil)
}
func (this *AssetApi) Listing(c *gin.Context) {
pageSize := q5.AdjustRangeValue(q5.ToInt32(c.DefaultQuery("page_size", "")), 1, 20)
cursor := q5.ToInt64(c.DefaultQuery("cursor", ""))
netId := q5.ToInt64(c.Param("net_id"))
accountAddress := strings.ToLower(c.Param("account_address"))
searchName := c.DefaultQuery("search_name", "")
sql := fmt.Sprintf(`
SELECT * FROM t_order WHERE net_id = %d AND status = "%s" AND seller_address=?`,
netId,
jccommon.ORDER_STATUS_ACTIVE)
params := []string{accountAddress}
subFilters := []f5.DbQueryFilter{}
{
itemIds := map[int32]int32{}
if searchName != "" {
mt.Table.Item.Search(searchName, itemIds)
}
if len(itemIds) > 0 {
inSub := `item_id IN (`
i := 0
for key, _ := range itemIds {
if i == 0 {
inSub += q5.ToString(key)
} else {
inSub += "," + q5.ToString(key)
}
i += 1
}
inSub += ")"
q5.AppendSlice(&subFilters, f5.GetDbFilter().Custom(inSub).And())
}
}
orderBy := ""
rspObj := struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
Page common.StreamPagination `json:"page"`
Rows []struct {
Event interface{} `json:"event"`
Nft interface{} `json:"nft"`
InShopCart int32 `json:"in_shopcart"`
Price string `json:"price"`
} `json:"rows"`
}{}
nfts := []*common.NftDto{}
f5.GetGoStyleDb().StreamPageQuery(
constant.BCNFT_DB,
pageSize,
cursor,
sql,
params,
f5.GetDbFilter().Comp(subFilters...),
orderBy,
func(err error, pagination *f5.StreamPagination) {
rspObj.Page.FillPage(pagination)
},
func(ds *f5.DataSet) {
p := new(common.NftDto)
p.NetId = q5.ToInt32(ds.GetByName("net_id"))
p.ContractAddress = ds.GetByName("contract_address")
p.TokenId = ds.GetByName("token_id")
q5.DecodeJson(ds.GetByName("event_data"), &p.Payload)
q5.AppendSlice(&nfts, p)
})
GetCacheMgr().GetNfts(nfts)
{
for _, val := range nfts {
p := q5.NewSliceElement(&rspObj.Rows)
p.Event = val.Payload
p.Nft = val.NftCache.GetJsonData()
/*
if cartDb != nil && cartDb.GetGoods(val.NetId, val.ContractAddress, val.TokenId) != nil{
p.InShopCart = 1
}*/
}
}
c.JSON(200, rspObj)
}

View File

@ -1,5 +0,0 @@
package asset
type ApiGroup struct {
AssetApi
}

View File

@ -1,33 +1,11 @@
package v1
import (
"main/api/v1/activity"
"main/api/v1/asset"
"main/api/v1/event"
"main/api/v1/game_switch"
"main/api/v1/gold_bullion"
"main/api/v1/hero"
"main/api/v1/ingame"
"main/api/v1/market"
"main/api/v1/recharge"
"main/api/v1/shopcart"
"main/api/v1/user"
"main/api/v1/vip"
)
type ApiGroup struct {
MarketApiGroup market.ApiGroup
AssetApiGroup asset.ApiGroup
HeroApiGroup hero.ApiGroup
GoldBullionApiGroup gold_bullion.ApiGroup
ShopCartApiGroup shopcart.ApiGroup
InGameApiGroup ingame.ApiGroup
UserApiGroup user.ApiGroup
ActivityApiGroup activity.ApiGroup
EventApiGroup event.ApiGroup
RechargeApiGroup recharge.ApiGroup
SwitchApiGroup game_switch.ApiGroup
VIPApiGroup vip.ApiGroup
}
var ApiGroupApp = new(ApiGroup)

View File

@ -1,5 +0,0 @@
package event
type ApiGroup struct {
EventApi
}

View File

@ -1,198 +0,0 @@
package event
import (
"f5"
"fmt"
"main/common"
"main/constant"
. "main/global"
"main/mt"
"net/http"
"q5"
"strings"
"github.com/gin-gonic/gin"
)
type EventApi struct {
}
var EVENTYPE = map[string]int32{
"mint": 1,
"lock": 2,
"unlock": 3,
}
func (ea *EventApi) TxQuery(c *gin.Context) {
netid := q5.SafeToInt32(c.Param("net_id"))
txhash := strings.ToLower(c.Param("txhash"))
rspObj := struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
Confirmed int32 `json:"confirmed"`
}{}
{
sql := fmt.Sprintf(`SELECT idx FROM t_blockchain_event WHERE idx > 0 AND txhash = ? AND net_id = %d`, netid)
params := []string{
txhash,
}
f5.GetGoStyleDb().RawQuery(
constant.PAY_DB,
sql,
params,
func(err error, ds *f5.DataSet) {
if err != nil {
c.JSON(200, rspObj)
return
}
if ds != nil {
rspObj.Confirmed = 1
}
c.JSON(200, rspObj)
})
}
}
func (ea *EventApi) ActivityQuery(c *gin.Context) {
account := strings.ToLower(c.Param("account_address"))
reqJson := struct {
PageSize interface{} `json:"page_size"`
Cursor interface{} `json:"cursor"`
Search struct {
Name string `json:"name"`
} `json:"search"`
Filter struct {
ItemIds []interface{} `json:"item_ids"`
} `json:"filter"`
Sort struct {
Fields []struct {
Name string `json:"name"`
Type interface{} `json:"type"`
} `json:"fields"`
} `json:"sort"`
}{}
if err := c.ShouldBindJSON(&reqJson); err != nil {
c.JSON(http.StatusOK, gin.H{
"errcode": 1,
"errmsg": err.Error(),
})
return
}
pageSize := q5.AdjustRangeValue(q5.SafeToInt32(reqJson.PageSize), 1, 20)
cursor := q5.SafeToInt64(reqJson.Cursor)
sql := fmt.Sprintf(`
SELECT * FROM t_chain_activity
WHERE idx > %d AND (sender_address = ? OR to_address = ?) `,
cursor)
params := []string{account, account}
subFilters := []f5.DbQueryFilter{}
{
itemIds := map[int32]int32{}
if reqJson.Search.Name != "" {
mt.Table.Item.Search(reqJson.Search.Name, itemIds)
}
for _, val := range reqJson.Filter.ItemIds {
itemId := q5.SafeToInt32(val)
itemIds[itemId] = 1
}
if len(itemIds) > 0 {
inSub := `item_id IN (`
i := 0
for key, _ := range itemIds {
if i == 0 {
inSub += q5.ToString(key)
} else {
inSub += "," + q5.ToString(key)
}
i += 1
}
inSub += ")"
q5.AppendSlice(&subFilters, f5.GetDbFilter().Custom(inSub).And())
}
}
orderBy := " ORDER BY createtime DESC "
// {
// for _, val := range reqJson.Sort.Fields {
// if val.Name == "price" && orderBy == "" {
// t := q5.SafeToInt32(val.Type)
// if t < 0 {
// orderBy = " ORDER BY price_len DESC, price DESC"
// } else {
// orderBy = " ORDER BY price_len ASC, price ASC"
// }
// }
// }
// }
rspObj := struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
Page common.StreamPagination `json:"page"`
Rows []struct {
Nft interface{} `json:"nft"`
Type int32 `json:"type"`
From string `json:"from"`
To string `json:"to"`
Date int32 `json:"date"`
} `json:"rows"`
}{}
q5.NewSlice(&rspObj.Rows, 0, 10)
nfts := []*common.NftDto{}
f5.GetGoStyleDb().StreamPageQuery(
constant.PAY_DB,
pageSize,
cursor,
sql,
params,
f5.GetDbFilter().Comp(subFilters...),
orderBy,
func(err error, pagination *f5.StreamPagination) {
rspObj.Page.FillPage(pagination)
},
func(ds *f5.DataSet) {
p := new(common.NftDto)
p.NetId = q5.ToInt32(ds.GetByName("net_id"))
p.ContractAddress = ds.GetByName("nft_contract_address")
p.TokenId = ds.GetByName("token_id")
p.Payload = map[string]string{}
if ds.GetByName("is_mint") != "0" {
p.Payload.(map[string]string)["type"] = "mint"
} else {
p.Payload.(map[string]string)["type"] = ds.GetByName("event_name")
}
p.Payload.(map[string]string)["to"] = ds.GetByName("to_address")
p.Payload.(map[string]string)["from"] = ds.GetByName("sender_address")
p.Payload.(map[string]string)["date"] = ds.GetByName("createtime")
q5.AppendSlice(&nfts, p)
})
GetCacheMgr().GetNfts(nfts)
{
for _, val := range nfts {
p := q5.NewSliceElement(&rspObj.Rows)
jsonData := val.NftCache.GetJsonData()
if jsonData != nil {
if v, ok := jsonData.(map[string]interface{}); ok {
v := q5.MapClone(v)
tmpmap := val.Payload.(map[string]string)
p.Type = EVENTYPE[strings.ToLower(tmpmap["type"])]
p.To = tmpmap["to"]
p.From = tmpmap["from"]
p.Date = q5.SafeToInt32(tmpmap["date"])
jsonData = v
}
}
p.Nft = jsonData
}
}
c.JSON(200, rspObj)
}

View File

@ -1,5 +0,0 @@
package game_switch
type ApiGroup struct {
GameSwitchApi
}

View File

@ -1,23 +0,0 @@
package game_switch
import (
"main/service"
"net/http"
"github.com/gin-gonic/gin"
)
type GameSwitchApi struct {
data map[string]int32
time int64
}
func (this *GameSwitchApi) List(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"code": 0,
"message": "获取成功",
"contributionPoint": "",
"data": service.GameSwitches.GetSwitchList(),
})
}

View File

@ -1,5 +0,0 @@
package gold_bullion
type ApiGroup struct {
GoldBullionApi
}

View File

@ -1,9 +0,0 @@
package gold_bullion
import (
)
type GoldBullionApi struct {
}

View File

@ -1,5 +0,0 @@
package hero
type ApiGroup struct {
HeroApi
}

View File

@ -1,8 +0,0 @@
package hero
import (
)
type HeroApi struct {
}

View File

@ -1,8 +1,11 @@
package ingame
import (
"encoding/json"
"f5"
"main/constant"
"main/model"
"main/service"
"q5"
"strings"
@ -27,13 +30,7 @@ func (this *InGameApi) PreOrder(c *gin.Context) {
order.AccountId = reqJson.AccountId
order.OrderId = q5.ToString(f5.GetApp().NewLockNodeUuid())
order.ItemId = reqJson.GoodsId
order.IP = c.Request.Header.Get("X-Real-Ip")
if order.IP == "" {
order.IP = strings.Split(c.Request.Header.Get("X-Forwarded-For"), ",")[0]
}
if order.IP == "" {
order.IP = c.Request.RemoteAddr
}
order.IP = this.getIP(c)
order.CreateTime = nowTime
order.ModifyTime = nowTime
@ -76,6 +73,26 @@ func (this *InGameApi) OrderInfo(c *gin.Context) {
return
}
strs := strings.Split(reqJson.AccountId, "_")
if len(strs) < 3 {
f5.RspErr(c, 401, "params error1")
return
}
rediskey := "ls:accountid:" + reqJson.AccountId
str, err := service.Redis.Get(constant.LOGIN_REDIS, rediskey)
if err != nil {
f5.RspErr(c, 402, "invalid session")
return
}
data := map[string]interface{}{}
if json.Unmarshal([]byte(str), &data) != nil {
f5.RspErr(c, 402, "invalid session 1")
return
}
status := orderModel.Status
rspObj := struct {
ErrorCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
@ -83,8 +100,56 @@ func (this *InGameApi) OrderInfo(c *gin.Context) {
GoodsId int32 `json:"goods_id"`
Status int32 `json:"status"`
}{}
for status == 0 {
gameid := q5.SafeToInt64(strs[1])
openid := strs[2]
sessionkey := q5.SafeToString(data["session_key"])
userip := this.getIP(c)
balance, errcode, err := service.Wxpay.QueryBalance(openid, gameid, userip, sessionkey)
if err != nil {
f5.RspErr(c, 500, "system busy")
return
}
if errcode == constant.WX_ERRCODE_OK {
count, err := service.Wxpay.GetGoodsCount(gameid, int64(orderModel.ItemId))
if err != nil {
f5.RspErr(c, 401, "goods error")
return
}
if balance < count {
break
}
errcode = service.Wxpay.QueryPay(openid, gameid, userip, sessionkey, int32(count), orderModel.OrderId)
if errcode == constant.WX_ERRCODE_OK {
status = 1
orderModel.Status = 2
orderModel.UpdateFields([]string{"status"})
}
}
if errcode == constant.WX_ERRCODE_SESSIONERR || errcode == constant.WX_ERRCODE_SIGERR {
rspObj.ErrorCode = 402
rspObj.ErrMsg = "session overtime"
}
}
rspObj.OrderId = orderModel.OrderId
rspObj.GoodsId = orderModel.ItemId
rspObj.Status = orderModel.Status
rspObj.Status = status
c.JSON(200, rspObj)
}
func (this *InGameApi) getIP(c *gin.Context) (ip string) {
ip = c.Request.Header.Get("X-Real-Ip")
if ip == "" {
ip = strings.Split(c.Request.Header.Get("X-Forwarded-For"), ",")[0]
}
if ip == "" {
ip = c.Request.RemoteAddr
}
return ip
}

View File

@ -1,5 +0,0 @@
package market
type ApiGroup struct {
MarketApi
}

View File

@ -1,739 +0,0 @@
package market
import (
"f5"
"fmt"
"jccommon"
"main/common"
"main/constant"
. "main/global"
"main/service"
"main/mt"
"net/http"
"q5"
"strings"
"github.com/gin-gonic/gin"
)
type goodsDto struct {
Event interface{} `json:"event"`
Nft interface{} `json:"nft"`
InShopCart int32 `json:"in_shopcart"`
}
type MarketApi struct {
}
func (this *MarketApi) ProductList1(c *gin.Context) {
openId := c.MustGet("open_id").(string)
cartDb := service.GetShopCartByOpenId(openId)
netId := q5.ToInt64(c.Param("net_id"))
reqJson := struct {
PageSize interface{} `json:"page_size"`
Cursor interface{} `json:"cursor"`
Search struct {
Name string `json:"name"`
} `json:"search"`
Filter struct {
PriceMin interface{} `json:"price_min"`
PriceMax interface{} `json:"price_max"`
ItemIds []interface{} `json:"item_ids"`
HeroRanks []interface{} `json:"hero_ranks"`
} `json:"filter"`
Sort struct {
Fields [] struct {
Name string `json:"name"`
Type interface{} `json:"type"`
} `json:"fields"`
} `json:"sort"`
}{}
if err := c.ShouldBindJSON(&reqJson); err != nil {
c.JSON(http.StatusOK, gin.H{
"code": 1,
"message": err.Error(),
})
return
}
pageSize := q5.AdjustRangeValue(q5.SafeToInt32(reqJson.PageSize), 1, 20)
cursor := q5.SafeToInt64(reqJson.Cursor)
sql := fmt.Sprintf(`
SELECT * FROM t_order A WHERE idx > %d AND net_id = %d AND status="%s"
`,
cursor, netId, jccommon.ORDER_STATUS_ACTIVE)
/*
if f5.IsTestEnv() {
sql = fmt.Sprintf(`
SELECT * FROM t_order A WHERE idx > %d AND net_id = %d
`,
cursor, netId)
}*/
orderBy := ""
{
for _, val := range reqJson.Sort.Fields {
if val.Name == "price" && orderBy == "" {
t := q5.SafeToInt32(val.Type)
if t < 0 {
orderBy = " ORDER BY price_len DESC, price DESC"
} else {
orderBy = " ORDER BY price_len ASC, price ASC"
}
}
}
}
subFilters := []f5.DbQueryFilter{}
{
priceMin := q5.SafeToString(reqJson.Filter.PriceMin)
priceMax := q5.SafeToString(reqJson.Filter.PriceMax)
if !q5.IsPureNumber(priceMin) {
priceMin = ""
}
if !q5.IsPureNumber(priceMax) {
priceMax = ""
}
if priceMin != "" && priceMax != "" {
q5.AppendSlice(&subFilters, f5.GetDbFilter().Custom(
fmt.Sprintf(`LENGTH(price) >= LENGTH('%s') AND price >= '%s' AND
LENGTH(price) <= LENGTH('%s') AND price <= '%s'`,
priceMin,
priceMin,
priceMax,
priceMax)).And())
} else if priceMin != "" {
q5.AppendSlice(&subFilters, f5.GetDbFilter().Custom(
fmt.Sprintf(`LENGTH(price) >= LENGTH('%s') AND price >= '%s'`,
priceMin,
priceMin)).And())
} else if priceMax != "" {
q5.AppendSlice(&subFilters, f5.GetDbFilter().Custom(
fmt.Sprintf(`LENGTH(price) <= LENGTH('%s') AND price <= '%s'`,
priceMax,
priceMax)).And())
}
}
{
itemIds := map[int32]int32{}
if reqJson.Search.Name != "" {
mt.Table.Item.Search(reqJson.Search.Name, itemIds)
}
for _, val := range(reqJson.Filter.ItemIds) {
itemId := q5.SafeToInt32(val)
itemIds[itemId] = 1
}
if len(itemIds) > 0 {
inSub := `item_id IN (`
i := 0
for key, _ := range(itemIds) {
if i == 0 {
inSub += q5.ToString(key)
} else {
inSub += "," + q5.ToString(key)
}
i += 1
}
inSub += ")"
q5.AppendSlice(&subFilters, f5.GetDbFilter().Custom(inSub).And())
}
}
{
heroRanks := map[int32]int32{}
for _, val := range(reqJson.Filter.HeroRanks) {
rank := q5.SafeToInt32(val)
heroRanks[rank] = 1
}
if len(heroRanks) > 0 {
inSub := `hero_quality IN (`
i := 0
for key, _ := range(heroRanks) {
if i == 0 {
inSub += q5.ToString(key)
} else {
inSub += "," + q5.ToString(key)
}
i += 1
}
inSub += ")"
q5.AppendSlice(&subFilters, f5.GetDbFilter().Custom(inSub).And())
}
}
rspObj := struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
Page common.StreamPagination `json:"page"`
Rows []struct{
Event interface{} `json:"event"`
Nft interface{} `json:"nft"`
InShopCart int32 `json:"in_shopcart"`
Price string `json:"price"`
} `json:"rows"`
}{}
q5.NewSlice(&rspObj.Rows, 0, 10)
nfts := []*common.NftDto{}
f5.GetGoStyleDb().StreamPageQuery(
constant.BCNFT_DB,
pageSize,
cursor,
sql,
[]string{
},
f5.GetDbFilter().Comp(subFilters...),
orderBy,
func (err error, pagination *f5.StreamPagination) {
rspObj.Page.FillPage(pagination)
},
func (ds *f5.DataSet) {
p := new(common.NftDto)
p.NetId = q5.ToInt32(ds.GetByName("net_id"))
p.ContractAddress = ds.GetByName("contract_address")
p.TokenId = ds.GetByName("token_id")
p.Price = ds.GetByName("price")
p.Payload = map[string]interface{}{}
q5.DecodeJson(ds.GetByName("event_data"), &p.Payload)
q5.AppendSlice(&nfts, p)
})
GetCacheMgr().GetNfts(nfts)
{
for _, val := range nfts {
p := q5.NewSliceElement(&rspObj.Rows)
p.Event = val.Payload
p.Nft = val.NftCache.GetJsonData()
if cartDb != nil && cartDb.GetGoods(val.NetId, val.ContractAddress, val.TokenId) != nil{
p.InShopCart = 1
}
}
}
c.JSON(200, rspObj)
}
func (this *MarketApi) ProductList(c *gin.Context) {
openId := c.MustGet("open_id").(string)
cartDb := service.GetShopCartByOpenId(openId)
netId := q5.ToInt64(c.Param("net_id"))
reqJson := struct {
PageSize interface{} `json:"page_size"`
Cursor interface{} `json:"cursor"`
Search struct {
Name string `json:"name"`
} `json:"search"`
Filter struct {
PriceMin interface{} `json:"price_min"`
PriceMax interface{} `json:"price_max"`
ItemIds []interface{} `json:"item_ids"`
HeroRanks []interface{} `json:"hero_ranks"`
} `json:"filter"`
Sort struct {
Fields [] struct {
Name string `json:"name"`
Type interface{} `json:"type"`
} `json:"fields"`
} `json:"sort"`
}{}
if err := c.ShouldBindJSON(&reqJson); err != nil {
c.JSON(http.StatusOK, gin.H{
"code": 1,
"message": err.Error(),
})
return
}
pageSize := q5.AdjustRangeValue(q5.SafeToInt32(reqJson.PageSize), 1, 20)
cursor := q5.SafeToInt64(reqJson.Cursor)
sql := fmt.Sprintf(`
SELECT * FROM t_order A WHERE net_id = %d AND status="%s"
`,
netId, jccommon.ORDER_STATUS_ACTIVE)
/*
if f5.IsTestEnv() {
sql = fmt.Sprintf(`
SELECT * FROM t_order A WHERE idx > %d AND net_id = %d
`,
cursor, netId)
}*/
orderBy := ""
{
for _, val := range reqJson.Sort.Fields {
if val.Name == "price" && orderBy == "" {
t := q5.SafeToInt32(val.Type)
if t < 0 {
orderBy = " ORDER BY price_len DESC, price DESC"
} else {
orderBy = " ORDER BY price_len ASC, price ASC"
}
}
}
}
subFilters := []f5.DbQueryFilter{}
{
priceMin := q5.SafeToString(reqJson.Filter.PriceMin)
priceMax := q5.SafeToString(reqJson.Filter.PriceMax)
if !q5.IsPureNumber(priceMin) {
priceMin = ""
}
if !q5.IsPureNumber(priceMax) {
priceMax = ""
}
if priceMin != "" && priceMax != "" {
q5.AppendSlice(&subFilters, f5.GetDbFilter().Custom(
fmt.Sprintf(`
((LENGTH(price) > LENGTH('%s') OR (LENGTH(price) = LENGTH('%s') AND price >= '%s'))) AND
((LENGTH(price) < LENGTH('%s') OR (LENGTH(price) = LENGTH('%s') AND price <= '%s')))`,
priceMin,
priceMin,
priceMin,
priceMax,
priceMax,
priceMax)).And())
} else if priceMin != "" {
q5.AppendSlice(&subFilters, f5.GetDbFilter().Custom(
fmt.Sprintf(`(LENGTH(price) > LENGTH('%s') OR (LENGTH(price) = LENGTH('%s') AND price >= '%s'))`,
priceMin,
priceMin,
priceMin)).And())
} else if priceMax != "" {
q5.AppendSlice(&subFilters, f5.GetDbFilter().Custom(
fmt.Sprintf(`(LENGTH(price) < LENGTH('%s') OR (LENGTH(price) = LENGTH('%s') AND price <= '%s'))`,
priceMax,
priceMax,
priceMax)).And())
}
}
{
itemIds := map[int32]int32{}
if reqJson.Search.Name != "" {
mt.Table.Item.Search(reqJson.Search.Name, itemIds)
}
for _, val := range(reqJson.Filter.ItemIds) {
itemId := q5.SafeToInt32(val)
itemIds[itemId] = 1
}
if len(itemIds) > 0 {
inSub := `item_id IN (`
i := 0
for key, _ := range(itemIds) {
if i == 0 {
inSub += q5.ToString(key)
} else {
inSub += "," + q5.ToString(key)
}
i += 1
}
inSub += ")"
q5.AppendSlice(&subFilters, f5.GetDbFilter().Custom(inSub).And())
}
}
{
heroRanks := map[int32]int32{}
for _, val := range(reqJson.Filter.HeroRanks) {
rank := q5.SafeToInt32(val)
heroRanks[rank] = 1
}
if len(heroRanks) > 0 {
inSub := `hero_quality IN (`
i := 0
for key, _ := range(heroRanks) {
if i == 0 {
inSub += q5.ToString(key)
} else {
inSub += "," + q5.ToString(key)
}
i += 1
}
inSub += ")"
q5.AppendSlice(&subFilters, f5.GetDbFilter().Custom(inSub).And())
}
}
rspObj := struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
Page common.StreamPagination `json:"page"`
Rows []struct{
Event interface{} `json:"event"`
Nft interface{} `json:"nft"`
InShopCart int32 `json:"in_shopcart"`
Price string `json:"price"`
} `json:"rows"`
}{}
q5.NewSlice(&rspObj.Rows, 0, 10)
nfts := []*common.NftDto{}
f5.GetGoStyleDb().StreamPageQuery(
constant.BCNFT_DB,
pageSize,
cursor,
sql,
[]string{
},
f5.GetDbFilter().Comp(subFilters...),
orderBy,
func (err error, pagination *f5.StreamPagination) {
rspObj.Page.FillPage(pagination)
},
func (ds *f5.DataSet) {
p := new(common.NftDto)
p.NetId = q5.ToInt32(ds.GetByName("net_id"))
p.ContractAddress = ds.GetByName("contract_address")
p.TokenId = ds.GetByName("token_id")
p.Price = ds.GetByName("price")
p.Payload = map[string]interface{}{}
q5.DecodeJson(ds.GetByName("event_data"), &p.Payload)
q5.AppendSlice(&nfts, p)
})
GetCacheMgr().GetNfts(nfts)
{
for _, val := range nfts {
p := q5.NewSliceElement(&rspObj.Rows)
p.Event = val.Payload
p.Price = val.Price
p.Nft = val.NftCache.GetJsonData()
if cartDb != nil && cartDb.GetGoods(val.NetId, val.ContractAddress, val.TokenId) != nil{
p.InShopCart = 1
}
}
}
c.JSON(200, rspObj)
}
func (this *MarketApi) TransactionHistory(c *gin.Context) {
pageSize := q5.AdjustRangeValue(q5.ToInt32(c.DefaultQuery("page_size", "")), 1, 20)
cursor := q5.ToInt64(c.DefaultQuery("cursor", ""))
netId := q5.ToInt64(c.Param("net_id"))
accountAddress := strings.ToLower(c.Param("account_address"))
searchName := c.DefaultQuery("search_name", "")
filterType := q5.ToInt32(c.DefaultQuery("type", ""))
sql := fmt.Sprintf(`
SELECT * FROM t_sale WHERE idx > %d AND net_id = %d `,
cursor, netId)
params := []string{}
subFilters := []f5.DbQueryFilter{}
{
if filterType == 1 {
sql += "AND buyer = ? "
q5.AppendSlice(&params, accountAddress)
} else if filterType == 2 {
sql += "AND seller = ? "
q5.AppendSlice(&params, accountAddress)
} else {
sql += "AND (buyer = ? OR seller = ?)"
q5.AppendSlice(&params, accountAddress)
q5.AppendSlice(&params, accountAddress)
}
}
{
itemIds := map[int32]int32{}
if searchName != "" {
mt.Table.Item.Search(searchName, itemIds)
}
if len(itemIds) > 0 {
inSub := `item_id IN (`
i := 0
for key, _ := range(itemIds) {
if i == 0 {
inSub += q5.ToString(key)
} else {
inSub += "," + q5.ToString(key)
}
i += 1
}
inSub += ")"
q5.AppendSlice(&subFilters, f5.GetDbFilter().Custom(inSub).And())
}
}
rspObj := struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
Page common.StreamPagination `json:"page"`
Rows []struct{
Event interface{} `json:"event"`
Nft interface{} `json:"nft"`
InShopCart int32 `json:"in_shopcart"`
} `json:"rows"`
}{
}
q5.NewSlice(&rspObj.Rows, 0, 10)
orderBy := " ORDER BY modifytime DESC "
nfts := []*common.NftDto{}
f5.GetGoStyleDb().StreamPageQuery(
constant.BCNFT_DB,
pageSize,
cursor,
sql,
params,
f5.GetDbFilter().Comp(subFilters...),
orderBy,
func (err error, pagination *f5.StreamPagination) {
rspObj.Page.FillPage(pagination)
},
func (ds *f5.DataSet) {
p := new(common.NftDto)
p.NetId = q5.ToInt32(ds.GetByName("net_id"))
p.ContractAddress = ds.GetByName("contract_address")
p.TokenId = ds.GetByName("token_id")
p.Payload = map[string]interface{}{}
q5.DecodeJson(ds.GetByName("event_data"), &p.Payload)
q5.AppendSlice(&nfts, p)
})
GetCacheMgr().GetNfts(nfts)
{
for _, val := range nfts {
p := q5.NewSliceElement(&rspObj.Rows)
p.Event = val.Payload
p.Nft = val.NftCache.GetJsonData()
}
}
c.JSON(200, rspObj)
}
func (this *MarketApi) CategoryGoodsNum(c *gin.Context) {
netId := q5.ToInt64(c.Param("net_id"))
rspObj := &struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
Data []struct{
ItemId int32 `json:"item_id"`
Num int32 `json:"num"`
} `json:"data"`
}{}
q5.NewSlice(&rspObj.Data, 0, 10)
sql := fmt.Sprintf(`
SELECT item_id, COUNT(idx) AS num FROM t_order
WHERE net_id = %d AND status="%s" AND item_id <> 0 GROUP BY item_id
`,
netId,
jccommon.ORDER_STATUS_ACTIVE)
params := []string{}
f5.GetGoStyleDb().RawQuery(
constant.BCNFT_DB,
sql,
params,
func (err error, ds *f5.DataSet) {
if err != nil {
rspObj.ErrCode = 500
rspObj.ErrMsg = "server internal error"
c.JSON(200, rspObj)
return
}
for ds.Next() {
p := q5.NewSliceElement(&rspObj.Data)
p.ItemId = q5.ToInt32(ds.GetByName("item_id"))
p.Num = q5.ToInt32(ds.GetByName("num"))
}
c.JSON(200, rspObj)
})
}
func (this *MarketApi) QueryPrice(c *gin.Context) {
netId := q5.ToInt64(c.DefaultQuery("net_id", ""))
itemId := q5.ToInt64(c.DefaultQuery("item_id", ""))
contractAddress := c.DefaultQuery("contract_address", "")
itemQuality := q5.ToInt64(c.DefaultQuery("quality", ""))
itemMeta := mt.Table.Item.GetById(itemId)
if itemMeta != nil && itemMeta.GetType() != jccommon.ITEM_TYPE_HERO {
itemQuality = 0
}
rspObj := &struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
LowestPriceGoods *goodsDto `json:"lowest_price_goods"`
HighestPriceGoods *goodsDto `json:"highest_price_goods"`
}{}
lowestPriceGoodsIdx := int64(0)
highestPriceGoodsIdx := int64(0)
{
var dbErr error
lowestPrice := ""
highestPrice := ""
sql := fmt.Sprintf(`
SELECT idx, price FROM t_order
WHERE net_id = %d AND contract_address=? AND status="%s" AND item_id = %d AND hero_quality = %d
`,
netId,
jccommon.ORDER_STATUS_ACTIVE,
itemId,
itemQuality)
params := []string{
contractAddress,
}
f5.GetGoStyleDb().RawQuery(
constant.BCNFT_DB,
sql,
params,
func (err error, ds *f5.DataSet) {
dbErr = err
if err != nil {
return
}
for ds.Next() {
idx := q5.ToInt64(ds.GetByName("idx"))
price := ds.GetByName("price")
if lowestPriceGoodsIdx == 0 ||
q5.BigIntStrCmp(lowestPrice, price) < 0 {
lowestPriceGoodsIdx = idx
lowestPrice = price
}
if highestPriceGoodsIdx == 0 ||
q5.BigIntStrCmp(highestPrice, price) > 0 {
highestPriceGoodsIdx = idx
highestPrice = price
}
}
})
if dbErr != nil {
rspObj.ErrCode = 500
rspObj.ErrMsg = "server internal error"
c.JSON(200, rspObj)
return
}
}
{
idxs := []string{}
if lowestPriceGoodsIdx > 0 {
q5.AppendSlice(&idxs, q5.ToString(lowestPriceGoodsIdx))
}
if highestPriceGoodsIdx > 0 {
q5.AppendSlice(&idxs, q5.ToString(highestPriceGoodsIdx))
}
if len(idxs) <= 0 {
c.JSON(200, rspObj)
return
}
var dbErr error
sql := fmt.Sprintf(`
SELECT * FROM t_order
WHERE idx in (%s)
`,
strings.Join(idxs, ","))
nfts := []*common.NftDto{}
f5.GetGoStyleDb().RawQuery(
constant.BCNFT_DB,
sql,
[]string{},
func (err error, ds *f5.DataSet) {
dbErr = err
if err != nil {
return
}
for ds.Next() {
p := new(common.NftDto)
p.Param1 = q5.ToInt64(ds.GetByName("idx"))
p.NetId = q5.ToInt32(ds.GetByName("net_id"))
p.ContractAddress = ds.GetByName("contract_address")
p.TokenId = ds.GetByName("token_id")
p.Payload = map[string]interface{}{}
q5.DecodeJson(ds.GetByName("event_data"), &p.Payload)
q5.AppendSlice(&nfts, p)
}
})
if dbErr != nil {
c.JSON(200, rspObj)
return
}
GetCacheMgr().GetNfts(nfts)
{
for _, val := range nfts {
var p *goodsDto
p = new(goodsDto)
p.Event = val.Payload
p.Nft = val.NftCache.GetJsonData()
if val.Param1 == lowestPriceGoodsIdx {
rspObj.LowestPriceGoods = p
}
if val.Param1 == highestPriceGoodsIdx {
rspObj.HighestPriceGoods = p
}
}
}
c.JSON(200, rspObj)
}
}
func (this *MarketApi) Goods(c *gin.Context) {
openId := c.MustGet("open_id").(string)
cartDb := service.GetShopCartByOpenId(openId)
netId := q5.ToInt64(c.Param("net_id"))
contractAddress := c.Param("contract_address")
tokenId := c.Param("token_id")
rspObj := &struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
Data *goodsDto `json:"data"`
}{}
var dbErr error
sql := fmt.Sprintf(`
SELECT * FROM t_order
WHERE net_id=? AND contract_address=? AND token_id=? AND status=?
`)
nfts := []*common.NftDto{}
f5.GetGoStyleDb().RawQuery(
constant.BCNFT_DB,
sql,
[]string{
q5.ToString(netId),
contractAddress,
tokenId,
jccommon.ORDER_STATUS_ACTIVE,
},
func (err error, ds *f5.DataSet) {
dbErr = err
if err != nil {
return
}
for ds.Next() {
p := new(common.NftDto)
p.Param1 = q5.ToInt64(ds.GetByName("idx"))
p.NetId = q5.ToInt32(ds.GetByName("net_id"))
p.ContractAddress = ds.GetByName("contract_address")
p.TokenId = ds.GetByName("token_id")
p.Payload = map[string]interface{}{}
q5.DecodeJson(ds.GetByName("event_data"), &p.Payload)
q5.AppendSlice(&nfts, p)
}
})
if dbErr != nil {
rspObj.ErrCode = 500
rspObj.ErrMsg = "server internal error"
c.JSON(200, rspObj)
return
}
if len(nfts) <= 0 {
p := new(common.NftDto)
//p.Param1 = q5.ToInt64(ds.GetByName("idx"))
p.NetId = q5.ToInt32(netId)
p.ContractAddress = contractAddress
p.TokenId = tokenId
p.Payload = nil
q5.AppendSlice(&nfts, p)
}
GetCacheMgr().GetNfts(nfts)
{
for _, val := range nfts {
var p *goodsDto
p = new(goodsDto)
p.Event = val.Payload
p.Nft = val.NftCache.GetJsonData()
if cartDb != nil && cartDb.GetGoods(val.NetId, val.ContractAddress, val.TokenId) != nil{
p.InShopCart = 1
}
rspObj.Data = p
}
}
if rspObj.Data == nil {
rspObj.ErrCode = 1
rspObj.ErrMsg = "not found"
c.JSON(200, rspObj)
return
}
c.JSON(200, rspObj)
}

View File

@ -1,5 +0,0 @@
package recharge
type ApiGroup struct {
RechargeApi
}

View File

@ -1,340 +0,0 @@
package recharge
import (
"f5"
"fmt"
"jccommon"
"main/common"
"main/constant"
"main/service"
"main/mt"
"net/http"
"q5"
"strings"
"math/big"
"github.com/gin-gonic/gin"
)
type RechargeApi struct {
}
func (ea *RechargeApi) RechargeList(c *gin.Context) {
netId := q5.ToInt32(c.DefaultQuery("net_id", ""))
accountAddress := c.DefaultQuery("account_address", "")
rspObj := struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
Contribution string `json:"contribution"`
Rows []interface{} `json:"rows"`
}{}
currencysMeta := mt.Table.Currency.GetByNetId(netId)
if currencysMeta == nil {
f5.RspErr(c, 2, "server internal error")
return
}
if contribution, err := service.Contribution.GetAddressContribution(accountAddress, true); err != nil {
f5.RspErr(c, 2, err.Error())
return
} else {
rspObj.Contribution = q5.ToString(contribution)
}
mt.Table.Recharge.Traverse(func(tb *mt.Recharge) bool {
tmpmap := map[string]interface{}{}
tmpmap["goods_id"] = tb.GetId()
tmpmap["diamond"] = tb.GetDiamond()
tmpmap["present_diamond"] = tb.GetPresentDiamond()
tmpmap["price"] = tb.GetPrice()
tmpmap["max_buy_times"] = tb.GetMaxBuyTimes()
tmpmap["can_email_buy"] = tb.GetCanEmailBuy()
currencyList := []struct {
Name string `json:"name"`
Address string `json:"address"`
}{}
currencysMeta.Range(
func(key string, val *mt.Currency) bool {
currency := val
p := q5.NewSliceElement(&currencyList)
p.Name = currency.GetCurrencyName()
p.Address = currency.GetContract().GetAddress()
return true
})
tmpmap["currency_list"] = currencyList
rspObj.Rows = append(rspObj.Rows, tmpmap)
return true
})
c.JSON(200, rspObj)
}
func (this *RechargeApi) Buy(c *gin.Context) {
passportAddress := c.MustGet("account_address").(string)
reqJson := struct {
NetId int32 `json:"net_id"`
GoodsId int32 `json:"goods_id"`
GoodsNum int32 `json:"goods_num"`
AccountAddress string `json:"account_address"`
CurrencyAddress string `json:"currency_address"`
}{}
if err := c.ShouldBindJSON(&reqJson); err != nil {
f5.RspErr(c, 1, err.Error())
return
}
this.internalBuy(c, reqJson.NetId, reqJson.GoodsId, reqJson.GoodsNum,
reqJson.AccountAddress, passportAddress, "", reqJson.CurrencyAddress)
}
func (this *RechargeApi) BuyWithEmail(c *gin.Context) {
passportAddress := c.MustGet("account_address").(string)
email := c.MustGet("email").(string)
reqJson := struct {
NetId int32 `json:"net_id"`
GoodsId int32 `json:"goods_id"`
GoodsNum int32 `json:"goods_num"`
AccountAddress string `json:"account_address"`
CurrencyAddress string `json:"currency_address"`
}{}
if err := c.ShouldBindJSON(&reqJson); err != nil {
f5.GetSysLog().Info("BuyWithEmail passport_address:%s err:%s",
passportAddress, err)
f5.RspErr(c, 1, err.Error())
return
}
f5.GetSysLog().Info("BuyWithEmail passport_address:%s email:%s reqJson:%s",
passportAddress, email, q5.EncodeJson(&reqJson))
if email == "" {
f5.RspErr(c, 1, "email is empty")
return
}
this.internalBuy(c, reqJson.NetId, reqJson.GoodsId, reqJson.GoodsNum,
reqJson.AccountAddress, passportAddress, email, reqJson.CurrencyAddress)
}
func (this *RechargeApi) internalBuy(c *gin.Context,
netId int32, goodsId int32, goodsNum int32, accountAddress string, passportAddress string,
email string, currencyAddress string) {
accountAddress = strings.ToLower(accountAddress)
passportAddress = strings.ToLower(passportAddress)
currencyMeta := mt.Table.Currency.GetByNetIdAddress(netId, currencyAddress)
if currencyMeta == nil {
f5.GetSysLog().Info("internalBuy error:1")
f5.RspErr(c, 2, "server internal error")
return
}
currencyContractMeta := currencyMeta.GetContract()
if currencyContractMeta == nil {
f5.GetSysLog().Info("internalBuy error:2")
f5.RspErr(c, 2, "server internal error")
return
}
goodsMeta := mt.Table.Recharge.GetById(q5.ToInt64(goodsId))
if goodsMeta == nil {
f5.GetSysLog().Info("internalBuy error:3")
f5.RspErr(c, 2, "goods id param error")
return
}
if goodsMeta.GetPrice() <= 0 {
f5.GetSysLog().Info("internalBuy error:4")
f5.RspErr(c, 2, "goods id param error")
return
}
if goodsNum <= 0 || goodsNum > goodsMeta.GetMaxBuyTimes() {
f5.GetSysLog().Info("internalBuy error:5")
f5.RspErr(c, 2, "num param error")
return
}
if email != "" && goodsMeta.GetCanEmailBuy() == 0 {
f5.GetSysLog().Info("internalBuy error:6")
f5.RspErr(c, 2, "cant email buy")
return
}
nowTime := q5.ToInt32(f5.GetApp().GetRealSeconds())
shortOrderId := f5.GetApp().NewLockNodeUuid()
orderId := ""
{
transId := jccommon.NewTransId()
transId.Init(
jccommon.TRANS_ID_FUNC_NORMAL,
nowTime,
0,
[3]int64{
q5.ToInt64(goodsNum),
q5.ToInt64(goodsMeta.GetId()),
shortOrderId,
})
var err error
orderId, err = transId.ToString()
if err != nil {
f5.GetSysLog().Info("internalBuy error:6")
f5.RspErr(c, 2, "server internal error")
return
}
}
srcPrice := q5.ToInt64(goodsMeta.GetPrice()) * q5.ToInt64(goodsNum)
bnPrice := big.NewInt(0)
{
var i, e = big.NewInt(10), big.NewInt(currencyMeta.GetCurrencyDecimal())
i.Exp(i, e, nil)
bnPrice = i.Mul(i, big.NewInt(srcPrice))
}
f5.GetSysLog().Info("recharge net_id:%d currency_name:%s decimal:%d srcPrice:%d bnPrice:%s",
netId, currencyMeta.GetCurrencyName(), currencyMeta.GetCurrencyDecimal(), srcPrice, bnPrice.String());
if bnPrice.Cmp(big.NewInt(0)) < 0 || bnPrice.Cmp(big.NewInt(srcPrice)) < 0 {
f5.GetSysLog().Info("internalBuy error:7")
f5.RspErr(c, 3, "server internal error")
return
}
if ok, err := service.User.InBlackList(accountAddress); err != nil {
f5.GetSysLog().Info("internalBuy error:8")
f5.RspErr(c, 500, "server internal error")
return
} else if ok {
f5.GetSysLog().Info("internalBuy error:9")
f5.RspErr(c, 501, "illegal user")
return
}
params := map[string]string{
"c": "BcService",
"a": "recharge",
"net_id": q5.ToString(netId),
"order_id": orderId,
"account_address": accountAddress,
"passport_address": passportAddress,
"amount": bnPrice.String(),
"currency_name": currencyContractMeta.GetName(),
"currency_address": currencyContractMeta.GetAddress(),
}
jsonRspObj := &struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
Calls []jccommon.ContractCall `json:"calls"`
}{}
var itemNum int32 = goodsNum
var diamond int64 = q5.ToInt64(goodsMeta.GetDiamond()) * int64(itemNum)
var presentDiamond int64 = int64(goodsMeta.GetPresentDiamond()) * int64(itemNum)
url := fmt.Sprintf("%s/webapp/index.php", mt.Table.Web3SignCluster.RandElement().GetUrl())
f5.GetHttpCliMgr().SendGoStyleRequest(
url,
params,
func(rsp f5.HttpCliResponse) {
if rsp.GetErr() != nil {
f5.GetSysLog().Info("internalBuy error:a")
f5.RspErr(c, 500, "server internal error")
return
}
if q5.DecodeJson(rsp.GetRawData(), &jsonRspObj) != nil {
f5.GetSysLog().Info("internalBuy error:b")
f5.RspErr(c, 500, "server internal error")
return
}
if jsonRspObj.ErrCode != 0 {
c.JSON(200, jsonRspObj)
return
}
if !service.AddRechargeOrder(
orderId,
q5.ToString(shortOrderId),
netId,
accountAddress,
passportAddress,
currencyContractMeta.GetName(),
currencyContractMeta.GetAddress(),
goodsMeta.GetId(),
itemNum,
bnPrice.String(),
srcPrice,
diamond,
presentDiamond,
email) {
f5.GetSysLog().Info("internalBuy error:c")
f5.RspErr(c, 500, "server internal error")
return
}
f5.GetSysLog().Info("recharge net_id:%d currency_name:%s decimal:%d srcPrice:%d bnPrice:%s calls.len:%d jsonRsp:%s",
netId,
currencyMeta.GetCurrencyName(),
currencyMeta.GetCurrencyDecimal(),
srcPrice,
bnPrice.String(),
len(jsonRspObj.Calls),
q5.EncodeJson(&jsonRspObj));
c.JSON(200, jsonRspObj)
})
}
func (ea *RechargeApi) RechargeQuery(c *gin.Context) {
account := strings.ToLower(c.Param("account_address"))
netId := q5.ToInt64(c.Param("net_id"))
reqJson := struct {
PageSize interface{} `json:"page_size"`
Cursor interface{} `json:"cursor"`
Search struct{} `json:"search"`
Filter struct{} `json:"filter"`
Sort struct {
Fields []struct{} `json:"fields"`
} `json:"sort"`
}{}
if err := c.ShouldBindJSON(&reqJson); err != nil {
c.JSON(http.StatusOK, gin.H{
"errcode": 1,
"errmsg": err.Error(),
})
return
}
var pageSize int32 = 0xFFFF //q5.AdjustRangeValue(q5.SafeToInt32(reqJson.PageSize), 1, 20)
cursor := q5.SafeToInt64(reqJson.Cursor)
sql := fmt.Sprintf(`
SELECT * FROM t_recharge_order
WHERE idx > %d AND net_id = %d AND passport_address = ? AND pay_status = 1`,
cursor, netId)
params := []string{account}
subFilters := []f5.DbQueryFilter{}
orderBy := " ORDER BY createtime DESC "
rspObj := struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
Page common.StreamPagination `json:"page"`
Rows []struct {
OrderID string `gorm:"column:order_id" json:"order_id"`
ShortOrderID string `gorm:"column:short_order_id" json:"short_order_id"`
TxHash string `gorm:"column:txhash" json:"txhash"`
NetID int64 `gorm:"column:net_id" json:"net_id"`
Currency string `gorm:"column:currency_address" json:"currency"`
CurrencyName string `gorm:"column:currency_name" json:"currency_name"`
Amount string `gorm:"column:price" json:"amount"`
Diamond string `gorm:"column:diamond+present_diamond" json:"diamond"`
Date int32 `gorm:"column:createtime" json:"createtime"`
Account string `gorm:"column:account_address" json:"account_address"`
Passport string `gorm:"column:passport_address" json:"passport_address"`
} `json:"rows"`
}{}
q5.NewSlice(&rspObj.Rows, 0, 10)
f5.GetGoStyleDb().StreamPageQuery(
constant.BCNFT_DB,
pageSize,
cursor,
sql,
params,
f5.GetDbFilter().Comp(subFilters...),
orderBy,
func(err error, pagination *f5.StreamPagination) {
rspObj.Page.FillPage(pagination)
},
func(ds *f5.DataSet) {
p := q5.NewSliceElement(&rspObj.Rows)
f5.UnmarshalModel(ds, p)
})
c.JSON(200, rspObj)
}

View File

@ -1,5 +0,0 @@
package shopcart
type ApiGroup struct {
ShopCartApi
}

View File

@ -1,423 +0,0 @@
package shopcart
import (
"f5"
"jccommon"
"main/common"
"main/constant"
. "main/global"
"q5"
"strings"
"github.com/gin-gonic/gin"
)
type ShopCartApi struct {
}
func (this *ShopCartApi) List(c *gin.Context) {
openId := c.MustGet("open_id").(string)
accountAddress := c.MustGet("account_address").(string)
rspObj := &struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
Data []struct {
Event interface{} `json:"event"`
Nft interface{} `json:"nft"`
} `json:"data"`
}{}
q5.NewSlice(&rspObj.Data, 0, 10)
f5.GetGoStyleDb().OrmSelectOne(
constant.BCNFT_DB,
"t_shopcart",
[][]string{
{"open_id", openId},
},
func(err error, ds *f5.DataSet) {
if err != nil {
rspObj.ErrCode = 500
rspObj.ErrMsg = "server internal error"
c.JSON(200, rspObj)
return
}
nfts := []*common.NftDto{}
if ds.Next() {
cartDb := common.NewShopCart()
if q5.DecodeJson(ds.GetByName("data"), cartDb) == nil {
q5.Sort[common.ShopCartGoods](cartDb.Goods,
func(a *common.ShopCartGoods, b *common.ShopCartGoods) bool {
return a.SortIdx < b.SortIdx
})
dirty := false
newGoods := []*common.ShopCartGoods{}
priceType := ""
priceContractAddress := ""
for _, val := range cartDb.Goods {
var err1 error
wherekv := [][]string{
{"net_id", q5.ToString(val.NetId)},
{"contract_address", q5.ToString(val.ContractAddress)},
{"token_id", q5.ToString(val.TokenId)},
{"status", jccommon.ORDER_STATUS_ACTIVE},
}
if priceType != "" {
wherekv = append(wherekv, []string{"src_price_item_type", priceType})
}
if priceContractAddress != "" {
wherekv = append(wherekv, []string{"src_price_contract_address", priceContractAddress})
}
f5.GetGoStyleDb().OrmSelectOne(
constant.BCNFT_DB,
"t_order",
wherekv,
func(err error, ds *f5.DataSet) {
err1 = err
if err == nil {
if ds.Next() {
if ds.GetByName("seller_address") != accountAddress {
val.PriceType = ds.GetByName("src_price_item_type")
val.PriceContractAddress = ds.GetByName("src_price_contract_address")
val.OrderId = ds.GetByName("order_id")
if priceType == "" && priceContractAddress == "" {
priceType = val.PriceType
priceContractAddress = val.PriceContractAddress
}
p := new(common.NftDto)
p.NetId = q5.ToInt32(ds.GetByName("net_id"))
p.ContractAddress = ds.GetByName("contract_address")
p.TokenId = ds.GetByName("token_id")
p.Payload = map[string]interface{}{}
q5.DecodeJson(ds.GetByName("event_data"), &p.Payload)
q5.AppendSlice(&nfts, p)
q5.AppendSlice(&newGoods, val)
}
} else {
val.Flag = 1
}
dirty = true
}
})
if err1 != nil {
rspObj.ErrCode = 500
rspObj.ErrMsg = "server internal error"
c.JSON(200, rspObj)
return
}
} //end for goods
if dirty {
cartDb.Goods = newGoods
this.save(openId, cartDb)
}
}
}
GetCacheMgr().GetNfts(nfts)
{
for _, val := range nfts {
p := q5.NewSliceElement(&rspObj.Data)
p.Event = val.Payload
p.Nft = val.NftCache.GetJsonData()
}
}
c.JSON(200, rspObj)
})
}
func (this *ShopCartApi) Add(c *gin.Context) {
openId := c.MustGet("open_id").(string)
accountAddress := c.MustGet("account_address").(string)
rspObj := &struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
}{}
reqJson := struct {
NetId interface{} `json:"net_id"`
Tokens []struct {
TokenId interface{} `json:"token_id"`
ContractAddress string `json:"contract_address"`
} `json:"tokens"`
}{}
if err := c.ShouldBindJSON(&reqJson); err != nil {
rspObj.ErrCode = 1
rspObj.ErrMsg = "json parse error"
c.JSON(200, rspObj)
return
}
if len(reqJson.Tokens) > constant.SHOPCART_MAX_GOODS_NUM {
rspObj.ErrCode = 2
rspObj.ErrMsg = "token len error"
c.JSON(200, rspObj)
return
}
f5.GetGoStyleDb().OrmSelectOne(
constant.BCNFT_DB,
"t_shopcart",
[][]string{
{"open_id", openId},
},
func(err error, ds *f5.DataSet) {
if err != nil {
rspObj.ErrCode = 500
rspObj.ErrMsg = "server internal error"
c.JSON(200, rspObj)
return
}
cartDb := common.NewShopCart()
dirty := false
if ds.Next() {
if q5.DecodeJson(ds.GetByName("data"), cartDb) == nil {
}
}
priceType := ""
priceContractAddress := ""
for _, g := range cartDb.Goods {
inreq := false
for _, req := range reqJson.Tokens {
netId := q5.SafeToInt32(reqJson.NetId)
contractAddress := req.ContractAddress
tokenId := q5.SafeToString(req.TokenId)
if g.NetId == netId && g.ContractAddress == contractAddress && g.TokenId == tokenId {
inreq = true
break
}
}
if !inreq {
priceType = g.PriceType
priceContractAddress = g.PriceContractAddress
break
}
}
for _, val := range reqJson.Tokens {
netId := q5.SafeToInt32(reqJson.NetId)
contractAddress := val.ContractAddress
tokenId := q5.SafeToString(val.TokenId)
p := cartDb.GetGoods(netId, contractAddress, tokenId)
if p != nil {
var err1 error
orderok := false
f5.GetGoStyleDb().OrmSelectOne(
constant.BCNFT_DB,
"t_order",
[][]string{
{"net_id", q5.ToString(netId)},
{"contract_address", contractAddress},
{"token_id", tokenId},
{"status", jccommon.ORDER_STATUS_ACTIVE},
},
func(err error, ds *f5.DataSet) {
err1 = err
if err != nil {
return
}
if !ds.Next() {
return
}
if ds.GetByName("seller_address") == accountAddress {
return
}
p.OrderId = ds.GetByName("order_id")
p.PriceType = ds.GetByName("src_price_item_type")
p.PriceContractAddress = ds.GetByName("src_price_contract_address")
if priceType == "" && priceContractAddress == "" {
priceType = p.PriceType
priceContractAddress = p.PriceContractAddress
orderok = true
} else if priceType != "" && priceContractAddress != "" &&
priceType == p.PriceType && priceContractAddress == p.PriceContractAddress {
orderok = true
}
})
if err1 != nil {
rspObj.ErrCode = 500
rspObj.ErrMsg = "server internal error"
c.JSON(200, rspObj)
return
}
if orderok {
cartDb.CurrSortIdx += 1
p.SortIdx = cartDb.CurrSortIdx
p.AddTime = q5.ToInt32(f5.GetApp().GetRealSeconds())
} else {
j := 0
for _, g := range cartDb.Goods {
if g != p {
cartDb.Goods[j] = g
j++
}
}
cartDb.Goods = cartDb.Goods[:j]
}
dirty = true
} else {
var err1 error
f5.GetGoStyleDb().OrmSelectOne(
constant.BCNFT_DB,
"t_order",
[][]string{
{"net_id", q5.ToString(netId)},
{"contract_address", contractAddress},
{"token_id", tokenId},
{"status", jccommon.ORDER_STATUS_ACTIVE},
},
func(err error, ds *f5.DataSet) {
err1 = err
if err == nil {
if ds.Next() {
if ds.GetByName("seller_address") != accountAddress {
cartDb.CurrSortIdx += 1
g := common.NewShopCartGoods()
g.NetId = netId
g.ContractAddress = contractAddress
g.TokenId = tokenId
g.SortIdx = cartDb.CurrSortIdx
g.AddTime = q5.ToInt32(f5.GetApp().GetRealSeconds())
g.OrderId = ds.GetByName("order_id")
g.PriceType = ds.GetByName("src_price_item_type")
g.PriceContractAddress = ds.GetByName("src_price_contract_address")
orderok := false
if priceType == "" && priceContractAddress == "" {
orderok = true
priceType = g.PriceType
priceContractAddress = g.PriceContractAddress
} else if priceType != "" && priceContractAddress != "" && priceType == g.PriceType && priceContractAddress == g.PriceContractAddress {
orderok = true
}
if orderok {
q5.AppendSlice(&cartDb.Goods, g)
}
}
} else {
}
}
})
if err1 != nil {
rspObj.ErrCode = 500
rspObj.ErrMsg = "server internal error"
c.JSON(200, rspObj)
return
}
dirty = true
}
}
if dirty {
cartDb.DeleteExcessData()
this.save(openId, cartDb)
}
c.JSON(200, rspObj)
})
}
func (this *ShopCartApi) Del(c *gin.Context) {
openId := c.MustGet("open_id").(string)
rspObj := &struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
}{}
reqJson := struct {
NetId interface{} `json:"net_id"`
Tokens []struct {
TokenId interface{} `json:"token_id"`
ContractAddress string `json:"contract_address"`
} `json:"tokens"`
}{}
if err := c.ShouldBindJSON(&reqJson); err != nil {
rspObj.ErrCode = 1
rspObj.ErrMsg = "json parse error"
c.JSON(200, rspObj)
return
}
f5.GetGoStyleDb().OrmSelectOne(
constant.BCNFT_DB,
"t_shopcart",
[][]string{
{"open_id", openId},
},
func(err error, ds *f5.DataSet) {
if err != nil {
rspObj.ErrCode = 500
rspObj.ErrMsg = "server internal error"
c.JSON(200, rspObj)
return
}
cartDb := common.NewShopCart()
dirty := false
if ds.Next() {
if q5.DecodeJson(ds.GetByName("data"), cartDb) == nil {
}
}
newGoods := []*common.ShopCartGoods{}
for _, val := range cartDb.Goods {
found := false
for _, val2 := range reqJson.Tokens {
if val.NetId == q5.SafeToInt32(reqJson.NetId) &&
q5.ToString(val.TokenId) == q5.SafeToString(val2.TokenId) &&
strings.ToLower(val.ContractAddress) == strings.ToLower(val2.ContractAddress) {
found = true
}
}
if !found {
q5.AppendSlice(&newGoods, val)
} else {
dirty = true
}
}
cartDb.Goods = newGoods
if dirty {
this.save(openId, cartDb)
}
c.JSON(200, rspObj)
})
}
func (this *ShopCartApi) Clear(c *gin.Context) {
openId := c.MustGet("open_id").(string)
rspObj := &struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
}{}
cartDb := common.NewShopCart()
this.save(openId, cartDb)
c.JSON(200, rspObj)
}
func (this *ShopCartApi) save(openId string, cartDb *common.ShopCart) {
nowTime := f5.GetApp().GetRealSeconds()
f5.GetGoStyleDb().Upsert(
constant.BCNFT_DB,
"t_shopcart",
[][]string{
{"open_id", openId},
},
[][]string{
{"data", q5.EncodeJson(cartDb)},
{"modifytime", q5.ToString(nowTime)},
},
[][]string{
{"open_id", openId},
{"data", q5.EncodeJson(cartDb)},
{"createtime", q5.ToString(nowTime)},
{"modifytime", q5.ToString(nowTime)},
},
func(err error, lastInsertId int64, rowsAffected int64) {
})
}

View File

@ -1,5 +0,0 @@
package user
type ApiGroup struct {
UserApi
}

View File

@ -1,134 +0,0 @@
package user
import (
"f5"
"fmt"
"main/constant"
"main/service"
"q5"
"strings"
"github.com/gin-gonic/gin"
)
type UserApi struct {
}
func (this *UserApi) Info(c *gin.Context) {
accountAddress := strings.ToLower(c.Param("account_address"))
rspObj := struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
NickName string `json:"nickname"`
Email string `json:"email"`
ContributionPoint string `json:"contribution_point"`
Gold string `json:"gold"`
Diamond string `json:"diamond"`
}{}
rspObj.Email = c.MustGet("email").(string)
contributionPoint, err := service.Contribution.GetAddressContribution(accountAddress, false)
if err != nil {
f5.RspErr(c, 2, err.Error())
return
}
var gold float64
var diamond float64
{
var dbErr error
f5.GetGoStyleDb().OrmSelectOne(
constant.GAME_DB,
"t_user",
[][]string{
{"address", accountAddress},
},
func(err error, ds *f5.DataSet) {
dbErr = err
if err != nil {
return
}
if ds.Next() {
rspObj.NickName = ds.GetByName("name")
gold = q5.ToFloat64(ds.GetByName("gold"))
diamond = q5.ToFloat64(ds.GetByName("diamond"))
}
})
if dbErr != nil {
f5.RspErr(c, 500, "server internal error")
return
}
}
// {
// var dbErr error
// f5.GetGoStyleDb().OrmSelectOne(
// constant.BCNFT_DB,
// "t_contribution",
// [][]string{
// {"account_address", accountAddress},
// },
// func(err error, ds *f5.DataSet) {
// dbErr = err
// if err != nil {
// return
// }
// if ds.Next() {
// contributionPoint += q5.ToFloat64(ds.GetByName("contribution"))
// }
// })
// if dbErr != nil {
// f5.RspErr(c, 500, "server internal error")
// return
// }
// }
// {
// var dbErr error
// sql := "SELECT SUM(contribution) FROM t_staking_daily_settlement WHERE account_address = ?"
// params := []string{
// accountAddress,
// }
// f5.GetGoStyleDb().RawQuery(
// constant.BCNFT_DB,
// sql,
// params,
// func(err error, ds *f5.DataSet) {
// dbErr = err
// if err != nil {
// return
// }
// for ds.Next() {
// contributionPoint += q5.ToFloat64(ds.GetByIndex(0))
// }
// })
// if dbErr != nil {
// f5.RspErr(c, 500, "server internal error")
// return
// }
// }
{
var dbErr error
sql := "SELECT SUM(diamond+present_diamond) FROM t_recharge_order WHERE passport_address = ? AND pay_status = 1 AND delivery_status = 0;"
params := []string{
accountAddress,
}
f5.GetGoStyleDb().RawQuery(
constant.BCNFT_DB,
sql,
params,
func(err error, ds *f5.DataSet) {
dbErr = err
if err != nil {
return
}
if ds.Next() {
diamond += q5.ToFloat64(ds.GetByIndex(0))
}
})
if dbErr != nil {
f5.RspErr(c, 500, "server internal error")
return
}
}
rspObj.ContributionPoint = fmt.Sprintf("%.2f", contributionPoint)
rspObj.Gold = fmt.Sprintf("%.2f", gold)
rspObj.Diamond = fmt.Sprintf("%.2f", diamond)
c.JSON(200, rspObj)
}

View File

@ -1,5 +0,0 @@
package vip
type ApiGroup struct {
VIPApi
}

View File

@ -1,167 +0,0 @@
package vip
import (
"f5"
"main/constant"
"main/service"
"q5"
"strings"
"github.com/gin-gonic/gin"
)
type VIPApi struct {
}
func (this *VIPApi) Info(c *gin.Context) {
accountAddress := c.MustGet("account_address").(string)
rspObj := struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
ContributionPoint string `json:"contribution_point"`
Info struct {
BindPassport string `json:"bind_passport_address"`
Email string `json:"bind_email"`
} `json:"info"`
}{}
{
var dbErr error
sql := "SELECT passport_address,lower_case_email FROM t_vip_bind WHERE account_address = ?;"
params := []string{
accountAddress,
}
f5.GetGoStyleDb().RawQuery(
constant.BCNFT_DB,
sql,
params,
func(err error, ds *f5.DataSet) {
dbErr = err
if err != nil {
return
}
if ds.Next() {
rspObj.Info.BindPassport = ds.GetByIndex(0)
rspObj.Info.Email = ds.GetByIndex(1)
}
})
if dbErr != nil {
f5.RspErr(c, 500, "server internal error")
return
}
}
c.JSON(200, rspObj)
}
func (this *VIPApi) Bind(c *gin.Context) {
accountAddress := c.GetString("account_address")
if accountAddress == "" {
f5.RspErr(c, 1, "bad request")
return
}
reqObj := struct {
Passport_jwt string `json:"passport_jwt"`
}{}
if err := c.ShouldBindJSON(&reqObj); err != nil {
f5.RspErr(c, 1, err.Error())
return
}
info := map[string]interface{}{}
info["account_address"] = ""
info["email"] = ""
service.JwtAuth.JwtAuthHandle(reqObj.Passport_jwt, &info, constant.JWT_PASSPORT)
passport_addr := info["account_address"].(string)
if passport_addr == "" || accountAddress == passport_addr {
f5.RspErr(c, 1, "bad request passport")
return
}
email := info["email"].(string)
bound := false
{
var dbErr error
sql := "SELECT idx FROM t_vip_bind WHERE account_address = ? OR passport_address = ?;"
params := []string{
accountAddress,
passport_addr,
}
f5.GetGoStyleDb().RawQuery(
constant.BCNFT_DB,
sql,
params,
func(err error, ds *f5.DataSet) {
dbErr = err
if err != nil {
return
}
if ds.Next() {
bound = true
}
})
if dbErr != nil {
f5.RspErr(c, 500, "server internal error")
return
}
}
if bound {
f5.RspErr(c, 1, "account or passport bound")
return
}
{
ts := f5.GetApp().GetRealSeconds()
var dbErr error
f5.GetGoStyleDb().Insert(
constant.BCNFT_DB,
"t_vip_bind",
[][]string{
{"account_address", accountAddress},
{"passport_address", passport_addr},
{"email", email},
{"lower_case_email", strings.ToLower(email)},
{"createtime", q5.ToString(ts)},
{"modifytime", q5.ToString(ts)},
},
func(err error, lastInsertId int64, rowsAffected int64) {
if err != nil {
dbErr = err
return
}
})
if dbErr != nil {
f5.RspErr(c, 500, "server internal error")
return
}
}
f5.RspErr(c, 0, "")
}
func (this *VIPApi) Details(c *gin.Context) {
accountAddress := c.GetString("account_address")
if accountAddress == "" {
f5.RspErr(c, 1, "bad request")
return
}
rspObj := struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
Info struct {
Level int32 `json:"level"`
Cur int64 `json:"curpoint"`
Target int64 `json:"target"`
} `json:"info"`
}{}
c.JSON(200, rspObj)
}

View File

@ -2,10 +2,8 @@ package app
import (
"f5"
"jccommon"
"main/constant"
"main/mt"
"q5"
)
type app struct {
@ -31,19 +29,6 @@ func (this *app) Init() {
f5.LoadMetaTable(mt.Table)
this.registerDataSources()
this.initCb()
transId := jccommon.NewTransId()
transId.Init(11, q5.ToInt32(f5.GetApp().GetRealSeconds()), 1234567, [3]int64{
1000000000123456789,
1000000000123456789,
1000000000123456789})
idStr, _ := transId.ToString()
transId2 := jccommon.NewTransId()
transId2.ParseString(idStr)
f5.GetSysLog().Info("transId1:%s", idStr)
{
idStr2, _ := transId2.ToString()
f5.GetSysLog().Info("transId2:%s", idStr2)
}
}
func (this *app) UnInit() {
@ -54,17 +39,6 @@ func (this *app) Update() {
}
func (this *app) registerDataSources() {
f5.GetGoStyleDb().RegisterDataSource(
constant.BCNFT_DB,
mt.Table.NftDb.GetById(0).GetHost(),
mt.Table.NftDb.GetById(0).GetPort(),
mt.Table.NftDb.GetById(0).GetUser(),
mt.Table.NftDb.GetById(0).GetPasswd(),
mt.Table.NftDb.GetById(0).GetDatabase(),
1,
mt.Table.NftDb.GetById(0).GetMaxOpenConns(),
mt.Table.NftDb.GetById(0).GetMaxIdleConns())
f5.GetGoStyleDb().RegisterDataSource(
constant.PAY_DB,
mt.Table.PayDb.GetById(0).GetHost(),

View File

@ -6,6 +6,7 @@ const (
GAME_DB = "gamedb"
CONF_DB = "confdb"
PAY_DB = "paydb"
LOGIN_REDIS = "loginredis"
)
const (
@ -37,3 +38,14 @@ const (
JWT_METAMAST = 1
JWT_PASSPORT = 2
)
const (
WX_ERRCODE_OK = 0
WX_ERRCODE_BUSY = -1
WX_ERRCODE_SIGERR = 90010
WX_ERRCODE_PAYSIGERR = 90011
WX_ERRCODE_SAMEBILLNO = 90012
WX_ERRCODE_NOENOUGH = 90013
WX_ERRCODE_SESSIONERR = 90016
WX_ERRCODE_PARAMERR = 90018
)

View File

@ -1,12 +1,7 @@
package middleware
import (
"f5"
"fmt"
"jccommon"
"main/mt"
"q5"
"strings"
"github.com/gin-gonic/gin"
)
@ -46,133 +41,133 @@ func internalJwtAuth(c *gin.Context, maybe bool) {
}
func internalImmutJwtAuth(c *gin.Context, jwtToken string) {
params := map[string]string{
"c": "Jwt",
"a": "verify",
}
jsonReqObj := &struct {
JwksUri string `json:"jwksUri"`
Data string `json:"data"`
}{
JwksUri: mt.Table.Config.GetJwksUri(),
Data: jwtToken,
}
jsonRspObj := &struct {
ErrCode interface{} `json:"errcode"`
ErrMsg string `json:"errmsg"`
Decoded struct {
Sub string `json:"sub"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Sid string `json:"sid"`
Passport struct {
ZkevmEthAddress string `json:"zkevm_eth_address"`
} `json:"passport"`
} `json:"decoded"`
}{}
rspObj := &struct {
ErrCode interface{} `json:"errcode"`
ErrMsg string `json:"errmsg"`
}{}
paramsStr := q5.EncodeJson(jsonReqObj)
url := fmt.Sprintf("%s/webapp/index.php", mt.Table.Web3ServiceCluster.RandElement().GetUrl())
f5.GetHttpCliMgr().SendGoStyleJsonRspPost(
url,
params,
jsonRspObj,
q5.HTTP_HEADER_JSON,
paramsStr,
func(rsp f5.HttpCliResponse) {
if rsp.GetErr() != nil ||
!rsp.JsonParseOk() {
rspObj.ErrCode = 500
rspObj.ErrMsg = "server internal error"
c.JSON(200, rspObj)
c.Abort()
return
}
rspObj.ErrCode = q5.SafeToInt32(jsonRspObj.ErrCode)
rspObj.ErrMsg = jsonRspObj.ErrMsg
if q5.SafeToInt32(rspObj.ErrCode) != 0 {
rspObj.ErrCode = 501
rspObj.ErrMsg = "jwt expired"
c.JSON(200, rspObj)
c.Abort()
return
}
openId := fmt.Sprintf("%d_2006_%s", jccommon.IMTBL_CHANNEL, jsonRspObj.Decoded.Sub)
c.Set("open_id", openId)
c.Set("account_address", jsonRspObj.Decoded.Passport.ZkevmEthAddress)
c.Set("email", jsonRspObj.Decoded.Email)
c.Next()
})
// params := map[string]string{
// "c": "Jwt",
// "a": "verify",
// }
// jsonReqObj := &struct {
// JwksUri string `json:"jwksUri"`
// Data string `json:"data"`
// }{
// JwksUri: mt.Table.Config.GetJwksUri(),
// Data: jwtToken,
// }
// jsonRspObj := &struct {
// ErrCode interface{} `json:"errcode"`
// ErrMsg string `json:"errmsg"`
// Decoded struct {
// Sub string `json:"sub"`
// Email string `json:"email"`
// EmailVerified bool `json:"email_verified"`
// Sid string `json:"sid"`
// Passport struct {
// ZkevmEthAddress string `json:"zkevm_eth_address"`
// } `json:"passport"`
// } `json:"decoded"`
// }{}
// rspObj := &struct {
// ErrCode interface{} `json:"errcode"`
// ErrMsg string `json:"errmsg"`
// }{}
// paramsStr := q5.EncodeJson(jsonReqObj)
// url := fmt.Sprintf("%s/webapp/index.php", mt.Table.Web3ServiceCluster.RandElement().GetUrl())
// f5.GetHttpCliMgr().SendGoStyleJsonRspPost(
// url,
// params,
// jsonRspObj,
// q5.HTTP_HEADER_JSON,
// paramsStr,
// func(rsp f5.HttpCliResponse) {
// if rsp.GetErr() != nil ||
// !rsp.JsonParseOk() {
// rspObj.ErrCode = 500
// rspObj.ErrMsg = "server internal error"
// c.JSON(200, rspObj)
// c.Abort()
// return
// }
// rspObj.ErrCode = q5.SafeToInt32(jsonRspObj.ErrCode)
// rspObj.ErrMsg = jsonRspObj.ErrMsg
// if q5.SafeToInt32(rspObj.ErrCode) != 0 {
// rspObj.ErrCode = 501
// rspObj.ErrMsg = "jwt expired"
// c.JSON(200, rspObj)
// c.Abort()
// return
// }
// openId := fmt.Sprintf("%d_2006_%s", jccommon.IMTBL_CHANNEL, jsonRspObj.Decoded.Sub)
// c.Set("open_id", openId)
// c.Set("account_address", jsonRspObj.Decoded.Passport.ZkevmEthAddress)
// c.Set("email", jsonRspObj.Decoded.Email)
// c.Next()
// })
}
func internalMetaMaskJwtAuth(c *gin.Context, jwtToken string) {
params := map[string]string{
"c": "MetaMaskJwt",
"a": "verify",
}
jsonReqObj := &struct {
Data string `json:"data"`
}{
Data: jwtToken,
}
jsonRspObj := &struct {
ErrCode interface{} `json:"errcode"`
ErrMsg string `json:"errmsg"`
Decoded struct {
Id string `json:"id"`
OpenId string `json:"openid"`
Plat int32 `json:"plat"`
Version int32 `json:"version"`
Email string `json:"email"`
} `json:"decoded"`
}{}
rspObj := &struct {
ErrCode interface{} `json:"errcode"`
ErrMsg string `json:"errmsg"`
}{}
paramsStr := q5.EncodeJson(jsonReqObj)
url := fmt.Sprintf("%s/webapp/index.php", mt.Table.Web3ServiceCluster.RandElement().GetUrl())
f5.GetHttpCliMgr().SendGoStyleJsonRspPost(
url,
params,
jsonRspObj,
q5.HTTP_HEADER_JSON,
paramsStr,
func(rsp f5.HttpCliResponse) {
if rsp.GetErr() != nil ||
!rsp.JsonParseOk() {
rspObj.ErrCode = 500
rspObj.ErrMsg = "server internal error"
c.JSON(200, rspObj)
c.Abort()
return
}
rspObj.ErrCode = q5.SafeToInt32(jsonRspObj.ErrCode)
rspObj.ErrMsg = jsonRspObj.ErrMsg
if q5.SafeToInt32(rspObj.ErrCode) != 0 {
rspObj.ErrCode = 501
rspObj.ErrMsg = "jwt error"
c.JSON(200, rspObj)
c.Abort()
return
}
if jsonRspObj.Decoded.Plat != jccommon.BC_POLY_POLY_METAKASK {
rspObj.ErrCode = 501
rspObj.ErrMsg = "not support this platform"
c.JSON(200, rspObj)
c.Abort()
f5.GetSysLog().Info("not support this platform:%s", rsp.GetRawData())
return
}
openId := fmt.Sprintf("%d_2006_%s",
jccommon.BC_CHANNEL,
strings.ToLower(jsonRspObj.Decoded.OpenId))
c.Set("open_id", openId)
c.Set("account_address", strings.ToLower(jsonRspObj.Decoded.OpenId))
c.Set("email", strings.ToLower(jsonRspObj.Decoded.Email))
c.Next()
})
// params := map[string]string{
// "c": "MetaMaskJwt",
// "a": "verify",
// }
// jsonReqObj := &struct {
// Data string `json:"data"`
// }{
// Data: jwtToken,
// }
// jsonRspObj := &struct {
// ErrCode interface{} `json:"errcode"`
// ErrMsg string `json:"errmsg"`
// Decoded struct {
// Id string `json:"id"`
// OpenId string `json:"openid"`
// Plat int32 `json:"plat"`
// Version int32 `json:"version"`
// Email string `json:"email"`
// } `json:"decoded"`
// }{}
// rspObj := &struct {
// ErrCode interface{} `json:"errcode"`
// ErrMsg string `json:"errmsg"`
// }{}
// paramsStr := q5.EncodeJson(jsonReqObj)
// url := fmt.Sprintf("%s/webapp/index.php", mt.Table.Web3ServiceCluster.RandElement().GetUrl())
// f5.GetHttpCliMgr().SendGoStyleJsonRspPost(
// url,
// params,
// jsonRspObj,
// q5.HTTP_HEADER_JSON,
// paramsStr,
// func(rsp f5.HttpCliResponse) {
// if rsp.GetErr() != nil ||
// !rsp.JsonParseOk() {
// rspObj.ErrCode = 500
// rspObj.ErrMsg = "server internal error"
// c.JSON(200, rspObj)
// c.Abort()
// return
// }
// rspObj.ErrCode = q5.SafeToInt32(jsonRspObj.ErrCode)
// rspObj.ErrMsg = jsonRspObj.ErrMsg
// if q5.SafeToInt32(rspObj.ErrCode) != 0 {
// rspObj.ErrCode = 501
// rspObj.ErrMsg = "jwt error"
// c.JSON(200, rspObj)
// c.Abort()
// return
// }
// if jsonRspObj.Decoded.Plat != jccommon.BC_POLY_POLY_METAKASK {
// rspObj.ErrCode = 501
// rspObj.ErrMsg = "not support this platform"
// c.JSON(200, rspObj)
// c.Abort()
// f5.GetSysLog().Info("not support this platform:%s", rsp.GetRawData())
// return
// }
// openId := fmt.Sprintf("%d_2006_%s",
// jccommon.BC_CHANNEL,
// strings.ToLower(jsonRspObj.Decoded.OpenId))
// c.Set("open_id", openId)
// c.Set("account_address", strings.ToLower(jsonRspObj.Decoded.OpenId))
// c.Set("email", strings.ToLower(jsonRspObj.Decoded.Email))
// c.Next()
// })
}

View File

@ -54,14 +54,6 @@ func (this *InAppOrder) UpdateFields(fields []string) error {
}
func (this *InAppOrder) Find(accountId string, orderId string) (error, bool) {
// if result := f5.GetApp().GetOrmDb(constant.PAY_DB).Table(this.TableName()).Take(
// this, "account_id = ? AND order_id = ?", accountId, orderId); result.Error != nil &&
// !errors.Is(result.Error, gorm.ErrRecordNotFound) {
// return result.Error, false
// } else {
// return nil, result.RowsAffected > 0
// }
err, ok := this.FindByOrderId(orderId)
if err != nil {
return err, false

View File

@ -3,6 +3,7 @@ package mt
import (
"f5"
"main/mtb"
"strings"
)
type Config struct {
@ -18,8 +19,8 @@ func (this *ConfigTable) GetGameApiUrl() string {
return this.selfConf.GetGameapiUrl()
}
func (this *ConfigTable) GetJwksUri() string {
return this.selfConf.GetJwksUri()
func (this *ConfigTable) GetWxUrl() []string {
return strings.Split(this.selfConf.GetWxUrl(), "|")
}
/*

View File

@ -1,112 +0,0 @@
package mt
import (
"encoding/json"
"f5"
"fmt"
"q5"
"strings"
)
type Contract struct {
name string
address string
}
type ContractTable struct {
netIdNameHash *q5.ConcurrentMap[string, *Contract]
netIdAddressHash *q5.ConcurrentMap[string, *Contract]
}
func (this *Contract) GetName() string {
return this.name
}
func (this *Contract) GetAddress() string {
return this.address
}
func (this *ContractTable) IsNoLoad() bool {
return false
}
func (this *ContractTable) Load() {
this.netIdNameHash = new(q5.ConcurrentMap[string, *Contract])
this.netIdAddressHash = new(q5.ConcurrentMap[string, *Contract])
nets := []interface{}{}
{
if jsonStr, err := f5.ReadJsonFile("../config/nets.json"); err == nil {
if err := json.Unmarshal([]byte(jsonStr), &nets); err != nil {
panic(fmt.Sprintf("load metafile json decode error %s %s", "nets.json", err))
}
} else {
panic(fmt.Sprintf("load metafile error %s %s", "nets.json", err))
}
}
{
for _, val := range nets {
netId := q5.SafeToInt32(val)
fileName := fmt.Sprintf("../config/nets/%d/contract.json", netId)
if jsonStr, err := f5.ReadJsonFile(fileName); err == nil {
contracts := []struct {
Name string `json:"name"`
Address string `json:"address"`
}{}
if err := json.Unmarshal([]byte(jsonStr), &contracts); err != nil {
panic(fmt.Sprintf("load metafile json decode error %s %s", "contract.json", err))
}
for _, val2 := range contracts {
p := new(Contract)
p.name = q5.SafeToString(val2.Name)
p.address = strings.ToLower(q5.SafeToString(val2.Address))
{
key := fmt.Sprintf("%d_%s", netId, p.name)
this.netIdNameHash.Store(key, p)
}
{
key := fmt.Sprintf("%d_%s", netId, p.address)
this.netIdAddressHash.Store(key, p)
}
}
} else {
panic(fmt.Sprintf("load metafile error %s %s", "contract.json", err))
}
}
}
}
func (this *ContractTable) PreInit1() {
}
func (this *ContractTable) ElementsInit(int) {
}
func (this *ContractTable) PostInit1() {
}
func (this *ContractTable) GetByNetIdName(netId int32, name string) *Contract {
key := fmt.Sprintf("%d_%s", netId, name)
if v, ok := this.netIdNameHash.Load(key); ok {
return *v
} else {
return nil
}
}
func (this *ContractTable) GetByNetIdAddress(netId int32, address string) *Contract {
key := fmt.Sprintf("%d_%s", netId, address)
if v, ok := this.netIdAddressHash.Load(key); ok {
return *v
} else {
return nil
}
}
func (this *ContractTable) Traverse(cb func(*Contract) bool) {
this.netIdNameHash.Range(func(k string, v *Contract) bool {
return cb(v)
})
}

View File

@ -1,164 +0,0 @@
package mt
import (
"f5"
"fmt"
"jccommon"
"main/constant"
"q5"
"strings"
)
type Currency struct {
currencyName string
contractName string
currencyDecimal int64
contract *Contract
}
type CurrencyTable struct {
f5.CustomMetaTable
netIdHash *q5.ConcurrentMap[int32, *q5.ConcurrentMap[string, *Currency]]
}
func (this *Currency) init(currencyName string, contractName string, currencyDecimal int64) {
this.currencyName = currencyName
this.contractName = contractName
this.currencyDecimal = currencyDecimal
}
func (this *Currency) GetCurrencyName() string {
return this.currencyName
}
func (this *Currency) GetContractName() string {
return this.contractName
}
func (this *Currency) GetCurrencyDecimal() int64 {
return this.currencyDecimal
}
func (this *Currency) GetContract() *Contract {
return this.contract
}
func (this *Currency) check(netId int32) {
if this.GetCurrencyDecimal() <= 0 {
panic("Currency currency_decimal <= 0")
return
}
if netId == 56 || netId == 97 {
if this.GetCurrencyDecimal() != constant.BNB_RECHARGE_CURRENCY_MAX_DECIMAL {
panic("Currency exchange_rate > uplimit")
return
}
} else {
if this.GetCurrencyDecimal() != constant.RECHARGE_CURRENCY_MAX_DECIMAL {
panic("Currency exchange_rate > uplimit")
return
}
}
}
func (this *CurrencyTable) GetByNetId(netId int32) *q5.ConcurrentMap[string, *Currency] {
if v, ok := this.netIdHash.Load(netId); ok {
return *v
} else {
return nil
}
}
func (this *CurrencyTable) GetByNetIdAddress(netId int32, currencyAddress string) *Currency {
currencysMeta := this.GetByNetId(netId)
if currencysMeta == nil {
return nil
}
var result *Currency
currencyAddress = strings.ToLower(currencyAddress)
currencysMeta.Range(
func(key string, meta *Currency) bool {
if meta.GetContract().GetAddress() == currencyAddress {
result = meta
return false
}
return true
})
return result
}
func (this *CurrencyTable) Load() {
}
func (this *CurrencyTable) PostInit1() {
}
func (this *CurrencyTable) verifyCurrencyAddress(netId int32, name string, address string) {
switch netId {
case jccommon.ETH_NET_ID:
{
if name == "BEUSDC" {
if strings.ToLower(address) != strings.ToLower(jccommon.ETH_USDC_ADDRESS) {
panic(fmt.Sprintf("verifyCurrencyAddress error net:%d name:%s address:%s",
netId, name, address))
}
} else if name == "BEUSDT" {
if strings.ToLower(address) != strings.ToLower(jccommon.ETH_USDT_ADDRESS) {
panic(fmt.Sprintf("verifyCurrencyAddress error net:%d name:%s address:%s",
netId, name, address))
}
} else {
panic(fmt.Sprintf("verifyCurrencyAddress error net:%d name:%s address:%s",
netId, name, address))
}
}
case jccommon.IMTBL_NET_ID:
{
if name == "BEUSDC" {
if strings.ToLower(address) != strings.ToLower(jccommon.IMTBL_USDC_ADDRESS) {
panic(fmt.Sprintf("verifyCurrencyAddress error net:%d name:%s address:%s",
netId, name, address))
}
} else {
panic(fmt.Sprintf("verifyCurrencyAddress error net:%d name:%s address:%s",
netId, name, address))
}
}
case jccommon.ARB_NET_ID:
{
if name == "BEUSDC" {
if strings.ToLower(address) != strings.ToLower(jccommon.ARB_USDC_ADDRESS) {
panic(fmt.Sprintf("verifyCurrencyAddress error net:%d name:%s address:%s",
netId, name, address))
}
} else if name == "BEUSDT" {
if strings.ToLower(address) != strings.ToLower(jccommon.ARB_USDT_ADDRESS) {
panic(fmt.Sprintf("verifyCurrencyAddress error net:%d name:%s address:%s",
netId, name, address))
}
} else {
panic(fmt.Sprintf("verifyCurrencyAddress error net:%d name:%s address:%s",
netId, name, address))
}
}
case jccommon.BNB_NET_ID:
{
if name == "BEUSDC" {
if strings.ToLower(address) != strings.ToLower(jccommon.BNB_USDC_ADDRESS) {
panic(fmt.Sprintf("verifyCurrencyAddress error net:%d name:%s address:%s",
netId, name, address))
}
} else if name == "BEUSDT" {
if strings.ToLower(address) != strings.ToLower(jccommon.BNB_USDT_ADDRESS) {
panic(fmt.Sprintf("verifyCurrencyAddress error net:%d name:%s address:%s",
netId, name, address))
}
} else {
panic(fmt.Sprintf("verifyCurrencyAddress error net:%d name:%s address:%s",
netId, name, address))
}
}
}
}

View File

@ -1,60 +0,0 @@
package mt
import (
"q5"
"f5"
"os"
"main/mtb"
"jccommon"
"strings"
)
type Item struct {
mtb.Item
lowerName string
}
type ItemTable struct {
f5.IdMetaTable[Item]
itemIdHash *q5.ConcurrentMap[int64, *Item]
}
func (this *ItemTable) PostInit1() {
this.itemIdHash = new(q5.ConcurrentMap[int64, *Item])
items := []struct {
Id int32 `json:"id"`
Name string `json:"name"`
Type int32 `json:"type"`
SubType int32 `json:"sub_type"`
}{}
this.Traverse(
func (ele *Item) bool {
if ele.GetType() == jccommon.ITEM_TYPE_HERO ||
ele.GetType() == jccommon.ITEM_TYPE_GOLD_BULLION {
langMeta := Table.Language.GetByName(ele.GetName())
p := q5.NewSliceElement(&items)
p.Id = ele.GetId()
p.Name = langMeta.GetEn()
p.Type = ele.GetType()
p.SubType = ele.GetSubType()
ele.lowerName = strings.ToLower(langMeta.GetEn())
this.itemIdHash.Store(q5.ToInt64(ele.GetId()), ele)
}
return true
})
data := q5.EncodeJson(&items)
if err := os.WriteFile("item.json", []byte(data), 0644); err == nil {
}
}
func (this *ItemTable) Search(name string, itemIds map[int32]int32) {
name = strings.ToLower(name)
this.Traverse(
func (ele *Item) bool {
if strings.Contains(ele.lowerName, name) {
itemIds[ele.GetId()] = 1
}
return true
})
}

View File

@ -1,14 +0,0 @@
package mt
import (
"f5"
"main/mtb"
)
type Language struct {
mtb.Language
}
type LanguageTable struct {
f5.NameMetaTable[Language]
}

View File

@ -0,0 +1,15 @@
package mt
import (
"f5"
"main/mtb"
)
type LoginRedis struct {
mtb.LoginRedis
}
type LoginRedisTable struct {
f5.IdMetaTable[LoginRedis]
selfConf *LoginRedis
}

View File

@ -1,17 +0,0 @@
package mt
import (
"f5"
"main/mtb"
)
type NftDb struct {
mtb.NftDb
}
type NftDbTable struct {
f5.IdMetaTable[NftDb]
}
func (this *NftDb) Init1() {
}

View File

@ -1,14 +0,0 @@
package mt
import (
"f5"
"main/mtb"
)
type StakingVip struct {
mtb.StakingVip
}
type StakingVipTable struct {
f5.IdMetaTable[StakingVip]
}

View File

@ -1,18 +0,0 @@
package mt
import (
"f5"
"main/mtb"
)
type Web3ServiceCluster struct {
mtb.Web3ServiceCluster
}
type Web3ServiceClusterTable struct {
f5.IdMetaTable[Web3ServiceCluster]
}
func (this *Web3ServiceCluster) Init1() {
}

View File

@ -1,18 +0,0 @@
package mt
import (
"f5"
"main/mtb"
)
type Web3SignCluster struct {
mtb.Web3SignCluster
}
type Web3SignClusterTable struct {
f5.IdMetaTable[Web3SignCluster]
}
func (this *Web3SignCluster) Init1() {
}

View File

@ -0,0 +1,14 @@
package mt
import (
"f5"
"main/mtb"
)
type Wxconfig struct {
mtb.Wxconfig
}
type WxconfigTable struct {
f5.IdMetaTable[Wxconfig]
}

View File

@ -6,18 +6,13 @@ import (
type table struct {
PayServerCluster *PayServerClusterTable
NftDb *NftDbTable
PayDb *PayDbTable
GameDb *GameDbTable
Config *ConfigTable
Item *ItemTable
Language *LanguageTable
Web3ServiceCluster *Web3ServiceClusterTable
Web3SignCluster *Web3SignClusterTable
Recharge *RechargeTable
Currency *CurrencyTable
AccountDb *AccountDbTable
ConfDb *ConfDbTable
Wxconfig *WxconfigTable
LoginRedis *LoginRedisTable
}
var Table = f5.New(func(this *table) {
@ -26,11 +21,6 @@ var Table = f5.New(func(this *table) {
this.PrimKey = "instance_id"
})
this.NftDb = f5.New(func(this *NftDbTable) {
this.FileName = "../config/nftdb.mysql.json"
this.PrimKey = ""
})
this.PayDb = f5.New(func(this *PayDbTable) {
this.FileName = "../config/paydb.mysql.json"
this.PrimKey = ""
@ -56,30 +46,13 @@ var Table = f5.New(func(this *table) {
this.PrimKey = ""
})
this.Item = f5.New(func(this *ItemTable) {
this.FileName = "../res/item@item.json"
this.PrimKey = "id"
this.Wxconfig = f5.New(func(this *WxconfigTable) {
this.FileName = "../res/wxconfig@wxconfig.json"
this.PrimKey = "gameid"
})
this.Language = f5.New(func(this *LanguageTable) {
this.FileName = "../res/language@language.json"
this.PrimKey = "info"
})
this.Web3ServiceCluster = f5.New(func(this *Web3ServiceClusterTable) {
this.FileName = "../config/web3service.cluster.json"
this.LoginRedis = f5.New(func(this *LoginRedisTable){
this.FileName = "../config/login.redis.json"
this.PrimKey = ""
})
this.Web3SignCluster = f5.New(func(this *Web3SignClusterTable) {
this.FileName = "../config/web3sign.cluster.json"
this.PrimKey = ""
})
this.Currency = new(CurrencyTable)
this.Recharge = f5.New(func(this *RechargeTable) {
this.FileName = "../res/recharge@recharge.json"
this.PrimKey = "id"
})
})

View File

@ -26,19 +26,6 @@ type AccountDb struct {
_flags2_ uint64
}
type NftDb struct {
host string
port int32
user string
passwd string
database string
max_open_conns int32
max_idle_conns int32
_flags1_ uint64
_flags2_ uint64
}
type PayDb struct {
host string
port int32
@ -80,7 +67,7 @@ type ConfDb struct {
type Config struct {
gameapi_url string
jwks_uri string
wx_url string
_flags1_ uint64
_flags2_ uint64
@ -125,30 +112,24 @@ type Recharge struct {
_flags2_ uint64
}
type Web3ServiceCluster struct {
url string
type Wxconfig struct {
gameid int64
appid string
appkey string
zoneid string
offerid string
_flags1_ uint64
_flags2_ uint64
}
type Web3SignCluster struct {
url string
_flags1_ uint64
_flags2_ uint64
}
type StakingVip struct {
rights string
require int64
thisPoint int64
rank int32
vip_name string
rate float64
vip_working_tips string
vip_unworking_tips string
id int32
type LoginRedis struct {
host string
port int32
passwd string
database int32
max_open_conns int32
max_idle_conns int32
_flags1_ uint64
_flags2_ uint64
@ -234,62 +215,6 @@ func (this *AccountDb) HasMaxIdleConns() bool {
return (this._flags1_ & (uint64(1) << 7)) > 0
}
func (this *NftDb) GetHost() string {
return this.host
}
func (this *NftDb) HasHost() bool {
return (this._flags1_ & (uint64(1) << 1)) > 0
}
func (this *NftDb) GetPort() int32 {
return this.port
}
func (this *NftDb) HasPort() bool {
return (this._flags1_ & (uint64(1) << 2)) > 0
}
func (this *NftDb) GetUser() string {
return this.user
}
func (this *NftDb) HasUser() bool {
return (this._flags1_ & (uint64(1) << 3)) > 0
}
func (this *NftDb) GetPasswd() string {
return this.passwd
}
func (this *NftDb) HasPasswd() bool {
return (this._flags1_ & (uint64(1) << 4)) > 0
}
func (this *NftDb) GetDatabase() string {
return this.database
}
func (this *NftDb) HasDatabase() bool {
return (this._flags1_ & (uint64(1) << 5)) > 0
}
func (this *NftDb) GetMaxOpenConns() int32 {
return this.max_open_conns
}
func (this *NftDb) HasMaxOpenConns() bool {
return (this._flags1_ & (uint64(1) << 6)) > 0
}
func (this *NftDb) GetMaxIdleConns() int32 {
return this.max_idle_conns
}
func (this *NftDb) HasMaxIdleConns() bool {
return (this._flags1_ & (uint64(1) << 7)) > 0
}
func (this *PayDb) GetHost() string {
return this.host
}
@ -466,11 +391,11 @@ func (this *Config) HasGameapiUrl() bool {
return (this._flags1_ & (uint64(1) << 1)) > 0
}
func (this *Config) GetJwksUri() string {
return this.jwks_uri
func (this *Config) GetWxUrl() string {
return this.wx_url
}
func (this *Config) HasJwksUri() bool {
func (this *Config) HasWxUrl() bool {
return (this._flags1_ & (uint64(1) << 2)) > 0
}
@ -594,94 +519,94 @@ func (this *Recharge) HasCanEmailBuy() bool {
return (this._flags1_ & (uint64(1) << 6)) > 0
}
func (this *Web3ServiceCluster) GetUrl() string {
return this.url
func (this *Wxconfig) GetGameid() int64 {
return this.gameid
}
func (this *Web3ServiceCluster) HasUrl() bool {
func (this *Wxconfig) HasGameid() bool {
return (this._flags1_ & (uint64(1) << 1)) > 0
}
func (this *Web3SignCluster) GetUrl() string {
return this.url
func (this *Wxconfig) GetAppid() string {
return this.appid
}
func (this *Web3SignCluster) HasUrl() bool {
return (this._flags1_ & (uint64(1) << 1)) > 0
}
func (this *StakingVip) GetRights() string {
return this.rights
}
func (this *StakingVip) HasRights() bool {
return (this._flags1_ & (uint64(1) << 1)) > 0
}
func (this *StakingVip) GetRequire() int64 {
return this.require
}
func (this *StakingVip) HasRequire() bool {
func (this *Wxconfig) HasAppid() bool {
return (this._flags1_ & (uint64(1) << 2)) > 0
}
func (this *StakingVip) GetThisPoint() int64 {
return this.thisPoint
func (this *Wxconfig) GetAppkey() string {
return this.appkey
}
func (this *StakingVip) HasThisPoint() bool {
func (this *Wxconfig) HasAppkey() bool {
return (this._flags1_ & (uint64(1) << 3)) > 0
}
func (this *StakingVip) GetRank() int32 {
return this.rank
func (this *Wxconfig) GetZoneid() string {
return this.zoneid
}
func (this *StakingVip) HasRank() bool {
func (this *Wxconfig) HasZoneid() bool {
return (this._flags1_ & (uint64(1) << 4)) > 0
}
func (this *StakingVip) GetVipName() string {
return this.vip_name
func (this *Wxconfig) GetOfferid() string {
return this.offerid
}
func (this *StakingVip) HasVipName() bool {
func (this *Wxconfig) HasOfferid() bool {
return (this._flags1_ & (uint64(1) << 5)) > 0
}
func (this *StakingVip) GetRate() float64 {
return this.rate
func (this *LoginRedis) GetHost() string {
return this.host
}
func (this *StakingVip) HasRate() bool {
func (this *LoginRedis) HasHost() bool {
return (this._flags1_ & (uint64(1) << 1)) > 0
}
func (this *LoginRedis) GetPort() int32 {
return this.port
}
func (this *LoginRedis) HasPort() bool {
return (this._flags1_ & (uint64(1) << 2)) > 0
}
func (this *LoginRedis) GetPasswd() string {
return this.passwd
}
func (this *LoginRedis) HasPasswd() bool {
return (this._flags1_ & (uint64(1) << 3)) > 0
}
func (this *LoginRedis) GetDatabase() int32 {
return this.database
}
func (this *LoginRedis) HasDatabase() bool {
return (this._flags1_ & (uint64(1) << 4)) > 0
}
func (this *LoginRedis) GetMaxOpenConns() int32 {
return this.max_open_conns
}
func (this *LoginRedis) HasMaxOpenConns() bool {
return (this._flags1_ & (uint64(1) << 5)) > 0
}
func (this *LoginRedis) GetMaxIdleConns() int32 {
return this.max_idle_conns
}
func (this *LoginRedis) HasMaxIdleConns() bool {
return (this._flags1_ & (uint64(1) << 6)) > 0
}
func (this *StakingVip) GetVipWorkingTips() string {
return this.vip_working_tips
}
func (this *StakingVip) HasVipWorkingTips() bool {
return (this._flags1_ & (uint64(1) << 7)) > 0
}
func (this *StakingVip) GetVipUnworkingTips() string {
return this.vip_unworking_tips
}
func (this *StakingVip) HasVipUnworkingTips() bool {
return (this._flags1_ & (uint64(1) << 8)) > 0
}
func (this *StakingVip) GetId() int32 {
return this.id
}
func (this *StakingVip) HasId() bool {
return (this._flags1_ & (uint64(1) << 9)) > 0
}
func (this *PayServerCluster) LoadFromKv(kv map[string]interface{}) {
f5.ReadMetaTableField(&this.instance_id, "instance_id", &this._flags1_, 1, kv)
@ -699,16 +624,6 @@ func (this *AccountDb) LoadFromKv(kv map[string]interface{}) {
f5.ReadMetaTableField(&this.max_idle_conns, "max_idle_conns", &this._flags1_, 7, kv)
}
func (this *NftDb) LoadFromKv(kv map[string]interface{}) {
f5.ReadMetaTableField(&this.host, "host", &this._flags1_, 1, kv)
f5.ReadMetaTableField(&this.port, "port", &this._flags1_, 2, kv)
f5.ReadMetaTableField(&this.user, "user", &this._flags1_, 3, kv)
f5.ReadMetaTableField(&this.passwd, "passwd", &this._flags1_, 4, kv)
f5.ReadMetaTableField(&this.database, "database", &this._flags1_, 5, kv)
f5.ReadMetaTableField(&this.max_open_conns, "max_open_conns", &this._flags1_, 6, kv)
f5.ReadMetaTableField(&this.max_idle_conns, "max_idle_conns", &this._flags1_, 7, kv)
}
func (this *PayDb) LoadFromKv(kv map[string]interface{}) {
f5.ReadMetaTableField(&this.host, "host", &this._flags1_, 1, kv)
f5.ReadMetaTableField(&this.port, "port", &this._flags1_, 2, kv)
@ -741,7 +656,7 @@ func (this *ConfDb) LoadFromKv(kv map[string]interface{}) {
func (this *Config) LoadFromKv(kv map[string]interface{}) {
f5.ReadMetaTableField(&this.gameapi_url, "gameapi_url", &this._flags1_, 1, kv)
f5.ReadMetaTableField(&this.jwks_uri, "jwks_uri", &this._flags1_, 2, kv)
f5.ReadMetaTableField(&this.wx_url, "wx_url", &this._flags1_, 2, kv)
}
func (this *RechargeCurrency) LoadFromKv(kv map[string]interface{}) {
@ -771,22 +686,19 @@ func (this *Recharge) LoadFromKv(kv map[string]interface{}) {
f5.ReadMetaTableField(&this.can_email_buy, "can_email_buy", &this._flags1_, 6, kv)
}
func (this *Web3ServiceCluster) LoadFromKv(kv map[string]interface{}) {
f5.ReadMetaTableField(&this.url, "url", &this._flags1_, 1, kv)
func (this *Wxconfig) LoadFromKv(kv map[string]interface{}) {
f5.ReadMetaTableField(&this.gameid, "gameid", &this._flags1_, 1, kv)
f5.ReadMetaTableField(&this.appid, "appid", &this._flags1_, 2, kv)
f5.ReadMetaTableField(&this.appkey, "appkey", &this._flags1_, 3, kv)
f5.ReadMetaTableField(&this.zoneid, "zoneid", &this._flags1_, 4, kv)
f5.ReadMetaTableField(&this.offerid, "offerid", &this._flags1_, 5, kv)
}
func (this *Web3SignCluster) LoadFromKv(kv map[string]interface{}) {
f5.ReadMetaTableField(&this.url, "url", &this._flags1_, 1, kv)
}
func (this *StakingVip) LoadFromKv(kv map[string]interface{}) {
f5.ReadMetaTableField(&this.rights, "rights", &this._flags1_, 1, kv)
f5.ReadMetaTableField(&this.require, "require", &this._flags1_, 2, kv)
f5.ReadMetaTableField(&this.thisPoint, "thisPoint", &this._flags1_, 3, kv)
f5.ReadMetaTableField(&this.rank, "rank", &this._flags1_, 4, kv)
f5.ReadMetaTableField(&this.vip_name, "vip_name", &this._flags1_, 5, kv)
f5.ReadMetaTableField(&this.rate, "rate", &this._flags1_, 6, kv)
f5.ReadMetaTableField(&this.vip_working_tips, "vip_working_tips", &this._flags1_, 7, kv)
f5.ReadMetaTableField(&this.vip_unworking_tips, "vip_unworking_tips", &this._flags1_, 8, kv)
f5.ReadMetaTableField(&this.id, "id", &this._flags1_, 9, kv)
func (this *LoginRedis) LoadFromKv(kv map[string]interface{}) {
f5.ReadMetaTableField(&this.host, "host", &this._flags1_, 1, kv)
f5.ReadMetaTableField(&this.port, "port", &this._flags1_, 2, kv)
f5.ReadMetaTableField(&this.passwd, "passwd", &this._flags1_, 3, kv)
f5.ReadMetaTableField(&this.database, "database", &this._flags1_, 4, kv)
f5.ReadMetaTableField(&this.max_open_conns, "max_open_conns", &this._flags1_, 5, kv)
f5.ReadMetaTableField(&this.max_idle_conns, "max_idle_conns", &this._flags1_, 6, kv)
}

View File

@ -20,17 +20,6 @@ message AccountDb
optional int32 max_idle_conns = 7;
}
message NftDb
{
optional string host = 1;
optional int32 port = 2;
optional string user = 3;
optional string passwd = 4;
optional string database = 5;
optional int32 max_open_conns = 6;
optional int32 max_idle_conns = 7;
}
message PayDb
{
optional string host = 1;
@ -67,7 +56,7 @@ message ConfDb
message Config
{
optional string gameapi_url = 1;
optional string jwks_uri = 2;
optional string wx_url = 2;
}
message RechargeCurrency
@ -101,25 +90,21 @@ message Recharge
optional int32 can_email_buy = 6;
}
message Web3ServiceCluster
message Wxconfig
{
optional string url = 1;
optional int64 gameid = 1;
optional string appid = 2;
optional string appkey = 3;
optional string zoneid = 4;
optional string offerid = 5;
}
message Web3SignCluster
message LoginRedis
{
optional string url = 1;
}
message StakingVip
{
optional string rights = 1;
optional int64 require = 2;
optional int64 thisPoint = 3;
optional int32 rank = 4;
optional string vip_name = 5;
optional double rate = 6;
optional string vip_working_tips = 7;
optional string vip_unworking_tips = 8;
optional int32 id = 9;
optional string host = 1;
optional int32 port = 2;
optional string passwd = 3;
optional int32 database = 4;
optional int32 max_open_conns = 5;
optional int32 max_idle_conns = 6;
}

View File

@ -1,14 +0,0 @@
package activity
import (
"f5"
v1 "main/api/v1"
)
type BitGetRouter struct{}
func (this *BitGetRouter) InitRouter() {
api := v1.ApiGroupApp.ActivityApiGroup
f5.GetApp().GetGinEngine().GET("/api/activity/bitget/mission/newuser/progress",
api.BitGetApi.NewUserMission)
}

View File

@ -1,16 +0,0 @@
package activity
import (
"f5"
v1 "main/api/v1"
)
type ContributionRouter struct{}
func (this *ContributionRouter) InitRouter() {
api := v1.ApiGroupApp.ActivityApiGroup
f5.GetApp().GetGinEngine().GET("api/activity/contribution/history/:account_address",
api.ContriApi.HistoryQuery)
f5.GetApp().GetGinEngine().GET("/api/activity/cec/contribution/:account_address",
api.ContriApi.CECQuery)
}

View File

@ -1,6 +0,0 @@
package activity
type RouterGroup struct {
BitGetRouter
ContributionRouter
}

View File

@ -1,14 +0,0 @@
package asset
import (
"f5"
"main/api/v1"
)
type AssetRouter struct{}
func (this *AssetRouter) InitRouter() {
api := v1.ApiGroupApp.AssetApiGroup
f5.GetApp().GetGinEngine().GET("/api/asset/:net_id/:account_address", api.AssetApi.AccountAsset)
f5.GetApp().GetGinEngine().GET("/api/listing/:net_id/:account_address", api.AssetApi.Listing)
}

View File

@ -1,5 +0,0 @@
package asset
type RouterGroup struct {
AssetRouter
}

View File

@ -1,5 +0,0 @@
package event
type RouterGroup struct {
EventRouter
}

View File

@ -1,14 +0,0 @@
package event
import (
"f5"
v1 "main/api/v1"
)
type EventRouter struct{}
func (er *EventRouter) InitRouter() {
api := v1.ApiGroupApp.EventApiGroup
f5.GetApp().GetGinEngine().GET("/api/chain/txhash/:net_id/:txhash", api.EventApi.TxQuery)
f5.GetApp().GetGinEngine().POST("/api/chain/event/activity/:account_address", api.EventApi.ActivityQuery)
}

View File

@ -1,5 +0,0 @@
package game_switch
type RouterGroup struct {
GameSwitchRouter
}

View File

@ -1,13 +0,0 @@
package game_switch
import (
"f5"
v1 "main/api/v1"
)
type GameSwitchRouter struct{}
func (this *GameSwitchRouter) InitRouter() {
api := v1.ApiGroupApp.SwitchApiGroup
f5.GetApp().GetGinEngine().GET("/api/server_switch", api.GameSwitchApi.List)
}

View File

@ -1,5 +0,0 @@
package gold_bullion
type RouterGroup struct {
GoldBullionRouter
}

View File

@ -1,13 +0,0 @@
package gold_bullion
import (
//"f5"
//"main/api/v1"
)
type GoldBullionRouter struct{}
func (this *GoldBullionRouter) InitRouter() {
//api := v1.ApiGroupApp.GoldBullionApiGroup
// f5.GetApp().GetGinEngine().POST("/api/gold_bullion/use/:net_id", api.GoldBullionApi.Use)
}

View File

@ -1,5 +0,0 @@
package hero
type RouterGroup struct {
HeroRouter
}

View File

@ -1,13 +0,0 @@
package hero
import (
//"f5"
//"main/api/v1"
)
type HeroRouter struct{}
func (this *HeroRouter) InitRouter() {
//api := v1.ApiGroupApp.HeroApiGroup
//f5.GetApp().GetGinEngine().POST("/api/hero/use/:net_id", api.HeroApi.Use)
}

View File

@ -1,5 +0,0 @@
package market
type RouterGroup struct {
MarketRouter
}

View File

@ -1,26 +0,0 @@
package market
import (
"f5"
v1 "main/api/v1"
"main/middleware"
)
type MarketRouter struct{}
func (this *MarketRouter) InitRouter() {
api := v1.ApiGroupApp.MarketApiGroup
f5.GetApp().GetGinEngine().POST("/api/market/product/list/:net_id",
middleware.MaybeJwtAuth,
api.MarketApi.ProductList)
f5.GetApp().GetGinEngine().POST("/api/market/product1/list/:net_id",
middleware.MaybeJwtAuth,
api.MarketApi.ProductList1)
f5.GetApp().GetGinEngine().GET("/api/market/transaction/history/:net_id/:account_address",
api.MarketApi.TransactionHistory)
f5.GetApp().GetGinEngine().GET("/api/market/product/category/:net_id", api.MarketApi.CategoryGoodsNum)
f5.GetApp().GetGinEngine().GET("/api/market/product/query_price", api.MarketApi.QueryPrice)
f5.GetApp().GetGinEngine().GET("/api/market/product/goods/:net_id/:contract_address/:token_id",
middleware.MaybeJwtAuth,
api.MarketApi.Goods)
}

View File

@ -1,5 +0,0 @@
package recharge
type RouterGroup struct {
RechargeRouter
}

View File

@ -1,17 +0,0 @@
package recharge
import (
"f5"
v1 "main/api/v1"
"main/middleware"
)
type RechargeRouter struct{}
func (er *RechargeRouter) InitRouter() {
api := v1.ApiGroupApp.RechargeApiGroup
f5.GetApp().GetGinEngine().POST("/api/recharge/history/:net_id/:account_address", api.RechargeApi.RechargeQuery)
f5.GetApp().GetGinEngine().GET("/api/recharge/goods", api.RechargeApi.RechargeList)
f5.GetApp().GetGinEngine().POST("/api/recharge/buy", middleware.JwtAuth, api.RechargeApi.Buy)
f5.GetApp().GetGinEngine().POST("/api/recharge/buy_with_email", middleware.JwtAuth, api.RechargeApi.BuyWithEmail)
}

View File

@ -3,50 +3,16 @@ package router
import (
"f5"
"main/middleware"
"main/router/activity"
"main/router/asset"
"main/router/event"
"main/router/game_switch"
"main/router/gold_bullion"
"main/router/hero"
"main/router/ingame"
"main/router/market"
"main/router/recharge"
"main/router/shopcart"
"main/router/user"
"main/router/vip"
)
type routerMgr struct {
market market.RouterGroup
asset asset.RouterGroup
hero hero.RouterGroup
goldBullion gold_bullion.RouterGroup
shopCart shopcart.RouterGroup
ingame ingame.RouterGroup
user user.RouterGroup
activity activity.RouterGroup
event event.RouterGroup
recharge recharge.RouterGroup
gameswitch game_switch.RouterGroup
vip vip.RouterGroup
}
func (this *routerMgr) Init() {
f5.GetApp().GetGinEngine().Use(middleware.Cors())
this.market.MarketRouter.InitRouter()
this.asset.AssetRouter.InitRouter()
this.hero.HeroRouter.InitRouter()
this.goldBullion.GoldBullionRouter.InitRouter()
this.shopCart.ShopCartRouter.InitRouter()
this.ingame.IngameRouter.InitRouter()
this.user.UserRouter.InitRouter()
this.activity.BitGetRouter.InitRouter()
this.activity.ContributionRouter.InitRouter()
this.event.EventRouter.InitRouter()
this.recharge.RechargeRouter.InitRouter()
this.gameswitch.GameSwitchRouter.InitRouter()
this.vip.InitRouter()
f5.GetSysLog().Info("routerMgr.init")

View File

@ -1,5 +0,0 @@
package shopcart
type RouterGroup struct {
ShopCartRouter
}

View File

@ -1,19 +0,0 @@
package shopcart
import (
"f5"
"main/api/v1"
"main/middleware"
)
type ShopCartRouter struct{}
func (this *ShopCartRouter) InitRouter() {
api := v1.ApiGroupApp.ShopCartApiGroup
shopCartGroup := f5.GetApp().GetGinEngine().Group("/api/shopcart")
shopCartGroup.Use(middleware.JwtAuth)
shopCartGroup.GET("/list", api.ShopCartApi.List)
shopCartGroup.POST("/add", api.ShopCartApi.Add)
shopCartGroup.POST("/del", api.ShopCartApi.Del)
shopCartGroup.POST("/clear", api.ShopCartApi.Clear)
}

View File

@ -1,5 +0,0 @@
package user
type RouterGroup struct {
UserRouter
}

View File

@ -1,16 +0,0 @@
package user
import (
"f5"
"main/middleware"
"main/api/v1"
)
type UserRouter struct{}
func (this *UserRouter) InitRouter() {
api := v1.ApiGroupApp.UserApiGroup
f5.GetApp().GetGinEngine().GET("/api/user/:account_address",
middleware.MaybeJwtAuth,
api.UserApi.Info)
}

View File

@ -1,5 +0,0 @@
package vip
type RouterGroup struct {
VIPRouter
}

View File

@ -1,22 +0,0 @@
package vip
import (
"f5"
v1 "main/api/v1"
"main/middleware"
)
type VIPRouter struct{}
func (this *VIPRouter) InitRouter() {
api := v1.ApiGroupApp.VIPApiGroup
f5.GetApp().GetGinEngine().GET("/api/vip/info",
middleware.JwtAuth,
api.VIPApi.Info)
f5.GetApp().GetGinEngine().POST("/api/vip/bind",
middleware.JwtAuth,
api.VIPApi.Bind)
f5.GetApp().GetGinEngine().GET("/api/vip/details",
middleware.JwtAuth,
api.VIPApi.Details)
}

View File

@ -1,341 +0,0 @@
package service
import (
"f5"
"fmt"
"main/constant"
"q5"
"time"
)
type accountContribution struct {
history float64
stakingContri float64
gamecontribution float64
rechargeContri float64
gcTime int64
loweremail string
accountid string
}
func (ac *accountContribution) sum() float64 {
return ac.history + ac.stakingContri + ac.gamecontribution + ac.rechargeContri
}
type contribution struct {
historyContribution float64
stakingContribution float64
rechargeContribution float64
gameContribution float64
gcTime int64
accountContributionlist q5.ConcurrentMap[string, *accountContribution]
emailContributionlist q5.ConcurrentMap[string, *accountContribution]
}
func (this *contribution) init() {
this.accountContributionlist = q5.ConcurrentMap[string, *accountContribution]{}
this.emailContributionlist = q5.ConcurrentMap[string, *accountContribution]{}
this.GetGlobalContribution(true)
go this.checkContributionList()
}
func (this *contribution) unInit() {
}
func (c *contribution) sum() float64 {
return c.historyContribution + c.stakingContribution + c.rechargeContribution + c.gameContribution
}
func (this *contribution) GetEmailContributionAccountid(email string) (float64, string, error) {
info, exist := this.emailContributionlist.Load(email)
if exist {
return (*info).sum(), (*info).accountid, nil
}
accountid := ""
accountAddress := ""
sql := `SELECT account_id, address FROM t_immutable_account WHERE idx > 0 AND lower_case_email = ?`
f5.GetGoStyleDb().RawQuery(
constant.ACCOUNT_DB,
sql,
[]string{email},
func(err error, ds *f5.DataSet) {
if err != nil {
return
}
if ds.Next() {
accountid = ds.GetByIndex(0)
accountAddress = ds.GetByIndex(1)
}
})
if accountAddress != "" {
contrinfo := new(accountContribution)
contrinfo.loweremail = email
contrinfo.accountid = accountid
this.accountContributionlist.Store(accountAddress, contrinfo)
contri, _ := this.GetAddressContribution(accountAddress, false)
return contri, accountid, nil
}
return 0, accountid, nil
}
func (this *contribution) GetEmailAccountId(accountAddress string) (string, string) {
accinfo, exist := this.accountContributionlist.Load(accountAddress)
if exist {
return (*accinfo).loweremail, (*accinfo).accountid
}
return "", ""
}
func (this *contribution) GetAddressContribution(accountAddress string, onlyrecharge bool) (float64, error) {
if accountAddress == "" {
return 0, fmt.Errorf("empty account")
}
accinfo, exist := this.accountContributionlist.Load(accountAddress)
var beforcontribution float64 = 0
if exist {
beforcontribution = (*accinfo).sum()
}
if nowseconds := f5.GetApp().GetRealSeconds(); !exist || (*accinfo).gcTime+60 < nowseconds {
if !exist {
info := new(accountContribution)
this.accountContributionlist.Store(accountAddress, info)
accinfo = &info
}
beforcontribution = (*accinfo).sum()
if (*accinfo).loweremail == "" {
sql := `SELECT account_id FROM t_user WHERE idx > 0 AND address = ?`
f5.GetGoStyleDb().RawQuery(
constant.GAME_DB,
sql,
[]string{accountAddress},
func(err error, ds *f5.DataSet) {
if err != nil {
return
}
if ds.Next() {
(*accinfo).accountid = ds.GetByIndex(0)
}
})
if (*accinfo).accountid != "" {
sql := `SELECT lower_case_email FROM t_immutable_account WHERE idx > 0 AND account_id = ?`
f5.GetGoStyleDb().RawQuery(
constant.ACCOUNT_DB,
sql,
[]string{(*accinfo).accountid},
func(err error, ds *f5.DataSet) {
if err != nil {
return
}
if ds.Next() {
(*accinfo).loweremail = ds.GetByIndex(0)
}
})
}
if (*accinfo).loweremail != "" {
this.emailContributionlist.Store((*accinfo).loweremail, *accinfo)
}
}
{
sql := `SELECT contribution FROM t_contribution WHERE idx > 0 and account_address = ?`
f5.GetGoStyleDb().RawQuery(
constant.BCNFT_DB,
sql,
[]string{accountAddress},
func(err error, ds *f5.DataSet) {
if err != nil {
return
}
if ds.Next() {
(*accinfo).history, _ = q5.ToFloat64Ex(ds.GetByIndex(0))
}
})
sql = `SELECT SUM(contribution) FROM t_staking_daily_settlement WHERE idx > 0 and account_address = ?`
f5.GetGoStyleDb().RawQuery(
constant.BCNFT_DB,
sql,
[]string{accountAddress},
func(err error, ds *f5.DataSet) {
if err != nil {
return
}
if ds.Next() {
(*accinfo).stakingContri, _ = q5.ToFloat64Ex(ds.GetByIndex(0))
}
})
}
if (*accinfo).accountid != "" {
sql := `SELECT contribution FROM t_contribution WHERE idx > 0 AND account_id = ?`
f5.GetGoStyleDb().RawQuery(
constant.GAME_DB,
sql,
[]string{(*accinfo).accountid},
func(err error, ds *f5.DataSet) {
if err != nil {
return
}
if ds.Next() {
(*accinfo).gamecontribution, _ = q5.ToFloat64Ex(ds.GetByIndex(0))
}
})
}
{
params := []string{accountAddress}
sql := `SELECT SUM(return_contribution) FROM t_recharge_return_contribution WHERE idx > 0 AND user_identity IN (?`
if (*accinfo).loweremail != "" {
sql += ", ?"
params = append(params, (*accinfo).loweremail)
}
sql += ")"
f5.GetGoStyleDb().RawQuery(
constant.BCNFT_DB,
sql,
params,
func(err error, ds *f5.DataSet) {
if err != nil {
return
}
if ds.Next() {
(*accinfo).rechargeContri, _ = q5.ToFloat64Ex(ds.GetByIndex(0))
}
})
}
(*accinfo).gcTime = nowseconds
}
if beforcontribution > 0.000001 && (*accinfo).sum() > beforcontribution+0.000001 {
this.GetGlobalContribution(true)
}
if onlyrecharge {
return (*accinfo).rechargeContri, nil
}
return (*accinfo).sum(), nil
}
func (this *contribution) GetGlobalContribution(instant bool) (float64, error) {
if this.historyContribution < 0.000001 {
sql := `SELECT SUM(contribution) FROM t_contribution WHERE idx > 0`
f5.GetGoStyleDb().RawQuery(
constant.BCNFT_DB,
sql,
[]string{},
func(err error, ds *f5.DataSet) {
if err != nil {
return
}
if ds.Next() {
this.historyContribution, _ = q5.ToFloat64Ex(ds.GetByIndex(0))
}
})
}
if nowseconds := f5.GetApp().GetRealSeconds(); nowseconds > this.gcTime+60 || instant {
sql := `SELECT SUM(contribution) FROM t_staking_daily_settlement WHERE idx > 0`
f5.GetGoStyleDb().RawQuery(
constant.BCNFT_DB,
sql,
[]string{},
func(err error, ds *f5.DataSet) {
if err != nil {
return
}
if ds.Next() {
this.stakingContribution, _ = q5.ToFloat64Ex(ds.GetByIndex(0))
}
})
sql = `SELECT SUM(contribution) FROM t_contribution WHERE idx > 0`
f5.GetGoStyleDb().RawQuery(
constant.GAME_DB,
sql,
[]string{},
func(err error, ds *f5.DataSet) {
if err != nil {
return
}
if ds.Next() {
this.gameContribution, _ = q5.ToFloat64Ex(ds.GetByIndex(0))
}
})
sql = `SELECT SUM(return_contribution) FROM t_recharge_return_contribution WHERE idx > 0`
f5.GetGoStyleDb().RawQuery(
constant.BCNFT_DB,
sql,
[]string{},
func(err error, ds *f5.DataSet) {
if err != nil {
return
}
if ds.Next() {
this.rechargeContribution, _ = q5.ToFloat64Ex(ds.GetByIndex(0))
}
})
this.gcTime = nowseconds
}
return this.sum(), nil
}
func (this *contribution) checkContributionList() {
fmt.Println("checkContributionList start")
for {
if time.Now().UTC().Hour() == 0 && time.Now().UTC().Minute() == 0 {
nowseconds := f5.GetApp().GetRealSeconds()
deletelist := []string{}
this.accountContributionlist.Range(func(key string, value *accountContribution) bool {
if value.gcTime+86400 < nowseconds {
deletelist = append(deletelist, key)
}
return true
})
for _, account := range deletelist {
v, _ := this.accountContributionlist.Load(account)
if (*v).loweremail != "" {
this.emailContributionlist.Delete((*v).loweremail)
}
this.accountContributionlist.Delete(account)
}
f5.GetSysLog().Info("delete contribution address cache count:%d", len(deletelist))
}
f5.GetSysLog().Info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
f5.GetSysLog().Info("contribution cache total:%.2f, recharge:%.2f, ingame:%.2f, history:%.2f",
this.sum(),
this.rechargeContribution,
this.gameContribution,
this.historyContribution)
f5.GetSysLog().Info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
time.Sleep((time.Second * 60))
}
}

View File

@ -5,11 +5,9 @@ import (
"main/global"
)
var Contribution = new(contribution)
var _serviceMgr = new(serviceMgr)
var GameSwitches = new(gameSwitch)
var User = new(user)
var JwtAuth = new(jwtauth)
var Wxpay = new(wxpay)
var Redis = new(redisMap)
func init() {
global.RegModule(constant.SERVICE_MGR_MODULE_IDX, _serviceMgr)

View File

@ -1,52 +0,0 @@
package service
import (
"f5"
"main/constant"
"q5"
)
type gameSwitch struct {
data map[string]int32
time int64
}
func (this *gameSwitch) init() {
this.GetSwitchList()
}
func (this *gameSwitch) unInit() {
}
func (this *gameSwitch) GetSwitchList() map[string]int32 {
now := f5.GetApp().GetRealSeconds()
if now > this.time+30 {
this.data = map[string]int32{}
this.time = now
f5.GetGoStyleDb().RawQuery(
constant.CONF_DB,
"SELECT * FROM t_game_switch WHERE 1=1",
[]string{},
func(err error, ds *f5.DataSet) {
if err != nil {
return
}
for ds.Next() {
this.data[ds.GetByName("switch_name")] = q5.SafeToInt32(ds.GetByName("is_open"))
}
})
}
return this.data
}
func (this *gameSwitch) CheckSwitch(gs string) int32 {
v, exist := this.data[gs]
if exist {
return v
}
return 0
}

View File

@ -1,149 +0,0 @@
package service
import (
"f5"
"fmt"
"jccommon"
"main/constant"
"main/mt"
"q5"
"strings"
)
type jwtauth struct {
}
func (this *jwtauth) init() {
}
func (this *jwtauth) unInit() {
}
func (this *jwtauth) JwtAuthHandle(srcToken string, rspinfo *map[string]interface{}, jwtType int32) {
jwtToken := ""
if len(srcToken) > 8 {
jwtToken = srcToken[7:]
}
tmpStrings := q5.StrSplit(jwtToken, ".")
if len(tmpStrings) > 3 {
if jwtType == constant.JWT_METAMAST {
this.internalMetaMaskJwtAuth(jwtToken, rspinfo)
}
} else {
if jwtType == constant.JWT_PASSPORT {
this.internalImmutJwtAuth(jwtToken, rspinfo)
}
}
}
func (this *jwtauth) internalImmutJwtAuth(jwtToken string, rspinfo *map[string]interface{}) {
params := map[string]string{
"c": "Jwt",
"a": "verify",
}
jsonReqObj := &struct {
JwksUri string `json:"jwksUri"`
Data string `json:"data"`
}{
JwksUri: mt.Table.Config.GetJwksUri(),
Data: jwtToken,
}
jsonRspObj := &struct {
ErrCode interface{} `json:"errcode"`
ErrMsg string `json:"errmsg"`
Decoded struct {
Sub string `json:"sub"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Sid string `json:"sid"`
Passport struct {
ZkevmEthAddress string `json:"zkevm_eth_address"`
} `json:"passport"`
} `json:"decoded"`
}{}
rspObj := &struct {
ErrCode interface{} `json:"errcode"`
ErrMsg string `json:"errmsg"`
}{}
paramsStr := q5.EncodeJson(jsonReqObj)
url := fmt.Sprintf("%s/webapp/index.php", mt.Table.Web3ServiceCluster.RandElement().GetUrl())
f5.GetHttpCliMgr().SendGoStyleJsonRspPost(
url,
params,
jsonRspObj,
q5.HTTP_HEADER_JSON,
paramsStr,
func(rsp f5.HttpCliResponse) {
if rsp.GetErr() != nil ||
!rsp.JsonParseOk() {
return
}
rspObj.ErrCode = q5.SafeToInt32(jsonRspObj.ErrCode)
rspObj.ErrMsg = jsonRspObj.ErrMsg
if q5.SafeToInt32(rspObj.ErrCode) != 0 {
return
}
openId := fmt.Sprintf("%d_2006_%s", jccommon.IMTBL_CHANNEL, jsonRspObj.Decoded.Sub)
(*rspinfo)["open_id"] = openId
(*rspinfo)["account_address"] = jsonRspObj.Decoded.Passport.ZkevmEthAddress
(*rspinfo)["email"] = jsonRspObj.Decoded.Email
})
}
func (this *jwtauth) internalMetaMaskJwtAuth(jwtToken string, rspinfo *map[string]interface{}) {
params := map[string]string{
"c": "MetaMaskJwt",
"a": "verify",
}
jsonReqObj := &struct {
Data string `json:"data"`
}{
Data: jwtToken,
}
jsonRspObj := &struct {
ErrCode interface{} `json:"errcode"`
ErrMsg string `json:"errmsg"`
Decoded struct {
Id string `json:"id"`
OpenId string `json:"openid"`
Plat int32 `json:"plat"`
Version int32 `json:"version"`
Email string `json:"email"`
} `json:"decoded"`
}{}
rspObj := &struct {
ErrCode interface{} `json:"errcode"`
ErrMsg string `json:"errmsg"`
}{}
paramsStr := q5.EncodeJson(jsonReqObj)
url := fmt.Sprintf("%s/webapp/index.php", mt.Table.Web3ServiceCluster.RandElement().GetUrl())
f5.GetHttpCliMgr().SendGoStyleJsonRspPost(
url,
params,
jsonRspObj,
q5.HTTP_HEADER_JSON,
paramsStr,
func(rsp f5.HttpCliResponse) {
if rsp.GetErr() != nil ||
!rsp.JsonParseOk() {
return
}
rspObj.ErrCode = q5.SafeToInt32(jsonRspObj.ErrCode)
rspObj.ErrMsg = jsonRspObj.ErrMsg
if q5.SafeToInt32(rspObj.ErrCode) != 0 {
return
}
if jsonRspObj.Decoded.Plat != jccommon.BC_POLY_POLY_METAKASK {
f5.GetSysLog().Info("not support this platform:%s", rsp.GetRawData())
return
}
openId := fmt.Sprintf("%d_2006_%s",
jccommon.BC_CHANNEL,
strings.ToLower(jsonRspObj.Decoded.OpenId))
(*rspinfo)["open_id"] = openId
(*rspinfo)["account_address"] = strings.ToLower(jsonRspObj.Decoded.OpenId)
(*rspinfo)["email"] = strings.ToLower(jsonRspObj.Decoded.Email)
})
}

View File

@ -1,54 +0,0 @@
package service
import (
"q5"
"f5"
"strings"
"main/constant"
)
func AddRechargeOrder(orderId string, shortOrderId string,
netId int32, accountAddress string, passportAddress string,
currencyAddress string, currencyName string, itemId int32, itemNum int32,
price string, srcPrice int64, diamond int64, presentDiamond int64, email string) bool {
ok := false
nowTime := f5.GetApp().GetRealSeconds()
fields := [][]string{
{"order_id", orderId},
{"short_order_id", shortOrderId},
{"net_id", q5.ToString(netId)},
{"account_address", accountAddress},
{"passport_address", passportAddress},
{"currency_name", currencyName},
{"currency_address", currencyAddress},
{"item_id", q5.ToString(itemId)},
{"item_num", q5.ToString(itemNum)},
{"price", price},
{"diamond", q5.ToString(diamond)},
{"present_diamond", q5.ToString(presentDiamond)},
{"return_contribution", q5.ToString(srcPrice * 1)},
{"createtime", q5.ToString(nowTime)},
{"modifytime", q5.ToString(nowTime)},
}
if email != "" {
q5.AppendSlice(&fields, []string{"email", email})
q5.AppendSlice(&fields, []string{"lower_case_email", strings.ToLower(email)})
}
f5.GetGoStyleDb().UpsertEx(
constant.BCNFT_DB,
"t_recharge_order",
[][]string{
{"short_order_id", shortOrderId},
},
[][]string{
},
fields,
func (err error, lastInsertId int64, rowsAffected int64) {
ok = err == nil
},
func (ds* f5.DataSet) bool {
ok = false
return false
})
return ok
}

View File

@ -0,0 +1,79 @@
package service
import (
"errors"
"main/constant"
"main/mt"
"q5"
"time"
"github.com/gomodule/redigo/redis"
)
type redisMap struct {
pools map[string]*redis.Pool
}
func (rm *redisMap) init() {
rm.pools = map[string]*redis.Pool{}
rm.RegisterRedis(constant.LOGIN_REDIS,
mt.Table.LoginRedis.GetById(0).GetHost(),
mt.Table.LoginRedis.GetById(0).GetPort(),
mt.Table.LoginRedis.GetById(0).GetPasswd(),
mt.Table.LoginRedis.GetById(0).GetDatabase(),
mt.Table.LoginRedis.GetById(0).GetMaxOpenConns(),
mt.Table.LoginRedis.GetById(0).GetMaxIdleConns())
}
func (rm *redisMap) unInit() {
}
func (rm *redisMap) RegisterRedis(
name string,
host string,
port int32,
passwd string,
dataBase int32,
maxOpenConns int32,
maxIdleConns int32) {
pool := &redis.Pool{
MaxIdle: int(maxIdleConns),
MaxActive: int(maxOpenConns),
Dial: func() (redis.Conn, error) {
address := host + ":" + q5.SafeToString(port)
rc, err := redis.Dial(
"tcp",
address,
redis.DialPassword(passwd),
redis.DialDatabase(int(dataBase)))
if err != nil {
return nil, err
}
return rc, nil
},
IdleTimeout: time.Second,
Wait: true,
}
rm.pools[name] = pool
}
func (rm *redisMap) getConn(name string) redis.Conn {
pool, ret := rm.pools[name]
if !ret {
return nil
}
return (*pool).Get()
}
func (rm *redisMap) Get(name string, key string) (value string, err error) {
con := rm.getConn(name)
if con == nil {
return "", errors.New("")
}
defer con.Close()
return redis.String(con.Do("get", key))
}

View File

@ -4,13 +4,11 @@ type serviceMgr struct {
}
func (this *serviceMgr) Init() {
Contribution.init()
User.init()
GameSwitches.init()
Wxpay.init()
Redis.init()
}
func (this *serviceMgr) UnInit() {
Contribution.unInit()
User.unInit()
GameSwitches.unInit()
Wxpay.unInit()
Redis.unInit()
}

View File

@ -1,28 +0,0 @@
package service
import (
"q5"
"f5"
"main/constant"
"main/common"
)
func GetShopCartByOpenId(openId string) *common.ShopCart {
cartDb := common.NewShopCart()
f5.GetGoStyleDb().OrmSelectOne(
constant.BCNFT_DB,
"t_shopcart",
[][]string{
{"open_id", openId},
},
func (err error, ds* f5.DataSet) {
if err != nil {
return
}
if ds.Next() {
if q5.DecodeJson(ds.GetByName("data"), cartDb) == nil {
}
}
})
return cartDb
}

View File

@ -1,43 +0,0 @@
package service
import (
//"f5"
//"main/constant"
//"q5"
)
//"strings"
type user struct {
}
func (this *user) init() {
}
func (this *user) unInit() {
}
func (this *user) InBlackList(userIdentity string) (bool, error) {
return false, nil
/*
if userIdentity == "" {
return true, nil
}
var queryerr error
blocked := false
f5.GetGoStyleDb().RawQuery(
constant.CONF_DB,
"SELECT * FROM t_blockplayer WHERE 1=1 AND account_id = ?",
[]string{userIdentity},
func(err error, ds *f5.DataSet) {
if err != nil {
queryerr = err
return
}
blocked = ds.Next() && q5.SafeToInt32(ds.GetByName("blocked")) != 0 && q5.SafeToInt32(ds.GetByName("deleted")) == 0
})
return blocked, queryerr
*/
}

View File

@ -0,0 +1,259 @@
package service
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"f5"
"main/constant"
"main/mt"
"q5"
"strings"
)
type wxpay struct {
gamesGoods q5.ConcurrentMap[int64, map[int64]int64]
}
type WxQuery struct {
AccessToken string `json:"access_token"`
Signature string `json:"signature"`
SigMethod string `json:"sig_method"`
PaySig string `json:"pay_sig"`
}
type WxBalanceRsp struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
Balance int64 `json:"balance"`
GiftBalance int64 `json:"present_balance"`
SumSave int64 `json:"sum_save"`
SumGift int64 `json:"sum_present"`
SumBalance int64 `json:"sum_balance"`
SumCost int64 `json:"sum_cost"`
FirstSave bool `json:"first_save"`
}
type WxPayRsp struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
BillNo string `json:"bill_no"`
Balance int64 `json:"balance"`
UsedGift int64 `json:"used_present_amount"`
}
func (wp *wxpay) init() {
wp.gamesGoods = q5.ConcurrentMap[int64, map[int64]int64]{}
mt.Table.Wxconfig.Traverse(func(w *mt.Wxconfig) bool {
filename := "../res/gamegoods/" + q5.SafeToString(w.GetGameid()) + ".json"
str, err := f5.ReadJsonFile(filename)
if err != nil {
return true
}
data := []map[string]interface{}{}
if json.Unmarshal([]byte(str), &data) != nil {
f5.GetSysLog().Error("parse [%s] error.", filename)
} else {
gamegoods := map[int64]int64{}
for _, data := range data {
gamegoods[q5.SafeToInt64(data["id"])] = q5.SafeToInt64(data["count"])
}
wp.gamesGoods.Store(w.GetGameid(), gamegoods)
}
return true
})
}
func (wp *wxpay) unInit() {
}
func (wp *wxpay) GetGoodsCount(gameid int64, goodsid int64) (count int64, err error) {
goods, ok := wp.gamesGoods.Load(gameid)
if !ok {
return 0, errors.New("no game")
}
count, ok = (*goods)[goodsid]
if !ok {
return 0, errors.New("no goods")
}
return count, nil
}
func (wp *wxpay) QueryBalance(openid string, gameid int64, userip string, sessionkey string) (balance int64, wxerrcode int32, err error) {
cfg := mt.Table.Wxconfig.GetById(gameid)
postbody := struct {
OpenId string `json:"openid"`
OfferId string `json:"offer_id"`
Ts int64 `json:"ts"`
ZoneId string `json:"zone_id"`
Env int32 `json:"env"`
UserIp string `json:"user_ip"`
}{
OpenId: openid,
OfferId: cfg.GetOfferid(),
Ts: f5.GetApp().GetRealSeconds(),
ZoneId: cfg.GetZoneid(),
UserIp: userip,
}
if !f5.IsOnlineEnv() {
postbody.Env = 1
}
poststr := q5.EncodeJson(postbody)
queryuri := "/wxa/game/getbalance"
query := WxQuery{
AccessToken: "",
Signature: wp.genSHA256Signature(poststr, sessionkey),
SigMethod: "hmac_sha256",
PaySig: wp.genSHA256Signature(queryuri+"&"+poststr, cfg.GetAppkey()),
}
params := map[string]string{}
data, _ := json.Marshal(query)
json.Unmarshal(data, &params)
sendRequest := false
urls := mt.Table.Config.GetWxUrl()
for _, urlheader := range urls {
url := urlheader + queryuri
f5.GetHttpCliMgr().SendGoStylePost(
url,
params,
"Content-Type: application/json",
poststr,
func(rsp f5.HttpCliResponse) {
if rsp.GetErr() != nil {
}
sendRequest = true
rspJson := WxBalanceRsp{}
f5.GetSysLog().Debug("wx balance rsp:%s", rsp.GetRawData())
err = q5.DecodeJson(rsp.GetRawData(), &rspJson)
if err != nil {
return
}
wxerrcode = rspJson.ErrCode
switch rspJson.ErrCode {
case constant.WX_ERRCODE_OK:
balance = rspJson.Balance
case constant.WX_ERRCODE_BUSY:
sendRequest = false
case constant.WX_ERRCODE_SIGERR:
fallthrough
case constant.WX_ERRCODE_PAYSIGERR:
fallthrough
case constant.WX_ERRCODE_PARAMERR:
f5.GetSysLog().Info("err msg:%s", rspJson.ErrMsg)
}
})
if sendRequest {
break
}
}
return balance, wxerrcode, err
}
func (wp *wxpay) QueryPay(openid string, gameid int64, userip string, sessionkey string, amount int32, billno string) (wxerrcode int32) {
cfg := mt.Table.Wxconfig.GetById(gameid)
postbody := struct {
OpenId string `json:"openid"`
OfferId string `json:"offer_id"`
Ts int64 `json:"ts"`
ZoneId string `json:"zone_id"`
Env int32 `json:"env"`
UserIp string `json:"user_ip"`
Amount int32 `json:"amount"`
BillNo string `json:"bill_no"`
}{
OpenId: openid,
OfferId: cfg.GetOfferid(),
Ts: f5.GetApp().GetRealSeconds(),
ZoneId: cfg.GetZoneid(),
UserIp: userip,
Amount: amount,
BillNo: billno,
}
if !f5.IsOnlineEnv() {
postbody.Env = 1
}
poststr := q5.EncodeJson(postbody)
queryuri := "/wxa/game/pay"
query := WxQuery{
AccessToken: "",
Signature: wp.genSHA256Signature(poststr, sessionkey),
SigMethod: "hmac_sha256",
PaySig: wp.genSHA256Signature(queryuri+"&"+poststr, cfg.GetAppkey()),
}
params := map[string]string{}
data, _ := json.Marshal(query)
json.Unmarshal(data, &params)
sendRequest := false
urls := mt.Table.Config.GetWxUrl()
for _, urlheader := range urls {
url := urlheader + queryuri
f5.GetHttpCliMgr().SendGoStylePost(
url,
params,
"Content-Type: application/json",
poststr,
func(rsp f5.HttpCliResponse) {
if rsp.GetErr() != nil {
}
sendRequest = true
rspJson := WxPayRsp{}
f5.GetSysLog().Debug("wx pay rsp:%s", rsp.GetRawData())
err := q5.DecodeJson(rsp.GetRawData(), &rspJson)
if err != nil {
return
}
wxerrcode = rspJson.ErrCode
switch rspJson.ErrCode {
case constant.WX_ERRCODE_OK:
case constant.WX_ERRCODE_BUSY:
sendRequest = false
case constant.WX_ERRCODE_SIGERR:
fallthrough
case constant.WX_ERRCODE_PAYSIGERR:
fallthrough
case constant.WX_ERRCODE_SAMEBILLNO:
fallthrough
case constant.WX_ERRCODE_NOENOUGH:
fallthrough
case constant.WX_ERRCODE_SESSIONERR:
fallthrough
case constant.WX_ERRCODE_PARAMERR:
f5.GetSysLog().Info("err msg:%s", rspJson.ErrMsg)
}
})
if sendRequest {
break
}
}
return wxerrcode
}
func (wp *wxpay) genSHA256Signature(str string, key string) string {
mac := hmac.New(sha256.New, []byte(key))
_, _ = mac.Write([]byte(str))
return strings.ToLower(hex.EncodeToString(mac.Sum(nil)))
}