Nuxtで、簡単なDapps作った
やったこと
ethereumの送金をできるだけのシンプルなDappsを作ってみた
慣れてるNuxtを使った。
アプリケーション側
初期設定
nuxtをinstallするとかの部分は割愛。
プラグイン作成
/plugin/web3.js を作成。
初期時に、web3 objectのinjectと、addressや、ethereum残金をstoreに入れてみた。
参考:
Breaking Change: No Accounts Exposed by Default - MetaMask - Medium
MetaMaskのアドレスをgetAccountsで取得する
import Web3 from 'web3'; export default async function({ store }, inject) { let web3; if (window.ethereum) { web3 = new Web3(window.ethereum); await ethereum.enable(); } else if (window.web3) { web3 = new Web3(window.web3.currentProvider); } else { console.log( 'Non-Ethereum browser detected. You should consider trying MetaMask!' ); return; } inject('web3', web3); if (web3 !== null) { web3.eth.getAccounts((error, accounts) => { if (error) return; let user_account = accounts[0]; if (typeof user_account !== 'undefined') { store.commit('setAccount', user_account); web3.eth.getBalance(user_account, function(err, balance) { if (!err) { store.commit('setBalance', balance); } }); } else { alert('ログインして下さい'); } }); } }
nuxt.config.js にも追加
plugins: ['~/plugins/web3.js'],
Store追加
/store/index.js に追加
export const state = () => ({ account: '', balance: 0 }); export const getters = { account: state => state.account, balance: state => state.balance }; export const mutations = { setAccount(state, account) { state.account = account; }, setBalance(state, balance) { state.balance = balance; } }; export const actions = {};
Pages作成
/pages/index.vue を編集
<template> <div> <div>account: {{ account }}</div> <div>balance: {{ balance }}</div> <button @click="send">Send Ether</button> </div> </template> <script> export default { computed: { account() { return this.$store.getters['account']; }, balance() { return this.$store.getters['balance']; } }, methods: { send() { if (this.$web3 === undefined) return; console.log(this.$web3); this.$web3.eth .sendTransaction({ from: this.account, to: '0x0C6390A4F8bE143d3905aFA1BcCcacC44f335794', value: 10 }) .on('receipt', console.log); } } }; </script>
ブラウザ側
PCなら、MetaMaskをChrome拡張で入れる。
モバイルなら、Trust Wallet とかの、ウォレット機能付DAppsブラウザでページを開く。
実際に送金したかったら、Ropstenとかのテストネット使って、下のサイトとかで、ethereumをもらうと楽。
Ropsten Ethereum Faucet
あんま関係ないけど、githubに公開
参考:
Nuxt.jsで作ったWebサイトをささっとGithub Pagesに公開する - Qiita
GitHub Pages へデプロイするには? - NuxtJS
nuxt.config.js に以下を追加
const routerBase = process.env.DEPLOY_ENV === 'GH_PAGES' ? { router: { base: '/<repository name>/' } } : {}; export default { ...routerBase, }
package.jsonに以下を追加
"scripts": { "gh:generate": "DEPLOY_ENV=GH_PAGES nuxt generate", "gh:push": "git subtree push --prefix dist/ origin gh-pages" },
ターミナルで以下を実行
$ yarn gh:generate $ git add --all $ git commit -m "commit" $ yarn gh:push
あとは、github pagesの対象ブランチを gh-pages に変えちゃえばOK!!
.gitignore に dist を指定している場合、うまく行かないので注意。
完成!
こんな感じに表示されるはず。