eos.go 2.2 KB

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