[Ethereum] How truffle selects the address with which it deploys a smart contract with and where does it gets it’s private keys

contract-deploymentganachetruffle

I am reading truffle tutorials for deployment smart contract to gauche, I've never deployed any smart contract to real network.
Now when migrate (deploy) a smart contract I get these info:

1_initial_migration.js
======================

   Replacing 'Migrations'
   ----------------------
   > transaction hash:    0x2d01568d6461be2557bb7b58c30fb0288e183ce090503a374caa635d1415b82e
   > Blocks: 0            Seconds: 0
   > contract address:    0xeCE6C3Df643eeaBeF14FB22Ec59025b3614337bb
   > account:             0xe04dAA90D31e43d860b36EA3E3DFdF962CFF0210
   > balance:             99.98776428
   > gas used:            284844
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.00569688 ETH


   Deploying 'Coin'
   ----------------
   > transaction hash:    0x7cf73aac0c7bc19cae31b170ab3987a51a7642029862abe62f03fe712a1d0437
   > Blocks: 0            Seconds: 0
   > contract address:    0x2FE15cC795B06e0369fBA40BE1E6004344f87818
   > account:             0xe04dAA90D31e43d860b36EA3E3DFdF962CFF0210
   > balance:             99.97940696
   > gas used:            417866
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.00835732 ETH


   > Saving migration to chain.
   > Saving artifacts
   -------------------------------------
   > Total cost:           0.0140542 ETH


Summary
=======
> Total deployments:   2
> Final cost:          0.0140542 ETH

enter image description here
From the screenshot below it can be seen that the smart contract is deployed with the address 0xe04dAA90D31e43d860b36EA3E3DFdF962CFF0210
how does truffle chooses this address, where it gets it's private key, and how to change this address if desired ?

Best Answer

Truffle uses the Web3 coinbase account (the first account in the list) to deploy the contract. Web3, in turn, gets the account data over HTTP and it is either unlocked (when using ganach) or locked when using Meta Mask chrome extension or Infura.

You can list all the available Web3 accounts (in your truffle console for example) with

web3.eth.getAccounts((e,a) => { accounts=a; });

or in your js file with

let getAccount = async () => {
   const accounts = await web3.eth.getAccounts()
}

If you want to change the default account from which it is deploying you can configure the 'from' field your truffle.js file.

module.exports = {
  networks: {
    development: {
      host: 'localhost',
      port: 8545,
      network_id: '*', // Match any network id
      from: '0xA21983B35C767CF8609D95F4886C9A18A194D8AA'
    }
  }
}

alternatively you could see here how to change the default account in a js file.

Another Advice: Always check which web3 version you are using there are many differences between the old and the new >1.0 version.