MetaMask Wallet in Web3.py – How to Use a MetaMask Wallet from Web3.py?

infurametamaskwalletsweb3.py

I deployed contracts to Ropsten test net using truffle and a metamask wallet to pay for the transactions and Infura as a Hosted ethereum node.

To do that in Truffle, I have to use the truffle-hdwallet-provider package to import the keys from my metamask wallet.

var HDWalletProvider = require("truffle-hdwallet-provider")
const mnemonic = "mnemonic words from metamask here"

module.exports = {
 networks : {
    ganache : {
      host : 'localhost',
      port : 8545,    // By default Ganache runs on this port.
      network_id : "*" // network_id for ganache is 5777. However, by keeping * as value you can run this node on  any network
    },
     ropsten: {
        provider: function(){
            return new HDWalletProvider(mnemonic,'https://ropsten.infura.io/v3/<infura_api_key>')
        },
         network_id: 3,
         gas: 4500000,
     }
  }
};

Now I want to Use web3.py to interact with the contracts and I am using the Automatic infura connector from web3.py, web3.auto.infura.w3. I didn't find in the documentation how to import the keys from my metamask wallet to pay for the transactions on the Ropsten network.

for example: suppose I have a contract instance, and I want to call a function on it:

token_contract_instance = w3.eth.contract(address=token_address, abi=token_artifact['abi'])
bal = token_contract_instance.functions.balanceOf(address).call()

But I want that msg.sender on this call to be the ethereum address I created with metamask.

Notice this is taking place in the server-side of the web app.

My guess is that the answer is to define eth.DefaultAccount but the deocumentation is non-existing for this method.

Can anyone show me how to do this?

Best Answer

You have access to the network through infura as you said. Web3py allows you to do everything (signing, sending, etc.) which is what you are doing with metamask -on websites. Metamask is running on the browser! and it injects web3 so that the methods to interact with the network are available in your webpage (and also allows you to sign transactions without exposing your keys).

In short, web3py allows you to do all you need without intermediary applications.