thirdweb-dev / go-sdk

Best in class web3 SDK for Go 1.16+
Apache License 2.0
38 stars 33 forks source link

Add support for websocket rpc connections #131

Open itsahedge opened 1 year ago

itsahedge commented 1 year ago

As of version 2.0.2, the Go SDK does not support websocket rpc connections because in the getDefaultRpc() function, it checks:

if strings.HasPrefix(rpcUrlorName, "http") {
    return rpcUrlorName, nil
} else {
    return "", fmt.Errorf("invalid rpc url or chain name: %s", rpcUrlorName)
}

Adding websocket support would make it easier to handle listening on contract events.

example: wss://goerli.infura.io/ws/v3/{your-infura-project-id}

solution:

func getDefaultRpcUrl(rpcUrlorName string) (string, error) {
    switch rpcUrlorName {
    case "mumbai":
        return defaultRpc("mumbai")
    case "goerli":
        return defaultRpc("goerli")
    case "polygon":
        return defaultRpc("polygon")
    case "mainnet", "ethereum":
        return defaultRpc("ethereum")
    case "fantom":
        return defaultRpc("fantom")
    case "avalanche":
        return defaultRpc("avalanche")
    case "optimism":
        return defaultRpc("optimism")
    case "optimism-goerli":
        return defaultRpc("optimism-goerli")
    case "arbitrum":
        return defaultRpc("arbitrum")
    case "arbitrum-goerli":
        return defaultRpc("arbitrum-goerli")
    default:
        if strings.HasPrefix(rpcUrlorName, "http") || strings.HasPrefix(rpcUrlorName, "wss") {
            return rpcUrlorName, nil
        } else {
            return "", fmt.Errorf("invalid rpc url or chain name: %s", rpcUrlorName)
        }
    }
}
joaquim-verges commented 1 year ago

Thank you for reporting this @itsahedge - would you like to put up a PR for this? Contributions are always welcome!

itsahedge commented 1 year ago
|| strings.HasPrefix(rpcUrlorName, "wss")

https://github.com/thirdweb-dev/go-sdk/pull/132