wallet.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. /* Import modules. */
  2. import moment from 'moment'
  3. import PouchDB from 'pouchdb'
  4. import { listUnspent } from '@nexajs/address'
  5. import { sha256 } from '@nexajs/crypto'
  6. import { encodePrivateKeyWif } from '@nexajs/hdnode'
  7. import { sendCoin } from '@nexajs/purse'
  8. import { encodeNullData } from '@nexajs/script'
  9. import { hexToBin } from '@nexajs/utils'
  10. import { Wallet } from '@nexajs/wallet'
  11. /* Initialize databases. */
  12. const playsDb = new PouchDB(`http://${process.env.COUCHDB_USER}:${process.env.COUCHDB_PASSWORD}@127.0.0.1:5984/plays`)
  13. const walletDb = new PouchDB(`http://${process.env.COUCHDB_USER}:${process.env.COUCHDB_PASSWORD}@127.0.0.1:5984/wallet`)
  14. /* Set constants. */
  15. const DUST_LIMIT = BigInt(546)
  16. const ESTIMATED_NUM_OUTPUTS = 5
  17. const VAULT_MNEMONIC = process.env.MNEMONIC
  18. /* Initialize wallet. */
  19. const vaultWallet = new Wallet(VAULT_MNEMONIC)
  20. /* Initialize spent coins. */
  21. const spentCoins = []
  22. /**
  23. * Handle (Wallet) Queue
  24. *
  25. * Process the pending queue of open transactions.
  26. *
  27. * NOTE: We handle payment processing in a SINGLE thread,
  28. * to mitigate the possibility of a "double send".
  29. */
  30. export default async (_queue, _pending) => {
  31. let latestDb
  32. let response
  33. let txResult
  34. let updatedDb
  35. let unspent
  36. let wif
  37. for (let i = 0; i < _pending.length; i++) {
  38. const payment = _queue[_pending[i]]
  39. console.log('PAYMENT (pending):', payment)
  40. console.log('PAYMENT (pending) receivers:', payment.receivers)
  41. /* Remove (payment) from queue. */
  42. delete _queue[_pending[i]]
  43. const paymentSatoshis = payment.receivers
  44. .reduce(
  45. (totalValue, receiver) => (totalValue + receiver.satoshis), BigInt(0)
  46. )
  47. // console.log('PAYMENT SATOSHIS', paymentSatoshis)
  48. const wallet = new Wallet(process.env.MNEMONIC)
  49. // console.log('WALLET', wallet)
  50. const address = wallet.address
  51. // console.log('TREASURY ADDRESS', address)
  52. /* Initialize receivers. */
  53. const receivers = []
  54. unspent = await listUnspent(address)
  55. // console.log('UNSPENT', unspent)
  56. /* Encode Private Key WIF. */
  57. wif = encodePrivateKeyWif(wallet.privateKey, 'mainnet')
  58. // console.log('PRIVATE KEY (WIF):', wif)
  59. /* Filter out ANY tokens. */
  60. // FIXME We should probably do something better than this, lol.
  61. // unspent = unspent.filter(_unspent => {
  62. // return _unspent.satoshis > DUST_LIMIT
  63. // })
  64. /* Filter out ANY tokens & spent. */
  65. // FIXME We should probably do something better than this, lol.
  66. // unspent = unspent.filter(_unspent => {
  67. // /* Initialize flag. */
  68. // let isValid = true
  69. //
  70. // if (_unspent.satoshis <= DUST_LIMIT) {
  71. // /* Set flag. */
  72. // isValid = false
  73. // }
  74. //
  75. // if (spentCoins.includes(_unspent.outpoint)) {
  76. // /* Set flag. */
  77. // isValid = false
  78. // }
  79. //
  80. // /* Return flag. */
  81. // return isValid
  82. // })
  83. /* Validate unspent outputs. */
  84. if (unspent.length === 0) {
  85. return console.error('There are NO unspent outputs available.')
  86. }
  87. /* Build parameters. */
  88. const coins = unspent.map(_unspent => {
  89. const outpoint = _unspent.outpoint
  90. const satoshis = _unspent.satoshis
  91. return {
  92. outpoint,
  93. satoshis,
  94. wif,
  95. }
  96. })
  97. // console.log('\n Coins-1:', coins)
  98. const wallet2 = new Wallet(payment.entropy)
  99. // console.log('WALLET-2', wallet2)
  100. const address2 = wallet2.address
  101. // console.log('TREASURY ADDRESS-2', address2)
  102. const pk2 = wallet2.privateKey
  103. // console.log('PRIVATE KEY-2', pk2)
  104. const playerCoin = {
  105. outpoint: payment.unspent.outpoint,
  106. satoshis: payment.unspent.satoshis,
  107. wif: encodePrivateKeyWif(pk2, 'mainnet'),
  108. }
  109. coins.unshift(playerCoin)
  110. // console.log('\n Coins-2:', coins)
  111. /* Calculate the total balance of the unspent outputs. */
  112. const unspentSatoshis = coins
  113. .reduce(
  114. (totalValue, coin) => (totalValue + coin.satoshis), BigInt(0)
  115. )
  116. // console.log('UNSPENT SATOSHIS', unspentSatoshis)
  117. const userData = `NEXA.games~${payment.id}`
  118. // console.log('BLOCKCHAIN DATA', chainData)
  119. /* Initialize hex data. */
  120. const nullData = encodeNullData(userData)
  121. // console.log('HEX DATA', nullData)
  122. // NOTE: 150b (per input), 35b (per output), 10b (misc)
  123. // NOTE: Double the estimate (for safety).
  124. // const feeEstimate = ((coins.length * 150) + (35 * ESTIMATED_NUM_OUTPUTS) + 10 + (chainData.length / 2)) * 2
  125. // console.log('FEE ESTIMATE', feeEstimate)
  126. // TODO Validate data length is less than OP_RETURN max (220).
  127. /* Add OP_RETURN data. */
  128. receivers.push({
  129. data: nullData,
  130. })
  131. /* Add value output. */
  132. for (let j = 0; j < payment.receivers.length; j++) {
  133. if (payment.receivers[j].satoshis > DUST_LIMIT) {
  134. receivers.push({
  135. address: payment.receivers[j].address,
  136. satoshis: payment.receivers[j].satoshis,
  137. })
  138. }
  139. }
  140. /* Set change receiver. */
  141. receivers.push({
  142. address: vaultWallet.address
  143. })
  144. console.log('\n Receivers:', receivers)
  145. /* Send UTXO request. */
  146. response = await sendCoin(coins, receivers)
  147. console.log('Send UTXO (response):', response)
  148. try {
  149. txResult = JSON.parse(response)
  150. console.log('TX RESULT', txResult)
  151. /* Validate transaction result. */
  152. if (txResult?.result) {
  153. /* Manage coins. */
  154. // coins.forEach(_coin => {
  155. // /* Add hash to spent. */
  156. // spentCoins.push(_coin.outpoint)
  157. //
  158. // // TODO Add check for MAX spent (eg. 100).
  159. // })
  160. latestDb = await walletDb
  161. .get(payment.id)
  162. .catch(err => console.err(err))
  163. // console.log('LATEST (wallet)', latestDb)
  164. updatedDb = {
  165. ...latestDb,
  166. txidem: txResult?.result,
  167. updatedAt: moment().valueOf(),
  168. }
  169. // console.log('UPDATED (wallet)', updatedDb)
  170. response = await walletDb
  171. .put(updatedDb)
  172. .catch(err => console.error(err))
  173. // console.log('UPDATE (wallet) RESPONSE', response)
  174. latestDb = await playsDb
  175. .get(payment.id)
  176. .catch(err => console.err(err))
  177. // console.log('LATEST (plays)', latestDb)
  178. updatedDb = {
  179. ...latestDb,
  180. txidem: txResult?.result,
  181. updatedAt: moment().valueOf(),
  182. updatedBy: 'WALLET',
  183. }
  184. // console.log('UPDATED (plays)', updatedDb)
  185. response = await playsDb
  186. .put(updatedDb)
  187. .catch(err => console.error(err))
  188. // console.log('UPDATE (plays) RESPONSE', response)
  189. }
  190. // TODO SEND EMAIL ERROR
  191. // txResult?.error
  192. // txResult?.result
  193. } catch (err) {
  194. console.error(err)
  195. }
  196. }
  197. }