Deploying Smart Contracts to Geth Using Truffle

Published on
2 mins read
--- views

Using Truffle with Geth Instead of Ganache

So, as a real blockchain developer, you may want to test your smart contract not only on Ganache (an in-memory blockchain emulator), but also in an environment that closely resembles a real blockchain. In this case, you're going to use Go Ethereum (Geth) and most likely Truffle for writing, testing, and deploying your contracts.

Using Ganache + Truffle is easy — they feel like they were made for each other. But pairing Truffle + Geth often brings issues. In this post, I’ll walk you through solving the problems I encountered.

Environment Setup

  • Go Ethereum (geth) version: 1.10.19-stable (for ARM64)
  • Truffle version: 5.5.18
  • Goal: Deploy smart contracts through Truffle to Geth and be able to interact with them.

Geth Command

geth --networkid 4224 --mine --miner.threads 1 --datadir "./private" --nodiscover -port "30303" --nat "any" \
  --http --http.api personal,eth,net,web3 \
  --ws --ws.api personal,eth,net,web3 \
  --password ./private/password.sec --ipcpath "~/Library/Ethereum/geth.ipc"

Notice the --password flag — it points to a password file for unlocking the account securely.

Truffle Configuration (truffle-config.js)

geth: {
  host: "127.0.0.1",
  port: 8545,
  network_id: 4224,
  from: '0x6db7f74b66403832fc2cfa40d6ee79f1b6915e37',
}

Create this account using:

geth --datadir . account new

You can skip the password prompt or use a file.

The Problem

Running:

truffle migrate --network geth
Truffle error

Results in an authentication error.

Solution: Unlock the Account

Add --allow-insecure-unlock to your Geth command:

geth ... --allow-insecure-unlock

Modify the Truffle Migration Script

Update migrations/1_initial_migration.js:

const Migrations = artifacts.require('Migrations');
const TruffleConfig = require('../truffle-config');
const Web3 = require('web3');

module.exports = function (deployer, network, accounts) {
  const config = TruffleConfig.networks[network];
  if (process.env.ACCOUNT_PASSWORD) {
    const web3 = new Web3(new Web3.providers.HttpProvider(`http://\${config.host}:\${config.port}`));
    web3.eth.personal.getAccounts().then((accounts) => {
      const defaultAccount = accounts[0];
      console.log(`[x] Unlocking account \${defaultAccount}`);
      web3.eth.personal.unlockAccount(defaultAccount, process.env.ACCOUNT_PASSWORD);
    });
  }
  console.log('[x] Making migrations');
  deployer.deploy(Migrations);
};

Option 2: Unlock in Geth Console

  1. Start Geth
  2. In another terminal:
geth attach
Geth attach
  1. Then:
personal.unlockAccount('0x6db7f74b66403832fc2cfa40d6ee79f1b6915e37', 'your_password');
  1. Re-run the migration:
truffle migrate --network geth
Truffle migrate

You're good to go!