User Avatar

full_duplex

Web3

3y ago

Engineer, photographer, mountain biker.

How to interact with Eth smart contracts from geth console
full_duplex

Most of us don't interact with Ethereum smart contracts directly, most of the time. They all come with beautiful Web UIs that hide the complexity. But what if you need to play with some of the functionality not exposed in the UI yet? Or automate a contract interaction to mint that rare NFT without having to wake up early?

Such contract interactions and automations can be done directly in the geth' javascript console. Here is how, using ArtBlocks contract as an example.

1. Find the address of the contract

Usually developers list it somewhere in the docs, or it can be extracted from the Dapp javascript code in the browser.

For ArtBlocks, it's 0xa7d8d9ef8D8Ce8992Df33D8b8CF4Aebabd5bD270.

2. Find the contract ABI

Contract ABI lists all the functions in the contract and their prototypes. To find the ABI, go to etherscan.io, find the contract page using its address and navigate to the Contract/Code section. Scroll down to the Contract ABI section and copy it from there.

This will only work for the majority of contracts that have their source code available. For ones that don't, you'll have to reverse-engineer the contract, which is a much longer discussion.

3. Create the contract instance

Now we have everything we need to start writing code. Fire up the geth console, and create the contract instance using the address and the ABI we obtained in the previous steps. Replace <abi> with the ABI you copied.

blocks = web3.eth.contract(<abi>)
blocks_ins = blocks.at("0xa7d8d9ef8D8Ce8992Df33D8b8CF4Aebabd5bD270")

4. Interact with the contract

We are finally ready to play with the contract. For example, let's find the details about the project 163, Meridian.

blocks_ins.projectDetails.call(163)

["Meridian", "Matt DesLauriers", "Stratified landforms constructed from many small strokes of colour. The hash of each token describes a coordinate within a multidimensional generative space, locating a unique composition that lies along one of many possible longitudes.", "https://mattdesl.com/", "CC BY-NC 4.0", true]

To get the Javascript code that generates the Meridian, we can just call the projectScriptByIndex() function:

blocks_ins.projectScriptByIndex.call(163, 0)

You can find the list of other functions available and arguments they take on the contract's etherscan page.

5. Write your code

You can now write the automation code that interacts with the contract. This can be any valid Javascript code, so possibilities are endless.

At this point you'll probably want to write it in a file. That file can be loaded by geth on attach:

geth attach --preload myscript.js

The all-in-one writing platform.

Write, publish everywhere, see what works, and become a better writer - all in one place.

Trusted by 80,000+ writers