3

I am trying to send a raw transaction with eth.sendTransaction but I am getting an error that says {"code":-32000,"message":"unknown account"}. I am not sure what is causing this and I cant seem to find an answer on the internet. Can anyone help me figure it out? Here is my code:

func ExecuteSignedTransaction(rawTransaction string) {
    var hash web3.Hash
    data := make(map[string]interface{})
    data["data"] = rawTransaction
    err := Web3HTTPClient.Call("eth_sendTransaction", &hash, data)

    if err != nil{
        fmt.Println(err)
        Os.Exit(1)
     }

    fmt.Println("Sent tx hash:", hash)
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
0xKitsune
  • 131
  • 6
  • 1
    You'd need to sign the transaction using something like a `*bind.TransactOpts` instance. My general recommendation would be to use something like the pre-existing `*ethclient.Client` found in the go-ethereum package, which provides incredibly useful interfaces for doing things like this -- there's also far more documentation on it that you might've been able to find otherwise. However, if you'd prefer not to use `*ethclient.Client`, look into signing your rawTransaction with the private key of an account you control. – bluebunny Nov 02 '21 at 05:36

1 Answers1

1

So, what I might do here:

import (
  "strings"
  "crypto/ecdsa"
  "math/big"
  "github.com/ethereum/go-ethereum/ethclient"
  "github.com/ethereum/go-ethereum/crypto"
  "github.com/ethereum/go-ethereum/accounts/abi/bind"
)

var chainId = big.NewInt(1) // chain id for the ethereum mainnet, change according to needs

func ecdsaPrivateKeyFromHex(privKeyHex string) *ecdsa.PrivateKey {
  ecdsaKey, err := crypto.HexToECDSA(privKeyHex)
  if err != nil { panic(err) }

  return ecdsaKey
}

func newTransactOpts(privKey *ecdsa.PrivateKey) *bind.TransactOpts {
  transactOpts, err := bind.NewKeyedTransactorWithChainID(privKey, chainId)
  if err != nil { panic(err) }

  return transactOpts
}

func newRpcClient() *ethclient.Client {
  c, err := ethclient.Dial("insert rpc url here")
  if err != nil { panic(err) }
  
  return c
}

// note: constructing the *types.Transaction object left as 
// an exercise to the reader
func ExecuteTransaction(rawTransaction *types.Transaction) {
  privKeyHex := "0xblahblahblahblahblah" // use your own account's private key
  transactOpts := newTransactOpts(ecdsaPrivateKeyFromHex(privKeyHex))

  signedTxn, err := transactOpts.Signer(transactOpts.From, rawTransaction)
  if err != nil { panic(err) }
  
  rpcClient := newRpcClient()
  if err := rpcClient.SendTransaction(context.Background(), signedTxn); err != nil { panic(err) }

  // do whatever
}
bluebunny
  • 295
  • 3
  • 13