Shomari 2 долоо хоног өмнө
parent
commit
ea10005574

+ 11 - 4
web/components/menu/Wallet.vue

@@ -91,14 +91,21 @@ const createWallet = () => {
     Wallet.createWallet()
 }
 
+const init = () => {
+    /* Set (starting) tab. */
+    setTab('deposit')
+
+    /* Initialize the Web wallet. */
+    Wallet.init()
+}
 
 onMounted(() => {
-    setTab('deposit')
+    init()
 })
 
-// onBeforeUnmount(() => {
-//     console.log('Before Unmount!')
-// })
+onBeforeUnmount(() => {
+    Wallet.cleanup()
+})
 </script>
 
 <template>

+ 62 - 11
web/stores/game/rollDice.ts

@@ -1,11 +1,33 @@
 /* Import modules. */
-import { sendCoins } from '@nexajs/purse'
-import { encodeNullData } from '@nexajs/script'
+import { broadcast } from '@nexajs/provider'
+import { buildCoins } from '@nexajs/purse'
+import {
+    encodeDataPush,
+    encodeNullData,
+    OP,
+} from '@nexajs/script'
+import {
+    hexToBin,
+    utf8ToBin,
+} from '@nexajs/utils'
 
 /* Import (local) modules. */
 import { useWalletStore } from '@/stores/wallet'
 
+/* Initialize constants. */
+const TIMETOCASHOUT_HEX = '6c6c6c6c5479009c63557a7cad6d6d67547a519d537ab275030051147b7e00cd8800cc55ea537a94a2697568'
+
 export default async function () {
+    /* Initialize locals. */
+    let coins
+    let lockingScript
+    let nullData
+    let receivers
+    let response
+    let scriptPubkey
+    let unlockingScript
+    let userData
+
     /* Initialize wallet store. */
     const Wallet = useWalletStore()
 
@@ -19,18 +41,43 @@ export default async function () {
         throw new Error('Missing authorization hash.')
     }
 
+    /* Set script public key. */
+    scriptPubkey = encodeDataPush(Wallet.publicKey)
+
+    /* Set locking script. */
+    lockingScript = hexToBin(TIMETOCASHOUT_HEX)
+    // console.info('\nCONTRACT TEMPLATE', binToHex(lockingScript))
+
+    /* Set unlocking script. */
+    // NOTE: Index of (executed) contract method.
+    unlockingScript = new Uint8Array([
+        ...encodeDataPush(scriptPubkey),
+        ...utf8ToBin('{{SIGNATURE}}'), // placeholder for signature
+        OP.ZERO, // contract function index
+    ])
+
+    /* Handle coin locks. */
+    coins = Wallet.coins.map(_coin => {
+        return {
+            ..._coin,
+            locking: lockingScript,
+            unlocking: unlockingScript,
+        }
+    })
+    // console.log('COINS-2', coins)
+
     /* Initialize receivers. */
-    const receivers = []
+    receivers = []
 
     /* Initialize user data. */
-    const userData = [
+    userData = [
         'NEXA.games',
         this.authHash,
     ]
     // console.log('AUTH HASH', this.authHash)
 
     /* Initialize hex data. */
-    const nullData = encodeNullData(userData)
+    nullData = encodeNullData(userData)
     // console.log('HEX DATA', nullData)
 
     /* Validate user data. */
@@ -45,8 +92,6 @@ export default async function () {
         })
     }
 
-    // console.log('\n  Coins:', Wallet.coins)
-
     /* Add value output. */
     receivers.push({
         address: this.address,
@@ -57,11 +102,17 @@ export default async function () {
         address: Wallet.address,
         // satoshis: changeVal,
     })
-    console.log('\n  Receivers:', receivers)
+    console.log('RECEIVERS', receivers)
+
+    /* Build transaction. */
+    response = await buildCoins(coins, receivers)
+        .catch(err => console.error(err))
+    console.log('BUILD TRANSACTION', response.raw)
 
-    /* Send UTXO request. */
-    const response = await sendCoins(Wallet.coins, receivers)
-    console.log('Send UTXO (response):', response)
+    /* Broadcast transaction. */
+    response = await broadcast(response.raw)
+        .catch(err => console.error(err))
+    console.log('SEND TRANSACTION', response)
 
     try {
         const txResult = JSON.parse(response)

+ 30 - 8
web/stores/wallet.ts

@@ -33,9 +33,13 @@ import {
 import { useSystemStore } from '@/stores/system'
 import _setEntropy from './wallet/setEntropy.ts'
 
+/* Initialize constants. */
 const CASHOUT_FEE = BigInt(1000) // FIXME We MUST calculate this (same as change).
 const TIMETOCASHOUT_HEX = '6c6c6c6c5479009c63557a7cad6d6d67547a519d537ab275030051147b7e00cd8800cc55ea537a94a2697568'
-const UPDATE_BALANCE_INTERVAL = 30000
+const UPDATE_BALANCE_INTERVAL = 5000
+
+/* Initialize globals. */
+let balanceHandler
 
 /**
  * Wallet Store
@@ -166,11 +170,12 @@ export const useWalletStore = defineStore('wallet', {
             if (System.ticker) {
                 /* Set quote. */
                 const quote = System.ticker.quote
+                console.log('QUOTE', quote)
 
                 /* Validate quote. */
                 if (quote) {
                     /* Set (USD) price. */
-                    USD = quote?.USD?.price * Number(satoshis)
+                    USD = (quote?.USD?.price * parseFloat(Number(satoshis) / 100))
                 }
             }
 
@@ -241,6 +246,15 @@ export const useWalletStore = defineStore('wallet', {
             return _state._wallet.isReady
         },
 
+        /* Return public key. */
+        publicKey(_state) {
+            if (!_state._wallet?.publicKey) {
+                return null
+            }
+
+            return _state._wallet?.publicKey
+        },
+
         scriptPubkey(_state) {
             /* Initialize locals. */
             let constraintData
@@ -266,8 +280,8 @@ export const useWalletStore = defineStore('wallet', {
             // console.log('TEMPLATE HASH', binToHex(scriptHash))
 
             /* Set public key. */
-            publicKey = this._wallet.publicKey
-            // console.log('PUBLIC KEY', binToHex(publicKey))
+            publicKey = this.publicKey
+            // console.log('PUBLIC KEY', publicKey)
 
             /* Hash the public key hash according to the P2PKH/P2PKT scheme. */
             constraintData = encodeDataPush(publicKey)
@@ -298,9 +312,7 @@ export const useWalletStore = defineStore('wallet', {
             scriptPubkey = new Uint8Array([
                 OP.ZERO, // groupid or empty stack item
                 ...encodeDataPush(scriptHash), // script hash
-                // OP.ZERO, // arguments hash or empty stack item
                 ...encodeDataPush(constraintHash),  // arguments hash
-                // ...encodeDataPush(publicKey), // Owners public key.
                 ...encodeDataPush(recoveryPkh), // A recovery address (specified by the Owner) used to cashout the balance, after a timeout period.
                 ...gratitude, // The rate of exchange, charged by the Provider. (measured in <satoshis> per <asset>)
                 ...timeout, // The rate of exchange, charged by the Provider. (measured in <satoshis> per <asset>)
@@ -348,7 +360,7 @@ export const useWalletStore = defineStore('wallet', {
             console.info('(Initialized) wallet', this.wallet)
 
             /* Update balance. */
-            setInterval(this.updateBalance, UPDATE_BALANCE_INTERVAL)
+            balanceHandler = setInterval(this.updateBalance, UPDATE_BALANCE_INTERVAL)
             this.updateBalance()
         },
 
@@ -399,7 +411,7 @@ export const useWalletStore = defineStore('wallet', {
             let unlockingScript
 
             /* Set script public key. */
-            scriptPubkey = encodeDataPush(this._wallet.publicKey)
+            scriptPubkey = encodeDataPush(this.publicKey)
 
             /* Set locking script. */
             lockingScript = hexToBin(TIMETOCASHOUT_HEX)
@@ -506,6 +518,16 @@ export const useWalletStore = defineStore('wallet', {
             return this.wallet
         },
 
+        cleanup() {
+            console.info('Cleaning up wallet...')
+
+            /* Validate balance handler. */
+            if (balanceHandler) {
+                /* Stop balance interval. */
+                clearInterval(balanceHandler)
+            }
+        },
+
         destroy() {
             /* Reset wallet. */
             this._entropy = null