当前位置: 首页 > Web前端 > vue.js

【NearProtocol】Near开发Demo分析——GambleGameNear(二):Dapp

时间:2023-03-31 14:17:59 vue.js

Dapp链接:https://github.com/Yang94J/Gamble_Game_Near_Front简介本项目依赖Vue搭建前端应用,调用near-api-js与部署的合约进行交互,完成掷骰子功能。环境搭建前提:系统中应该已经安装了Nodejs,Vue3项目搭建:vuecreategamble_gamble_near_front最终代码框架如下:主要为/components/GambleGame.vue、App.vue、config.js、main.js、store.js,.引入了env、package.json和vue.config.js。

代码分析

package.json下面是package.json的关键部分"dependencies":{"@rollup/plugin-inject":"^4.0.4","buffer":"^6.0.3","core-js":"^3.8.3","near-api-js":"^0.44.2","vue":"^3.2.13","vuex":"^4.0.2"},这里表示依赖buffer、near-api-js、vue、vuex等(特别是buffer,必须引入并显式声明,否则项目会出现Can'tfindvariable:Buffer这样的错误).envVUE_APP_CONTRACT_NAME=gamble_game1.XXX.testnet指定dapp需要调用的合约名称(testnet)main.jsimport{createApp}from'vue'importAppfrom'./App.vue'importstorefrom'./store'从“缓冲区”导入{缓冲区};global.Buffer=Buffer;createApp(App).use(store).mount('#app')注意这里明确声明了global.Bufferconfig.jsconstCONTRACT_NAME=process.env.VUE_APP_CONTRACT_NAME;Readcontractnamefrom.envfilecase'testnet':return{networkId:'testnet',nodeUrl:'https://rpc.testnet.near.org',contractName:CONTRACT_NAME,walletUrl:'https://wallet.testnet.near.org',helperUrl:'https://helper.testnet.near.org',explorerUrl:'https://explorer.testnet.near.org',};根据用户输入环境,选择对应的网络配置(这里是测试网络)store.jsstore.js存储数据到本地浏览器,获取缓存等,可以参考这个链接状态:{contract:null,currentUser:null,wallet:null,nearConfig:null},存储状态包括合约、当前用户、钱包和附近的配置突变:{setupNear(state,payload){state.contract=payload.contract;state.currentUser=payload.currentUser;state.wallet=payload.wallet;state.nearConfig=payload.nearConfig;}}设置状态对象asyncinitNear({commit}){constnearConfig=getConfigurations('testnet');constnear=awaitnearApi.connect({deps:{keyStore:newnearApi.keyStores.BrowserLocalStorageKeyStore()},...nearConfig});constwallet=newnearApi.WalletConnection(near);console.log(wallet)让当前用户;如果(wallet.getAccountId()){currentUser={accountId:wallet.getAccountId(),balance:(awaitwallet.account().state()).amount,balanceInNear:(awaitwallet.account().state())。数量/(10**24),}}console.log(currentUser)constcontract=awaitnewnearApi.Contract(wallet.account(),process.env.VUE_APP_CONTRACT_NAME||'gamble_game1.young_cn.testnet',{viewMethods:['get_maximum_gamble_price'],changeMethods:['gamble','sponsor'],sender:wallet.getAccountId()});控制台日志(合同);//提交并发送到mutation.commit('setupNear',{contract,currentUser,wallet,nearConfig});这里initNear函数获取测试网配置,生成合约,钱包信息(需要用户登录),用户信息等。GambleGame.vue骰子赌博游戏{{currentUser?'LogOut':'LogIn'}}
根据当前用户情况,生成登录和注销按钮

您好,{{currentUser.accountId}},您的余额是{{currentUser.balanceInNear}}Near

显示当前用户id和当前余额(有关CurrentUser的信息参见store.js)Maximum:{{gambleLimit}}NearRefresh

显示当前最大投注金额,通过刷新函数访问智能合约刷新最大投注金额赌博:Gamble

投注按钮,调用gamblegame方法下注"number"required/>赞助我们

赞助按钮,调用sponsorus方法赞助asynccreated(){console.log("created")console.log(sessionStorage.getItem('gambleLimit'))if(sessionStorage.getItem('gambleLimit')){this.gambleLimit=sessionStorage.getItem('gambleLimit')}},使用创建的钩子函数自动获取最大投注额(否则数据会丢失)asyncmounted(){varthat=thisconsole.log("Mount")setInterval(()=>{console.log("refresh")that.refresh()},3000)},使用挂载的钩子函数设置自动更新的最大投注额——考虑合约的并发性signIn(){this.wallet.requestSignIn(this.nearConfig.contractName,'NearGambleGame');},signOut(){this.wallet.signOut();window.location.replace(window.location.origin+window.location.pathname)},signIn和signOut方法使用near.api.js实现与钱包的交互异步gamblegame(){try{awaitthis.contract.gamble({},this.gas,Big(this.gamble).times(10**24).toFixed());}catch(e){console.log(e);}},asyncsponsorus(){try{awaitthis.contract.sponsor({},this.gas,Big(this.sponsor).times(10**24).toFixed());}catch(e){console.log(e);alert('出了点问题!检查控制台。');}},asyncrefresh(){this.gambleLimit=awaitthis.contract.get_maximum_gamble_price()this.gambleLimit=this.gambleLimit/(10**24)sessionStorage.setItem('gambleLimit',this.gambleLimit)}}gambleGame、sponsorus、refresh都是异步方法。具体合约方法信息在store.js中声明如下:viewMethods:['get_maximum_gamble_price'],changeMethods:['gamble','sponsor'],deploymentVue.config.js修改其配置如下:const{defineConfig}=require('@vue/cli-service')module.exports=defineConfig({transpileDependencies:true,publicPath:'./',})将路径改为相对路径构建npmrunbuildrunningnpmrunserve效果展示至此,Dapp部分完成。诚然,这个演示显然有很多不足之处,但这也是一个好的开始。如果您有想法,欢迎与我讨论。相互交流,共同进步。