How to fix 'write tcp 127.0.0.1:54917->127.0.0.1:8545: i/o timeout' error in golang code that listens to smart contract events
Asked Answered
F

0

10

I am using golang to listen to the smart contract events. I deployed my contracts to ganache ui and ganache-cli ports. But I get the below error:

➜  sc_events go run main.go

2019/04/17 14:25:04 write tcp 127.0.0.1:54917->127.0.0.1:8545: i/o timeout
exit status 1

I tried using both ganache ui (listens to port 7545) and ganache-cli (8545). Both of them seems to yield the same error. But If I listen to infura URL, I don't think I get this error,

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/ethereum/go-ethereum"
    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/core/types"
    "github.com/ethereum/go-ethereum/ethclient"
)

func main() {
    client, err := ethclient.Dial("ws://127.0.0.1:8545")
    // client, err := ethclient.Dial("wss://rinkeby.infura.io/ws/v3/010590bb415e4664835a05a53b18a293")
    if err != nil {
        log.Fatal(err)
    }

    contractAddress := common.HexToAddress("0x82726c7c1202565f1fef63fa8d4caca6366d4749")
    query := ethereum.FilterQuery{
        Addresses: []common.Address{contractAddress},
    }

    logs := make(chan types.Log)

    sub, err := client.SubscribeFilterLogs(context.Background(), query, logs)
    if err != nil {
        log.Fatal(err)
    }

    for {
        select {
        case err := <-sub.Err():
            log.Fatal(err)
        case vLog := <-logs:
            fmt.Println(vLog) // pointer to event log
        }
    }
}

I am expecting the code to keep listening to smart contract events. Also, If someone can also post the code to decode the event object into the Map data structure to read it, would be helpful.

Faun answered 17/4, 2019 at 9:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.