Metamask Address Exercise

function mintAfterGame(nrOfTokens){

    return web3.eth.getAccounts().then(accounts => {
        var address = accounts[0];
        contract.methods.mint(address, nrOfTokens).send({from: address})
        .on("receipt", receipt => {
            alert("transaction complete!")
        })
    })


}```
  function mintAfterGame( nrOfTokens){
    address = 0;

    web3.eth.getAccounts().then( accs => {
      address = accs[0];
      console.log("got!" + address);
      contract.methods.mint(address, nrOfTokens).send({from: address})
      .on('receipt', receipt => {
        alert("Transaction Complete");
      });
    });
  }
index.html code fragment
  if(gameOver) {
            if(!coinsSent){
              mintAfterGame(score);
              coinsSent = true;
            }
            return;
          }
eth.js
function mintAfterGame(nrOfTokens){
  web3.eth.getAccounts().then(account => {
    return account[0];
  }).then(address => {
    contract.methods.mint(address, nrOfTokens).send({from: address})
    .on('receipt', receipt => {
      alert("Transaction Complete");
    })
  })
Solution
function mintNewCoins(amount){

  web3.eth.getAccounts().then((addresses) => {
 
  let address = addresses[0];

  contract.methods.mint(address, amount).send({from: address})
    .on("reciept", reciept => {
          console.log("E");
    });

  });
}

index.html
//Adding mintAfterGame function, so that
//the token will be minted after the game
if(gameOver)
{
if(!coinSent){
mintAfterGame(score);
}
coinSent = true;
return;
};
eth.js
//account will obtain the address
var account = 0;
var contract = new web3.eth.Contract(abi,"");

console.log(contract);

function mintAfterGame(nrOFTokens){
//Returns a list of accounts the node controls.
//PromisereturnsArray- An array of addresses controlled by node.
web3.eth.getAccounts().then(e => {account=e[0]});
contract.methods.mint(address, nrOFTokens).send({from: address})
.on(‘receipt’, receipt => {
alert(“Transaction Complete”);

})
1 Like
  function mintAfterGame(nrOfTokens){
      web3.eth.getAccounts().then(accounts => {
          var address = accounts[0];
          contract.methods.mint(address, nrOfTokens).send({from:address})
          .on('receipt', receipt => {
              alert("Transaction Complete");
      })
      })
  }

I used ethers.js with typescript and typechain

import { ethers } from 'ethers'
import { GameToken__factory } from '../../abis/types';

const tokenAddr = "0xd93Bc3E68b80B09D943282Ef9EaDdB4a31D2580B";

export async function mintAfterGame(amount: number) {
  //@ts-ignore
  const {ethereum} = window;
  const provider = new ethers.providers.Web3Provider(ethereum)
  await provider.send("eth_requestAccounts", []);
  const signer = provider.getSigner();
  const token = GameToken__factory.connect(tokenAddr, signer);
  const tx = await token.mint(await signer.getAddress(), amount);
  await tx.wait();
}

main.js file

var web3 = new Web3(Web3.givenProvider);
var instance;
var user;
var contractAddress = '0x1893E5C27E2fFde4C38a191b109502a32AEbeFA9';

$(document).ready(()=>{
    window.ethereum.enable().then(accounts => {
        instance = new web3.eth.Contract(abi,contractAddress,{from: accounts[0]});
        user = accounts[0];
        console.log(instance);
    });
 
});

async function mintAfterGame(amount){
    var amt = web3.utils.toWei(amount.toString(),'ether');
    await instance.methods.mint(user,amt).send({},function(error,txHash){
       if(error){
           console.log(error);
       }
       else{
           console.log(txHash);
       }
    });
} 

1 Like

After some Googling around I lifted this code from a forum, it seems to work. A little complicated to implement though, it uses async functions. I had to also change updateTimeLeft to be async so it could run mintAfterGame().

async function getUserAddress() {
  let _web3 = Web3;
  const ethereum = window.ethereum;
  if (ethereum) {
    if (!ethereum.selectedAddress) {
      await ethereum.enable();
    }
    userAccount = ethereum.selectedAddress;
    _web3 = new Web3(ethereum);
  }
  else {
    _web3 = new Web3(window.ethereum);
  }
  return userAccount;
}

async function mintAfterGame(numberOfTokens) {
  var address = await getUserAddress();
  console.log(address);
  contract.methods.mint(address, numberOfTokens).send({from: address})
  .on("receipt", receipt => {
    alert("Transaction complete");
    return;
  })
}
2 Likes

Got it to work :slight_smile:

Modifications I made in index.html

...
      function updateTimeLeft() {

        if(gameOver) {

          if(!coinsMinted) {
            mintAfterGame(score);
            coinsMinted = true;
          }
...

Modifications I made in eth.js

...
      async function mintAfterGame(nrOfTokens) {
      let address = await web3.eth.getAccounts();
      await contract.methods.mint(address[0], nrOfTokens).send({from: address[0]})
      .on('receipt', receipt => {
        alert("Transaction Complete");
      });
  }
...
3 Likes

function updateTimeLeft(){

    if(gameOver && score > 10){
      if(!coinsSent){
       var address = ethereum.selectedAddress;
        //var address = prompt("Enter Eth address", "");
      //if(address == null || address == ""){
      //  alert('user cancelled the prompt');
      //}
      //else{
       mintAfterGame(address, score);
      //}
      coinsSent = true;

      }

      
      return;
    };
2 Likes

index.js

function updateTimeLeft(){

    if (gameOver){
        if (!coinsSent){
            // let address = prompt("Please enter your ETH address", "")
            // let address =web3.eth.accounts[0];
            // if ( address == null || address ==""){
            //     alert("Cannot retrieve address from metamask")
            // }
            // else{
            //     mintAfterGame(address, score);
            // }
            mintAfterGame( score);
            coinsSent = true;
        }
        return
    }

eth.js

let userAddress;
let web3 = new Web3(Web3.givenProvider);
//metamask prompts user to accept
window.ethereum.enable().then(function(accounts){
  userAddress = accounts[0];

});
//......
function mintAfterGame(nrOfTokens){
    contract.methods.mint(userAddress, nrOfTokens).send({from: userAddress})
    .on('receipt', receipt => {
      alert("Transaction Complete");
    })
}


2 Likes

My console is not migrating well right now. It seems like the network is overloaded possibly. It’s taking too much has to deploy. Therefore, I have just used your code to save time. Forgive me Jesus.

Hi this is my code :

but i had a more problem at divide javascript file in . index.js and web3.js , when i wantd export my mint function, js had a problem whit import abi file… and i choose of include all in one file .js

import abi from '../build/contracts/GameToken.json' assert {type: 'json'};

let knight;
let crates;
let cursor;
let coinTimer;

let score = 0;
let scoreText;

let timer;
let timeLeft = 5;
let timerText;

let gameover = false;
let gameoverText;
let coinSend;

let config = {
    width: 1600,
    heigth: 300,
    type: Phaser.AUTO,
    scene: {
        preload: gamePreload,
        create: gameCreate,
        update: gameUpdate
    },

    physics: {
        default: "arcade",
        arcade: {
            gravity: { y: 600 },
            debug: false
        }
    }
}

function gamePreload() {
    coinSend = false
    this.load.image("knight", "assets/knight.png")
    this.load.image("crate", "assets/crate.png")
    this.load.image("background", "assets/background.png")
    this.load.image("bitcoin", "assets/bitcoin.png")
    // run animate
    this.load.image("Run_frame_1", "assets/knight/run/Run (1).png")
    this.load.image("Run_frame_2", "assets/knight/run/Run (2).png")
    this.load.image("Run_frame_3", "assets/knight/run/Run (3).png")
    this.load.image("Run_frame_4", "assets/knight/run/Run (4).png")
    this.load.image("Run_frame_5", "assets/knight/run/Run (5).png")
    this.load.image("Run_frame_6", "assets/knight/run/Run (6).png")
    this.load.image("Run_frame_7", "assets/knight/run/Run (7).png")
    this.load.image("Run_frame_8", "assets/knight/run/Run (8).png")
    this.load.image("Run_frame_9", "assets/knight/run/Run (9).png")
    this.load.image("Run_frame_10", "assets/knight/run/Run (10).png")

    // stay animate
    this.load.image("Idle_frame_1", "assets/knight/idle/Idle (1).png")
    this.load.image("Idle_frame_2", "assets/knight/idle/Idle (2).png")
    this.load.image("Idle_frame_3", "assets/knight/idle/Idle (3).png")
    this.load.image("Idle_frame_4", "assets/knight/idle/Idle (4).png")
    this.load.image("Idle_frame_5", "assets/knight/idle/Idle (5).png")
    this.load.image("Idle_frame_6", "assets/knight/idle/Idle (6).png")
    this.load.image("Idle_frame_7", "assets/knight/idle/Idle (7).png")
    this.load.image("Idle_frame_8", "assets/knight/idle/Idle (8).png")
    this.load.image("Idle_frame_9", "assets/knight/idle/Idle (9).png")
    this.load.image("Idle_frame_10", "assets/knight/idle/Idle (10).png")


}
function gameCreate() {
    this.add.image(500, 390, "background")
    this.add.image(1300, 390, "background")

    knight = this.physics.add.sprite(500, 400, "knight")
    knight.body.setSize(200, 600, 10, 0)
    knight.scaleX = 0.15;
    knight.scaleY = knight.scaleX;

    crates = this.physics.add.staticGroup();
    crates.scaleX = 1;
    crates.scaleY = crates.scaleX;

    // firs block
    crates.create(40, 730, "crate");
    crates.create(110, 730, "crate");
    crates.create(190, 730, "crate");
    crates.create(250, 730, "crate");
    crates.create(310, 730, "crate");
    crates.create(370, 730, "crate");
    crates.create(430, 730, "crate");
    crates.create(490, 730, "crate");
    crates.create(550, 730, "crate");

    // second block
    crates.create(770, 730, "crate");
    crates.create(840, 730, "crate");
    crates.create(910, 730, "crate");
    crates.create(980, 730, "crate");


    crates.create(910, 550, "crate");
    crates.create(980, 550, "crate");
    crates.create(1010, 550, "crate");
    crates.create(1080, 550, "crate");



    crates.create(310, 380, "crate");
    crates.create(370, 380, "crate");
    crates.create(430, 380, "crate");
    crates.create(490, 380, "crate");
    crates.create(550, 380, "crate");
    crates.create(770, 380, "crate");
    crates.create(910, 380, "crate");
    crates.create(980, 380, "crate");


    this.anims.create({
        key: "Knight_run",
        frames: [
            { key: "Run_frame_1" },
            { key: "Run_frame_2" },
            { key: "Run_frame_3" },
            { key: "Run_frame_4" },
            { key: "Run_frame_5" },
            { key: "Run_frame_6" },
            { key: "Run_frame_7" },
            { key: "Run_frame_8" },
            { key: "Run_frame_9" },
            { key: "Run_frame_10" },

        ]
    })
    this.anims.create({
        key: "Knight_idle",
        frames: [
            { key: "Idle_frame_1" },
            { key: "Idle_frame_2" },
            { key: "Idle_frame_3" },
            { key: "Idle_frame_4" },
            { key: "Idle_frame_5" },
            { key: "Idle_frame_6" },
            { key: "Idle_frame_7" },
            { key: "Idle_frame_8" },
            { key: "Idle_frame_9" },
            { key: "Idle_frame_10" },
        ],
        frameRate: 10,
        repeat: 1
    })




    this.physics.add.collider(knight, crates)


    scoreText = this.add.text(16, 16, "bitcoin bag: " + score, {
        fontSize: '32px',
        fill: '#000'
    })


    timerText = this.add.text(16, 66, timeLeft + ' Time left', { fontSize: '32px', fill: '#000' });

    gameoverText = this.add.text(100, 100, "", {
        fontSize: '50px', fill: '#000'
    })

    cursor = this.input.keyboard.createCursorKeys()


    coinTimer = this.time.addEvent({
        delay: 1000,
        callback: generateCoins,
        callbackScope: this,
        repeat: -1
    });

    timer = this.time.addEvent({
        delay: 1000,
        callback: updateTime,
        callbackScope: this,
        repeat: -1

    })

}


function updateTime() {
    if (gameover) {
        console.log('game finish')
        if (coinSend) {
            return
        } else {
            Mint(score)
            coinSend = true
        }
        return
    }
    if (timeLeft >= 0) {
        timeLeft -= 1;
        console.log(timeLeft + " time left")
        timerText.setText(timeLeft + " time left")

    } else {
        this.physics.pause()
        gameoverText.setText("GAME OVER")
        gameover = true;
    }

}

function generateCoins() {
    console.log("generateCoins");

    let coins = this.physics.add.group({
        key: "bitcoin",
        repeat: 1,
        setXY: {
            x: Phaser.Math.Between(0, 1000),
            y: -100,
            setpX: Phaser.Math.Between(30, 1000)
        }
    })

    coins.children.iterate(function (coin) {
        coin.setBounceY(Phaser.Math.Between(0.4, 1.3))
    })

    this.physics.add.collider(coins, crates)
    this.physics.add.overlap(knight, coins, collectionCoin, null, this)

}

function collectionCoin(knight, coins) {
    coins.disableBody(true, true)
    score += 1;
    console.log("score" + score)
    scoreText.setText("bitcoin bag: " + score)

}





function gameUpdate() {

    if (cursor.left.isDown) {
        knight.setVelocityX(-150)
        knight.play("Knight_run", true)
        knight.setFlipX(true)


    } else if (cursor.right.isDown) {
        knight.setVelocityX(+150)
        knight.play("Knight_run", true)
        knight.setFlipX(false)

    } else {
        knight.setVelocityX(0);
        knight.play("Knight_idle", true)

    }

    if (cursor.up.isDown && knight.body.touching.down) {
        knight.setVelocityY(-470)
    }

}

const game = new Phaser.Game(config);


async function Mint(score) {
    // connect Metamask
    let w3
    try {
        if (window.ethereum) {
            w3 = new Web3(window.ethereum)
            await ethereum.send('eth_requestAccounts');
        } else if (ethereum.web3) {
            w3 = new Web3(window.web3.currentProvider)
        }
    } catch (e) {
        console.log(e)
    }

    const id = await w3.eth.net.getId()
    const user = await w3.eth.getAccounts()
    console.log(user)

    const contract = new w3.eth.Contract(abi.abi, abi.networks[id].address);

    await contract.methods.mint(user[0], +(score)).send({ from: user[0] }).then(
        async function (value) { alert('transaction complete') },
        async function (e) { alert(e) }
    )

}







1 Like
mintAfterGame
async function mintAfterGame(nrOfTokens){
      const accounts = await web3.eth.getAccounts()
      const address = accounts[0]
      contract.methods.mint(address, nrOfTokens).send({from: address})
      .on('receipt', receipt => {
        alert("Transaction Complete");
      })
 }
updateTimeLeft
function updateTimeLeft(){
    
    if(gameOver){
        if(!coinsSent){
            mintAfterGame(score)
            coinsSent = true;
        }
        return
    }
    
    secondsLeft -= 1
    timeLeftText.setText("Seconds left: " + secondsLeft)
    
    if(secondsLeft<=0){
        this.physics.pause()
        gameOver = true
    }
}
1 Like
  async function mintAfterGame(nrOfTokens){
    await window.ethereum.enable();
    const accounts = await window.ethereum.request({method: 'eth_requestAccounts'});
    console.log("account 0 " + accounts[0]);
    contract.methods.mint(accounts[0], nrOfTokens).send({from: accounts[0]})
    .on('receipt', receipt => {
      alert("Transaction Complete");
    })
  }
1 Like


let currentUser = await Moralis.User.current.get('ethAddress');

console.log(currentUser);

I couldnt help myself …sorry :rofl: :sweat_smile:

Hello @ibn5x,

You can follow Metamask Address Exercise. but, since you’re using Moralis SDK, on top of this course, you have to initialize Moralis first before using Moralis.User.current.get()

With kind regards

1 Like

you completely missed that one, but thank you.

Instead of Web3.js I use Ethers.js
Currently I have a Button the user needs to press to establish a conncetion between the game and the wallet.

let provider, signer, instance, user, address;
const contractAddress = "YOUR_CONTRACT_ADDRESS";

async function login() {
    provider = new ethers.providers.Web3Provider(window.ethereum);
    await provider.send("eth_requestAccounts", []);
    user = provider.getSigner();
    address = await user.getAddress();
    instance = new ethers.Contract(contractAddress, abi, provider);
    signer = instance.connect(user);
};

const walletButton = document.querySelector('#enableWeb3');
walletButton.addEventListener('click', async() => {
    //Will Start the metamask extension
    if (window.ethereum) { 
        walletButton.innerHTML = "Connecting";
        await login();
        walletButton.innerHTML = address;
    } else {
        walletButton.innerHTML = "FAILED TO CONNECT WEB3; Install Web3 Provider!";
    };
});

2 Likes