github.com/hungdoo/bot@v0.0.0-20240325145135-dd1f386f7b81/src/packages/tombplus/adaptor.go (about)

     1  package tombplus
     2  
     3  import (
     4  	"context"
     5  	"crypto/ecdsa"
     6  	"fmt"
     7  	"math/big"
     8  
     9  	"github.com/ethereum/go-ethereum/accounts/abi/bind"
    10  	"github.com/ethereum/go-ethereum/common"
    11  	"github.com/ethereum/go-ethereum/core/types"
    12  	"github.com/ethereum/go-ethereum/ethclient"
    13  )
    14  
    15  var _contract *Tombplus
    16  
    17  func GetTombplusContract(ec *ethclient.Client, contractAdr common.Address) (*Tombplus, error) {
    18  	if _contract != nil {
    19  		return _contract, nil
    20  	}
    21  	_contract, err := NewTombplus(contractAdr, ec)
    22  	if err != nil {
    23  		return nil, err
    24  	}
    25  	return _contract, nil
    26  }
    27  
    28  func NewAuthorizedTransactor(ec *ethclient.Client, privateKeyECDSA *ecdsa.PrivateKey, gaslimit uint64, maxGas *big.Int, value *big.Int) (*bind.TransactOpts, error) {
    29  	ctx := context.Background()
    30  	fromAddress, err := AddressFromPriKey(privateKeyECDSA)
    31  	if err != nil {
    32  		return nil, err
    33  	}
    34  
    35  	nonce, err := ec.PendingNonceAt(ctx, fromAddress)
    36  	if err != nil {
    37  		return nil, fmt.Errorf("failed to get nonce: %w", err)
    38  	}
    39  
    40  	chainID, err := ec.ChainID(ctx)
    41  	if err != nil {
    42  		return nil, fmt.Errorf("failed to get chainId: %w", err)
    43  	}
    44  	gasPrice, err := ec.SuggestGasPrice(ctx)
    45  	if err != nil {
    46  		return nil, fmt.Errorf("failed to get gasPrice: %w", err)
    47  	}
    48  	// gasPrice = min(gasPrice, maxGas)
    49  	if maxGas == nil || gasPrice.Cmp(maxGas) >= 1 { // maxGas is nil (user oracle price) or ftm gas > maxGas
    50  		gasPrice = maxGas
    51  	}
    52  	signerFn := func(address common.Address, transaction *types.Transaction) (*types.Transaction, error) {
    53  		return types.SignTx(transaction, types.LatestSignerForChainID(chainID), privateKeyECDSA)
    54  	}
    55  	opts := &bind.TransactOpts{
    56  		From:     fromAddress,
    57  		Signer:   signerFn,
    58  		GasPrice: gasPrice,
    59  		GasLimit: gaslimit, // 0 = estimate
    60  		Value:    value,
    61  		Nonce:    big.NewInt(int64(nonce)),
    62  		NoSend:   true,
    63  	}
    64  
    65  	return opts, nil
    66  }