eos.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/pkg/errors"
  6. "github.com/sirupsen/logrus"
  7. "io/ioutil"
  8. "math/rand"
  9. "net/http"
  10. "net/url"
  11. "strconv"
  12. "strings"
  13. "time"
  14. )
  15. func Transfer(player string, starId int) (int64, error) {
  16. rand.Seed(time.Now().UnixNano())
  17. single := (rand.Intn(2) + 1) * 1000
  18. //total := toEOS(single * 10)
  19. total := single
  20. totalStr := toEOS(total)
  21. num := rand.Intn(23) + 75 // [75, 97]
  22. cmd := fmt.Sprintf("cleos -u %s transfer %s supstargames \"%s\" \"dice|%d|1|%d|%d\" -p %s -j", NET_HOST, player, totalStr, starId, num, single, player)
  23. logrus.WithField("command", cmd).Infof("execute command")
  24. output, errStr, err := ShellCmdTimeout(5, "/bin/sh", "-c", cmd)
  25. if err != nil {
  26. return 0, err
  27. }
  28. if len(errStr) > 0 && strings.Contains(errStr, "Error ") {
  29. return 0, errors.New(errStr)
  30. }
  31. trx := &TrxResp{}
  32. err = json.Unmarshal([]byte(output), trx)
  33. if err == nil { // 上报交易id
  34. gameReport(player, trx.TrxId, trx.Processed.BlockNum)
  35. }
  36. return int64(total), nil
  37. }
  38. func gameReport(player string, trxId string, blockNum int) {
  39. api := fmt.Sprintf("%s%s", API_HOST, "dice/gameReport")
  40. h := http.Client{}
  41. v := url.Values{}
  42. v.Add("player", player)
  43. v.Add("transaction_id", trxId)
  44. v.Add("block_num", strconv.Itoa(blockNum))
  45. resp, err := h.PostForm(api, v)
  46. if err != nil {
  47. logrus.WithField("error", err.Error()).Errorf("bot:%s, trxId:%s, blockNum:%d report request error", player, trxId, blockNum)
  48. }
  49. defer resp.Body.Close()
  50. b, _ := ioutil.ReadAll(resp.Body)
  51. respData := &Resp{}
  52. json.Unmarshal(b, respData)
  53. if respData.Result == 1 {
  54. logrus.Infof("bot:%s, trxId:%s, blockNum:%d report success", player, trxId, blockNum)
  55. } else {
  56. logrus.WithField("error", respData.Msg).Errorf("bot:%s, trxId:%s, blockNum:%d report report error", player, trxId, blockNum)
  57. }
  58. }
  59. func toEOS(num int) string {
  60. return fmt.Sprintf("%.4f EOS", float64(num)/10000)
  61. }
  62. type Account struct {
  63. Player string `json:"player"`
  64. StarId int `json:"star_id"`
  65. }
  66. type TrxResp struct {
  67. TrxId string `json:"transaction_id"`
  68. Processed Processed `json:"processed"`
  69. }
  70. type Processed struct {
  71. Id string `json:"id"`
  72. BlockNum int `json:"block_num"`
  73. }
  74. type Resp struct {
  75. Result int `json:"result"`
  76. Code int `json:"code"`
  77. Msg string `json:"msg"`
  78. }