LoginSignup
1
2

More than 1 year has passed since last update.

Metamaskのweb3をVuexで管理する

Last updated at Posted at 2021-03-05

はじめに

metamaskを接続するのにちょっとつまづいたので共有
metamaskがinjectしたwindow.ethereumからweb3インスタンスを作成し,
Vuexのstoreで管理した.

APIの規定

EIP-1193ではクライアントのAPIを規定している

実装

Store

今回ややこしいことはしてなく,接続できるかのテストで書いていたので
もしmetamaskがインストールされていなかったらなどの条件分岐は省いています

store.js
import Web3 from 'web3'

export const web3Store = {
    namespaced: true,
    state: {
        web3: {}
    },
    getters: {
        getWeb3: (state) => {
            return state.web3
        }
    },
    mutations: {
        async mutateWeb3Provider(state) {
            if (window.ethereum) {
                await window.ethereum.request({ method: 'eth_requestAccounts' });
                const web3 = new Web3(window.ethereum);
                state.web3 = web3;
                return true;
            }
            console.log("fatal")
            return false;
        }
    },
    actions: {
        async setWeb3Provider({ commit }) {
            await commit('mutateWeb3Provider')
        }
    }
}

署名のテスト

let prefix = "\x19Ethereum Signed Message:\n" + this.signMessage.length
let msgHash = this.web3js.utils.sha3(prefix+this.signMessage)
const signature = await this.web3js.eth.sign(msgHash, account)

つまづいたところ

metamaskのドキュメント

Metamask上でログイン後,リロードしないとweb3がstoreに入らない

脳死で書いていたのでwindow.addEventListenerを書いていた.
どうやらこれが原因っぽい


// 当初書いていたコード
mutations: {
        async mutateWeb3Provider(state) {
            window.addEventListener("load", async () => {
                if (window.ethereum) {
                    window.web3 = new Web3(window.ethereum);
                    state.web3 = window.web3;
                    console.log(state.web3);
                    window.ethereum.enable();
                    return true;
                }
                return false;
            });
        }
    },

window.web3の非推奨

metamaskはwindow.ethereumを推奨しているらしい
でもmetamask以外をクライアントで使用した時のこと考えるとwindow.web3を対処する必要はある

ethereum.enable()の非推奨

公式によると

ethereum.enable() (DEPRECATED)

WARNING
Use ethereum.request({ method: 'eth_requestAccounts' }) instead.

を代わりに使おうとのことethereum.request({ method: 'eth_requestAccounts' })

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2