Skip to main content

Wallet Address

We can use the data we received from the wallet to display certain information to our player within the game. With these two lines in our Web3Connection.js we get our instance of the Menu class defined in Menu.js to update the network text and set the connection button visibility.

Web3Connection.js

//...

// Update network text on menu scene
this.game.scene.scenes[0].updateNetworkText(this.web3Network)
this.game.scene.scenes[0].setConnectWalletButtonVisibility(false)

//...

Menu.js

// ...

updateNetworkText = (web3Network) => {
if(!this.networkText) { return }
const baseString = "Connected to: "
const chainId = web3Network.chainId
let networkName = web3Network.name

// Turn recognized network name into more readable format
if(networkName === 'unknown') {
if(web3Network.chainId === constants.GAME.HMV_TEST_CHAINID) {
networkName = "Homeverse Testnet"
} else if(web3Network.chainId === constants.GAME.HMV_MAIN_CHAINID) {
networkName = "Homeverse Mainnet"
}
} else if(networkName === 'homestead') {
networkName = "Ethereum Mainnet"
} else if(networkName === 'matic') {
networkName = "Polygon Mainnet"
}

this.networkText.setText(`${baseString} ${networkName} (${chainId})`)
}

// ...

setConnectWalletButtonVisibility = (setVisible) => {
if(!this.connectWalletButton) { return }
this.connectWalletButton.setVisible(setVisible)

if(!this.disconnectButton) { return }
if(setVisible) {
this.disconnectButton.setVisible(false)
} else if (!setVisible && !!web3Connection.web3Network) {
// Only show disconnect button if connected and connect button is hidden
this.disconnectButton.setVisible(true)
}
}

// ...

Before:

Before Connecting

After:

After Connecting

We can then also create an event to update this in the case the user switches networks in his wallet.

Web3Connection.js

this.provider.on("chainChanged", this.handleNetworkSwitch)

// ...

// Reset ethers settings and show new network in ui
handleNetworkSwitch = async() => {
await this.setEthers()

// Update network text on menu
this.game.scene.scenes[0].updateNetworkText(this.web3Network)
}

Network Switch

We can then also do something similar to display the users public wallet address. To accomplish this we trigger a method on our user interface instance from the create function.

Runner.js

if(web3Connection && this.userInterface) {
this.userInterface.updateAddressText(web3Connection.web3Address)
}

UserInterface.js

// ...

initUI = () => {
//...
this.addressText = this.runnerScene.add.text(25, 25, 'Address: 0x0', { fontSize: '20px', fill: '#FFF', fontFamily: this.textFont })
this.addressText.setScrollFactor(0)
this.addressText.setDepth(constants.INTERFACE.HUD_RENDER_DEPTH)
//...
}

// ...

updateAddressText = (address) => {
this.addressText.setText('Address: ' + address)
}

// ...

Game Address