github.com/0xsequence/ethkit@v1.25.0/ethcontract/ethcontract.go (about)

     1  package ethcontract
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/0xsequence/ethkit"
     7  	"github.com/0xsequence/ethkit/ethcoder"
     8  	"github.com/0xsequence/ethkit/go-ethereum/accounts/abi"
     9  	"github.com/0xsequence/ethkit/go-ethereum/accounts/abi/bind"
    10  	"github.com/0xsequence/ethkit/go-ethereum/common"
    11  )
    12  
    13  type Contract struct {
    14  	*bind.BoundContract
    15  	Address common.Address
    16  	ABI     abi.ABI
    17  }
    18  
    19  func NewContractCaller(address common.Address, abi abi.ABI, caller bind.ContractCaller) *Contract {
    20  	return NewContract(address, abi, caller, nil, nil)
    21  }
    22  
    23  func NewContractTransactor(address common.Address, abi abi.ABI, caller bind.ContractCaller, transactor bind.ContractTransactor) *Contract {
    24  	return NewContract(address, abi, caller, transactor, nil)
    25  }
    26  
    27  func NewContractFilterer(address common.Address, abi abi.ABI, filterer bind.ContractFilterer) *Contract {
    28  	return NewContract(address, abi, nil, nil, filterer)
    29  }
    30  
    31  func NewContract(address common.Address, abi abi.ABI, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) *Contract {
    32  	contract := &Contract{
    33  		BoundContract: bind.NewBoundContract(address, abi, caller, transactor, filterer),
    34  		Address:       address,
    35  		ABI:           abi,
    36  	}
    37  	return contract
    38  }
    39  
    40  func (c *Contract) Encode(method string, args ...interface{}) ([]byte, error) {
    41  	m, ok := c.ABI.Methods[method]
    42  	if !ok {
    43  		return nil, fmt.Errorf("contract method %s not found", method)
    44  	}
    45  	input, err := m.Inputs.Pack(args...)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  	input = append(m.ID, input...)
    50  	return input, nil
    51  }
    52  
    53  func (c *Contract) EventTopicHash(eventName string) (ethkit.Hash, error) {
    54  	ev, ok := c.ABI.Events[eventName]
    55  	if !ok {
    56  		return ethkit.Hash{}, fmt.Errorf("ethcontract: event '%s' not found in contract abi", eventName)
    57  	}
    58  	h := ethcoder.Keccak256Hash([]byte(ev.Sig))
    59  	return h, nil
    60  }