66 "fmt"
77 "math/big"
88 "strings"
9- "sync/atomic "
9+ "sync"
1010
1111 "github.com/ethereum/go-ethereum/accounts/abi/bind"
1212 "github.com/ethereum/go-ethereum/common"
@@ -22,6 +22,7 @@ type TxBuilder interface {
2222}
2323
2424type TxBuild struct {
25+ mu sync.Mutex
2526 client bind.ContractTransactor
2627 privateKey * ecdsa.PrivateKey
2728 signer types.Signer
@@ -69,10 +70,12 @@ func (b *TxBuild) Transfer(ctx context.Context, to string, value *big.Int) (comm
6970 return common.Hash {}, fmt .Errorf ("invalid transfer value: must be positive" )
7071 }
7172
73+ b .mu .Lock ()
74+ defer b .mu .Unlock ()
75+
7276 gasLimit := uint64 (21000 )
7377 toAddress := common .HexToAddress (to )
74-
75- nonce := b .getAndIncrementNonce ()
78+ nonce := b .nonce
7679
7780 var err error
7881 var unsignedTx * types.Transaction
@@ -99,6 +102,7 @@ func (b *TxBuild) Transfer(ctx context.Context, to string, value *big.Int) (comm
99102 return common.Hash {}, err
100103 }
101104
105+ b .nonce ++
102106 return signedTx .Hash (), nil
103107}
104108
@@ -143,10 +147,6 @@ func (b *TxBuild) buildLegacyTx(ctx context.Context, to *common.Address, value *
143147 }), nil
144148}
145149
146- func (b * TxBuild ) getAndIncrementNonce () uint64 {
147- return atomic .AddUint64 (& b .nonce , 1 ) - 1
148- }
149-
150150func (b * TxBuild ) refreshNonce (ctx context.Context ) {
151151 nonce , err := b .client .PendingNonceAt (ctx , b .Sender ())
152152 if err != nil {
@@ -157,7 +157,7 @@ func (b *TxBuild) refreshNonce(ctx context.Context) {
157157 return
158158 }
159159
160- atomic . StoreUint64 ( & b .nonce , nonce )
160+ b .nonce = nonce
161161 log .WithField ("nonce" , nonce ).Info ("Nonce refreshed successfully" )
162162}
163163
0 commit comments