actions.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import NP from 'number-precision'
  2. import API from '@/api'
  3. import { showError, Cookie } from '@/util/util.js'
  4. import { getNetwork } from '@/util/contract.js'
  5. import Eos from 'eosjs'
  6. export const actions = {
  7. setScatter: ({ commit }, scatter) => commit('setScatter', scatter),
  8. setEos: ({ commit }, eosjs) => commit('setEos', eosjs),
  9. setAccount: ({ commit }, account) => commit('setAccount', account),
  10. /**
  11. * 调起授权登录
  12. * @param {Object} store
  13. * @param {Object} params
  14. */
  15. async doScatterLogin ({ dispatch, commit, state }, params) {
  16. if (!state.scatter) {
  17. showError('Please install the scatter', 'Scatter')
  18. } else {
  19. // 获取最快主网
  20. let networkConfig = getNetwork()
  21. // 调用getIdentity方法获取用户名
  22. try {
  23. var identity = await state.scatter.getIdentity({
  24. accounts: [networkConfig]
  25. })
  26. } catch (error) {
  27. if (error.type !== 'identity_rejected') {
  28. showError(error.message)
  29. }
  30. return Promise.reject(error)
  31. }
  32. // console.log(identity)
  33. let accounts = identity.accounts.find(x => x.blockchain === 'eos')
  34. commit('setAccount', accounts)
  35. // 如果当前登录的用户名和cookie中保存的account不一致
  36. // 则删除cookie中保存的account
  37. // 避免某些用户在移动端钱包中切换账号时跳过注销流程导致账号不一致的问题
  38. // if (Cookie.getCookie('account') !== accounts.name) {
  39. // Cookie.delCookie('account')
  40. // }
  41. // 设置全局EOS对象
  42. window.EOS = state.scatter.eos(networkConfig, Eos, {})
  43. // 调用scatter登录成功后获取用户EOS、GT
  44. // dispatch('getUserEOS')
  45. // dispatch('getUserGT')
  46. await dispatch('getAccount')
  47. // 每分钟刷新一次
  48. // this.limitTimer = setInterval(() => {
  49. // dispatch('getAccount')
  50. // }, 60000)
  51. return Promise.resolve(true)
  52. }
  53. },
  54. /**
  55. * 注销当前scatter账号
  56. * @param {Object} store
  57. * @param {Object} params
  58. */
  59. doScatterLogout ({ commit, state }, params) {
  60. Cookie.delCookie('user_id')
  61. Cookie.delCookie('token')
  62. localStorage.removeItem('user_id')
  63. localStorage.removeItem('token')
  64. state.scatter && state.scatter.forgetIdentity()
  65. commit('setAccount', '')
  66. },
  67. /**
  68. * 更新用户EOS币数量
  69. * @param {Object} store
  70. * @param {Object} params
  71. */
  72. getUserEOS ({ dispatch, commit, state }, params) {
  73. return new Promise((resolve, reject) => {
  74. window.EOS.getCurrencyBalance('eosio.token', state.account.name, 'EOS').then(([ balance ]) => {
  75. let balanceNum = Number(balance.replace(/\sEOS/, '')).toFixed(4)
  76. balanceNum = NP.times(balanceNum, 10000)
  77. commit('setBalance', balanceNum)
  78. commit('setEOSError', 0)
  79. resolve()
  80. }).catch(error => {
  81. // 失败重新尝试,最大尝试5次
  82. commit('setEOSError', state.eosErrorCount + 1)
  83. if (state.eosErrorCount <= 5) {
  84. setTimeout(() => {
  85. dispatch('getUserEOS')
  86. }, 1000 * state.eosErrorCount)
  87. }
  88. reject(error)
  89. })
  90. })
  91. },
  92. /**
  93. * 获取用户信息
  94. * @param {Object} store
  95. * @param {Object} params
  96. */
  97. getAccount ({ commit, state }, params) {
  98. return new Promise((resolve, reject) => {
  99. window.EOS.getAccount(state.account.name).then(data => {
  100. // 设置公钥
  101. const perms = JSON.parse(JSON.stringify(data.permissions))
  102. perms.forEach(v => {
  103. if (v.perm_name === 'active') {
  104. let publicKey = v.required_auth.keys[0].key
  105. commit('setPublicKey', publicKey)
  106. }
  107. })
  108. resolve(data)
  109. }).catch(error => {
  110. reject(error)
  111. })
  112. })
  113. },
  114. /**
  115. * 进行验证身份登录,生成业务登录态token
  116. * @param {Object} store
  117. * @param {Object} params
  118. */
  119. async doGameLogin ({ dispatch, commit, state }, params) {
  120. let userId = localStorage.getItem('user_id')
  121. let token = localStorage.getItem('token')
  122. if (userId && token) {
  123. commit('setUserId', userId)
  124. commit('setToken', token)
  125. return Promise.resolve({
  126. user_id: userId,
  127. token: token
  128. })
  129. } else {
  130. let rData = await API.user.getRandom({ account: state.account.name })
  131. let random = rData.data.data
  132. let pubkey = state.publicKey
  133. return new Promise((resolve, reject) => {
  134. state.scatter.getArbitrarySignature(pubkey, random, 'Need Login').then(sign => {
  135. let param = {
  136. account: state.account.name,
  137. sign,
  138. pubkey,
  139. data: random
  140. }
  141. API.user.eosLogin(param).then(({ data }) => {
  142. if (data.result === 1) {
  143. let userId = data.data.user_id
  144. let token = data.data.token
  145. localStorage.setItem('user_id', userId)
  146. localStorage.setItem('token', token)
  147. commit('setUserId', userId)
  148. commit('setToken', token)
  149. resolve(data)
  150. } else {
  151. reject(new Error(data.msg))
  152. }
  153. })
  154. }).catch(error => {
  155. reject(error)
  156. })
  157. })
  158. }
  159. },
  160. /**
  161. * 登录态过期,清除当前登录态相关数据,重新调起登录
  162. * @param {Object} store
  163. * @param {Object} params
  164. */
  165. resetGameLogin ({ dispatch, commit, state }, params) {
  166. localStorage.removeItem('user_id')
  167. localStorage.removeItem('token')
  168. dispatch('doGameLogin')
  169. },
  170. /**
  171. * 内嵌版本调起合约登录
  172. * @param {Array} params
  173. */
  174. async doParentLogin ({ dispatch, commit, state }, params) {
  175. try {
  176. let identity = { authorization: [`${state.account.name}@${state.account.authority}`] }
  177. let trx = await window.postMessager.send({
  178. action: 'meechat:eosAction',
  179. data: {
  180. contract: 'meechatadmin',
  181. action: 'login',
  182. param: params.concat(identity)
  183. }
  184. })
  185. return Promise.resolve(trx.transaction_id)
  186. } catch (error) {
  187. return Promise.reject(error)
  188. }
  189. }
  190. }