ウォレットの初期化
私はいつもOKXを使っているので、ここでもOKXをお勧めします。
OKXプロジェクトの作成
前のセクションでvueプロジェクトをすでに初期化しましたが、各セクションが独自の作業を行うという精神に従い、私は素直にプロジェクトを自分で作成します。
{{ msg }}
// ウォレット認証ボタンの表示/非表示を切り替えるグローバル変数
let displayButton = true
let accounts = [];
onload = async () => {
ブラウザにOKExウォレットプラグインがインストールされているかどうかを判断します。インストールされている場合は、ボタンが表示されます。
if (typeof window.okxwallet !== 'undefined') {
console.log('OKX is installed!');
displayButton = true;
getChainId();
以下の2つのパブリックチェーンの監視方法は、どちらも正常に動作します。
window.ethereum.on('chainChanged', (chainId) => {
console.log('window.ethereum', chainId)
});
okxwallet.on('chainChanged', (chainId) => {
console.log('okxwallet', chainId)
})
} else {
console.log('OKX is not installed!');
}
}
// パブリックチェーンIDを同期的に取得
async function getChainId() {
try {
const chainId = await okxwallet.request({ method: 'eth_chainId' });
console.log(chainId)
} catch(error) {
console.log(error)
}
}
// まだ使用されていません。問題は見当たりません。
async function handleChainChanged() {
// window.location.reload();
// getChainId();
}
export default {
name: 'HelloWorld',
data() {
return {
msg: 'Welcome to Your Vue.js App',
displayButton: displayButton
}
},
methods: {
getAccount: async function() {
try {
// ウォレットに接続し、ウォレットのアドレスを返します
accounts = await okxwallet.request({ method: 'eth_requestAccounts' });
console.log(accounts)
} catch(error) {
console.log(error)
}
},
connectEthereum: function () {
const connectEthereumButton = document.querySelector('.connectEthereumButton');
connectEthereumButton.addEventListener('click', () => {
// OKX 拡張機能を開始します
this.getAccount()
// アカウント変更リスナーを追加します。この関数は、アカウントを切り替える際にトリガーされます
okxwallet.on('accountsChanged', (accounts) => {
console.log('accountsChanged', accounts)
this.getAccount()
})
});
}
}
}