Skip to content

Commit

Permalink
support inline network specification with tx hash string, when tx is …
Browse files Browse the repository at this point in the history
…put as matic:0x... it will override -k param, this is to prepare jarvis to support working with multiple txs across multiple networks and multiple wallets at one session, support -Y option to answer Yes to all Y/N prompts
  • Loading branch information
tranvictor committed Apr 13, 2023
1 parent 5f80af6 commit fbb3f9a
Show file tree
Hide file tree
Showing 15 changed files with 285 additions and 355 deletions.
47 changes: 37 additions & 10 deletions bleve/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import (
"fmt"
"io/ioutil"
"log"
"math/rand"
"os"
"os/exec"
"os/user"
"path"
"path/filepath"
Expand All @@ -19,12 +21,25 @@ import (
)

var (
BLEVE_PATH string = filepath.Join(getHomeDir(), ".jarvis", "db.bleve")
BLEVE_DATA_PATH string = filepath.Join(getHomeDir(), ".jarvis", "bleve.data")
bleveDB *BleveDB
once sync.Once
BLEVE_PATH string = filepath.Join(getHomeDir(), ".jarvis", "db.bleve")
BLEVE_DATA_PATH string = filepath.Join(getHomeDir(), ".jarvis", "bleve.data")
THIS_SESSION_BLEVE_DATA_PATH string
bleveDB *BleveDB
bleveDBSession string
once sync.Once
)

func getRandomSessionBleveDataPath() string {
if bleveDBSession == "" {
rand.Seed(time.Now().UnixNano())
b := make([]byte, 8)
rand.Read(b)
bleveDBSession = fmt.Sprintf("%x", b)
}

return filepath.Join(getHomeDir(), ".jarvis", fmt.Sprintf("bleve_%s.data", bleveDBSession))
}

func getHomeDir() string {
usr, err := user.Current()
if err != nil {
Expand Down Expand Up @@ -92,8 +107,9 @@ func getDataFromDefaultFile() (result map[string]string, hash string) {
}

type BleveDB struct {
index bleve.Index
Hash string
index bleve.Index
Hash string
Session string
}

func buildIndexMapping() mapping.IndexMapping {
Expand All @@ -113,8 +129,8 @@ func buildIndexMapping() mapping.IndexMapping {
return indexMapping
}

func loadIndex(db *BleveDB) error {
index, err := bleve.Open(BLEVE_DATA_PATH)
func loadIndex(db *BleveDB, path string) error {
index, err := bleve.Open(path)
if err != nil && err != bleve.ErrorIndexPathDoesNotExist {
return err
}
Expand All @@ -128,7 +144,7 @@ func loadIndex(db *BleveDB) error {
if err == bleve.ErrorIndexPathDoesNotExist {
// here index file doesn't exist, create one
indexMapping := buildIndexMapping()
index, err = bleve.New(BLEVE_DATA_PATH, indexMapping)
index, err = bleve.New(path, indexMapping)
if err != nil {
return err
}
Expand Down Expand Up @@ -161,14 +177,25 @@ func loadBleveDB() (*BleveDB, error) {
return result, nil
}

func CopyBleveDataFileToSession() error {
return exec.Command("cp", "-R", BLEVE_DATA_PATH, THIS_SESSION_BLEVE_DATA_PATH).Run()
}

func NewBleveDB() (*BleveDB, error) {
var resError error
once.Do(func() {
bleveDB, resError = loadBleveDB()
if resError != nil {
return
}
resError = loadIndex(bleveDB)

// THIS_SESSION_BLEVE_DATA_PATH = getRandomSessionBleveDataPath()
// resError = CopyBleveDataFileToSession()
// if resError != nil {
// return
// }

resError = loadIndex(bleveDB, BLEVE_DATA_PATH)
})
return bleveDB, resError
}
Expand Down
81 changes: 62 additions & 19 deletions cmd/contract.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"io/ioutil"
"strings"
"time"

"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
Expand Down Expand Up @@ -101,7 +102,7 @@ Param rules:
return
}

data, err := util.PromptTxData(
data, err := cmdutil.PromptTxData(
analyzer,
contractAddress,
config.MethodIndex,
Expand Down Expand Up @@ -147,7 +148,7 @@ var txContractCmd = &cobra.Command{
return
}

data, err := util.PromptTxData(
data, err := cmdutil.PromptTxData(
analyzer,
config.To,
config.MethodIndex,
Expand Down Expand Up @@ -178,7 +179,7 @@ var txContractCmd = &cobra.Command{
config.GasPrice+config.ExtraGasPrice,
data,
)
err = util.PromptTxConfirmation(
err = cmdutil.PromptTxConfirmation(
analyzer,
util.GetJarvisAddress(config.From, config.Network()),
tx,
Expand All @@ -198,29 +199,70 @@ var txContractCmd = &cobra.Command{
return
}

signedTx, err := account.SignTx(tx)
if err != nil {
fmt.Printf("%s", err)
return
}

if config.DontBroadcast {
signedTx, err := account.SignTx(tx)
if err != nil {
fmt.Printf("%s", err)
return
}
data, err := rlp.EncodeToBytes(signedTx)
if err != nil {
fmt.Printf("Couldn't encode the signed tx: %s", err)
return
}
fmt.Printf("Signed tx: %s\n", hexutil.Encode(data))
} else {
tx, broadcasted, err := account.SignTxAndBroadcast(tx)
if config.DontWaitToBeMined {
util.DisplayBroadcastedTx(
tx, broadcasted, err, config.Network(),
)
var broadcasted bool

if config.RetryBroadcast {
ticker := time.NewTicker(500 * time.Millisecond)
quit := make(chan struct{})
broadcastedCh := make(chan *struct{})
go func() {
for {
select {
case <-ticker.C:
tx, broadcasted, err = account.Broadcast(signedTx)
if broadcasted {
broadcastedCh <- nil
close(quit)
} else {
fmt.Printf("Couldn't broadcast tx: %s. Retry in a while.\n", err)
}
case <-quit:
ticker.Stop()
return
}
}
}()

select {
case <-broadcastedCh:
if config.DontWaitToBeMined {
util.DisplayBroadcastedTx(
tx, broadcasted, err, config.Network(),
)
} else {
util.DisplayWaitAnalyze(
reader, analyzer, tx, broadcasted, err, config.Network(),
a, nil, config.DegenMode,
)
}
}

} else {
util.DisplayWaitAnalyze(
reader, analyzer, tx, broadcasted, err, config.Network(),
a, nil, config.DegenMode,
)
tx, broadcasted, err := account.Broadcast(signedTx)
if config.DontWaitToBeMined {
util.DisplayBroadcastedTx(
tx, broadcasted, err, config.Network(),
)
} else {
util.DisplayWaitAnalyze(
reader, analyzer, tx, broadcasted, err, config.Network(),
a, nil, config.DegenMode,
)
}
}
}
},
Expand Down Expand Up @@ -333,7 +375,7 @@ var readContractCmd = &cobra.Command{
return
}

methods := util.AllZeroParamFunctions(a)
methods := cmdutil.AllZeroParamFunctions(a)
for i := range methods {
method := methods[i]
resultJSON.Functions = append(resultJSON.Functions, method.Name)
Expand Down Expand Up @@ -369,7 +411,7 @@ var readContractCmd = &cobra.Command{
return
}

method, params, err := util.PromptFunctionCallData(
method, params, err := cmdutil.PromptFunctionCallData(
analyzer,
config.To,
config.MethodIndex,
Expand Down Expand Up @@ -410,6 +452,7 @@ func init() {
txContractCmd.PersistentFlags().BoolVarP(&config.DontBroadcast, "dry", "d", false, "Will not broadcast the tx, only show signed tx.")
txContractCmd.PersistentFlags().BoolVarP(&config.DontWaitToBeMined, "no-wait", "F", false, "Will not wait the tx to be mined.")
txContractCmd.PersistentFlags().BoolVarP(&config.ForceERC20ABI, "erc20-abi", "e", false, "Use ERC20 ABI where possible.")
txContractCmd.PersistentFlags().BoolVarP(&config.RetryBroadcast, "retry-broadcast", "r", false, "Retry broadcasting as soon as possible.")
txContractCmd.PersistentFlags().StringVarP(&config.CustomABI, "abi", "c", "", "Custom abi. It can be either an address, a path to an abi file or an url to an abi. If it is an address, the abi of that address from etherscan will be queried. This param only takes effect if erc20-abi param is not true.")
txContractCmd.Flags().StringVarP(&config.RawValue, "amount", "v", "0", "Amount of eth to send. It is in eth value, not wei.")
txContractCmd.MarkFlagRequired("from")
Expand Down
10 changes: 5 additions & 5 deletions cmd/msig.go
Original file line number Diff line number Diff line change
Expand Up @@ -254,10 +254,10 @@ var newMsigCmd = &cobra.Command{

cAddr := crypto.CreateAddress(HexToAddress(config.From), config.Nonce).Hex()

data, err := util.PromptTxData(
data, err := cmdutil.PromptTxData(
analyzer,
cAddr,
util.CONSTRUCTOR_METHOD_INDEX,
cmdutil.CONSTRUCTOR_METHOD_INDEX,
config.PrefillParams,
config.PrefillMode,
msigABI,
Expand Down Expand Up @@ -289,7 +289,7 @@ var newMsigCmd = &cobra.Command{
}
tx := BuildContractCreationTx(config.Nonce, config.Value, config.GasLimit+config.ExtraGasLimit, config.GasPrice+config.ExtraGasPrice, bytecode)

err = util.PromptTxConfirmation(
err = cmdutil.PromptTxConfirmation(
analyzer,
util.GetJarvisAddress(config.From, config.Network()),
tx,
Expand Down Expand Up @@ -379,7 +379,7 @@ var initMsigCmd = &cobra.Command{

data := []byte{}
if a != nil && !config.NoFuncCall {
data, err = util.PromptTxData(
data, err = cmdutil.PromptTxData(
analyzer,
config.MsigTo,
config.MethodIndex,
Expand Down Expand Up @@ -428,7 +428,7 @@ var initMsigCmd = &cobra.Command{
strings.ToLower(config.MsigTo): a,
strings.ToLower(config.To): msigABI,
}
err = util.PromptTxConfirmation(
err = cmdutil.PromptTxConfirmation(
analyzer,
util.GetJarvisAddress(config.From, config.Network()),
tx,
Expand Down
8 changes: 8 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,14 @@ func Execute() {
"Set to enable degen prints such as detailed contract calls, nonces... Default false",
)

rootCmd.PersistentFlags().BoolVarP(
&config.YesToAllPrompt,
"yes",
"Y",
false,
"Automatically Yes to all Y/N prompts",
)

if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
Expand Down
7 changes: 5 additions & 2 deletions cmd/send.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/ethereum/go-ethereum/rlp"
"github.com/spf13/cobra"
"github.com/tranvictor/jarvis/accounts"
cmdutil "github.com/tranvictor/jarvis/cmd/util"
. "github.com/tranvictor/jarvis/common"
"github.com/tranvictor/jarvis/config"
"github.com/tranvictor/jarvis/msig"
Expand Down Expand Up @@ -58,7 +59,7 @@ func handleMsigSend(
txdata,
)

err = util.PromptTxConfirmation(
err = cmdutil.PromptTxConfirmation(
analyzer,
util.GetJarvisAddress(config.From, config.Network()),
t,
Expand Down Expand Up @@ -158,7 +159,7 @@ func handleSend(
)
}

err = util.PromptTxConfirmation(
err = cmdutil.PromptTxConfirmation(
analyzer,
util.GetJarvisAddress(config.From, config.Network()),
t,
Expand Down Expand Up @@ -469,7 +470,9 @@ exact addresses start with 0x.`,
} else {
to = toAddr
}

reader, err := util.EthReader(config.Network())

if err != nil {
fmt.Printf("Couldn't establish connection to node: %s\n", err)
return
Expand Down
5 changes: 4 additions & 1 deletion cmd/util/pre_process.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,14 @@ func CommonFunctionCallPreprocess(cmd *cobra.Command, args []string) (err error)
} else {
config.To, _, err = util.GetAddressFromString(args[0])
if err != nil {
txs := util.ScanForTxs(args[0])
networks, txs := ScanForTxs(args[0])
if len(txs) == 0 {
return fmt.Errorf("can't interpret the contract address")
}
config.Tx = txs[0]
if networks[0] != "" {
config.SetNetwork(networks[0])
}

reader, err := util.EthReader(config.Network())
if err != nil {
Expand Down
Loading

0 comments on commit fbb3f9a

Please sign in to comment.