瀏覽代碼

nonce可以自动获取

skyfffire 2 年之前
父節點
當前提交
bf53a68fcd
共有 2 個文件被更改,包括 21 次插入7 次删除
  1. 18 6
      arbitrage/easy_wallet.go
  2. 3 1
      arbitrage/history.go

+ 18 - 6
arbitrage/easy_wallet.go

@@ -7,6 +7,7 @@ import (
 	"github.com/ethereum/go-ethereum/core/types"
 	"github.com/ethereum/go-ethereum/internal/ethapi"
 	"github.com/ethereum/go-ethereum/params"
+	"github.com/ethereum/go-ethereum/rpc"
 	"math/big"
 )
 
@@ -22,8 +23,18 @@ func NewEasyWallet(wallet accounts.Wallet, account accounts.Account) *EasyWallet
 	}
 }
 
-func (e *EasyWallet) SendTest(api *ethapi.PrivateAccountAPI) {
-	nonce := hexutil.Uint64(uint64(0))
+func (e *EasyWallet) SendTest(accountApi *ethapi.PrivateAccountAPI, txApi *ethapi.PublicTransactionPoolAPI) {
+	ctx := context.Background()
+	blockOrNbr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
+
+	// 获取nonce
+	nonce, err := txApi.GetTransactionCount(ctx, e.account.Address, blockOrNbr)
+	if err != nil {
+		HistoryError("Get transaction count error.", "error", err.Error())
+		return
+	}
+	HistoryInfo("Get transaction count", "addr", e.account.Address, "nonce", nonce)
+
 	gasLimit := hexutil.Uint64(uint64(21000))
 	gasPrice := hexutil.Big(*big.NewInt(30 * 1e9))
 	callData := hexutil.Bytes{}
@@ -32,7 +43,7 @@ func (e *EasyWallet) SendTest(api *ethapi.PrivateAccountAPI) {
 	toAddr := e.account.Address
 
 	sendArgs := ethapi.SendTxArgs{
-		Nonce:    &nonce,
+		Nonce:    nonce,
 		Gas:      &gasLimit,
 		GasPrice: &gasPrice,
 		Data:     &callData,
@@ -41,12 +52,13 @@ func (e *EasyWallet) SendTest(api *ethapi.PrivateAccountAPI) {
 		To:       &toAddr,
 	}
 
-	hash, err := api.SignAndSendTransaction(context.Background(), sendArgs, "")
+	hash, err := accountApi.SignAndSendTransaction(ctx, sendArgs, "")
 	if err != nil {
 		HistoryError("Send error.", "error", err.Error())
-	} else {
-		HistoryInfo("Send ok.", "hash", hash)
+		return
 	}
+
+	HistoryInfo("Send ok.", "hash", hash)
 }
 
 func (e *EasyWallet) OnlySignTest() {

+ 3 - 1
arbitrage/history.go

@@ -22,6 +22,7 @@ type HistoryArbitrage struct {
 	blockChainApi *ethapi.PublicBlockChainAPI
 	ethereumApi   *ethapi.PublicEthereumAPI
 	accountApi    *ethapi.PrivateAccountAPI
+	txApi         *ethapi.PublicTransactionPoolAPI
 }
 
 func RegisterHistoryArbitrage(stack *node.Node, ctx *cli.Context, apiBackend ethapi.Backend) {
@@ -39,6 +40,7 @@ func RegisterHistoryArbitrage(stack *node.Node, ctx *cli.Context, apiBackend eth
 		blockChainApi: ethapi.NewPublicBlockChainAPI(apiBackend),
 		ethereumApi:   ethapi.NewPublicEthereumAPI(apiBackend),
 		accountApi:    ethapi.NewPrivateAccountAPI(apiBackend, addrLock),
+		txApi:         ethapi.NewPublicTransactionPoolAPI(apiBackend, addrLock),
 	}
 
 	h.Register()
@@ -90,7 +92,7 @@ func (h *HistoryArbitrage) run() {
 	// 配置钱包
 	h.setupWallets()
 
-	h.wallets[0].SendTest(h.accountApi)
+	h.wallets[0].SendTest(h.accountApi, h.txApi)
 
 running:
 	for {