/
contract.go
48 lines (43 loc) · 1.41 KB
/
contract.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package eth
import (
"context"
"fmt"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"math/big"
"strings"
)
func DeployContract(opts *bind.TransactOpts, backend bind.ContractBackend, jsonAbi string, bytecode string, params ...interface{}) (common.Address, *types.Transaction, error) {
parsed, err := abi.JSON(strings.NewReader(jsonAbi))
if err != nil {
return common.Address{}, nil, err
}
address, tx, _, err := bind.DeployContract(opts, parsed, common.FromHex(bytecode), backend, params...)
if err != nil {
return common.Address{}, nil, err
}
return address, tx, nil
}
func EstimateContractMethodGas(param TransactBaseParam, backend bind.ContractBackend, contractAddress common.Address, input []byte) (int64, error) {
err := param.EnsureGasPrice(backend)
if err != nil {
return 0, err
}
ethValue := param.EthValue
if ethValue == nil {
ethValue = big.NewInt(0)
}
msg := ethereum.CallMsg{From: param.From, To: &contractAddress,
GasPrice: param.GasPrice,
GasFeeCap: param.GasFeeCap,
GasTipCap: param.GasTipCap,
Value: ethValue, Data: input}
gasLimit, err := backend.EstimateGas(context.Background(), msg)
if err != nil {
return 0, fmt.Errorf("failed to estimate gas needed: %v", err)
}
return int64(gasLimit), nil
}