Skip to content

Commit

Permalink
add output to json file param to all transactional cmd
Browse files Browse the repository at this point in the history
  • Loading branch information
tranvictor committed Apr 26, 2024
1 parent 63a79b6 commit 3d696f4
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 6 deletions.
2 changes: 2 additions & 0 deletions cmd/common_flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,6 @@ func AddCommonFlagsToTransactionalCmds(c *cobra.Command) {
BoolVarP(&config.RetryBroadcast, "retry-broadcast", "r", false, "Retry broadcasting as soon as possible.")
c.PersistentFlags().
BoolVarP(&config.ForceLegacy, "legacy-tx", "L", false, "Force using legacy transaction")
c.PersistentFlags().
StringVarP(&config.JSONOutputFile, "json-output", "o", "", "write signed transaction info to json file. It will not create or write the file if the transaction wasn't signed")
}
49 changes: 43 additions & 6 deletions cmd/util/util.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package util

import (
"encoding/json"
"fmt"
"io/ioutil"
"math/big"
"regexp"
"strings"
Expand Down Expand Up @@ -365,24 +367,59 @@ func HandleApproveOrRevokeOrExecuteMsig(
}
}

type signedTxResultJSON struct {
Tx *types.Transaction `json:"transaction"`
TxHash string `json:"txHash"`
SenderAddress string `json:"senderAddress"`
SignedHex string `json:"signedHex"`
}

func (s *signedTxResultJSON) Write(filepath string) {
data, _ := json.MarshalIndent(s, "", " ")
err := ioutil.WriteFile(filepath, data, 0644)
if err != nil {
fmt.Printf("Writing to json file failed: %s\n", err)
}
}

func HandlePostSign(
signedTx *types.Transaction,
reader *reader.EthReader,
analyzer *txanalyzer.TxAnalyzer,
a *abi.ABI,
) (broadcasted bool, err error) {
signedData, err := rlp.EncodeToBytes(signedTx)
if err != nil {
fmt.Printf("Couldn't encode the signed tx: %s", err)
return false, fmt.Errorf("Couldn't encode the signed tx: %w", err)
}
signedHex := hexutil.Encode(signedData)

signerHex, err := GetSignerAddressFromTx(
signedTx,
big.NewInt(int64(config.Network().GetChainID())),
)
if err != nil {
return false, fmt.Errorf("Couldn't derive sender address from signed tx: %w", err)
}

resultJSON := signedTxResultJSON{
Tx: signedTx,
TxHash: signedTx.Hash().Hex(),
SenderAddress: signerHex.Hex(),
SignedHex: signedHex,
}
if config.JSONOutputFile != "" {
defer resultJSON.Write(config.JSONOutputFile)
}

broadcaster, err := util.EthBroadcaster(config.Network())
if err != nil {
return false, err
}

if config.DontBroadcast {
data, err := rlp.EncodeToBytes(signedTx)
if err != nil {
fmt.Printf("Couldn't encode the signed tx: %s", err)
return false, fmt.Errorf("Couldn't encode the signed tx: %w", err)
}
fmt.Printf("Signed tx: %s\n", hexutil.Encode(data))
fmt.Printf("Signed tx: %s\n", signedHex)
return false, nil
}

Expand Down

0 comments on commit 3d696f4

Please sign in to comment.