/
contract.go
121 lines (98 loc) · 2.54 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package utils
import (
"context"
"errors"
"fmt"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/rpc"
"golang.org/x/crypto/sha3"
"strings"
)
const (
eip165SupportsInterfaceABI = ""
nft721InterfaceId = ""
)
// IsERC721 supportsInterface(0x80ac58cd)是否返回true
func IsERC721() {
}
func CalculateInterfaceId(contractABI string) []byte {
// 计算函数签名的 keccak256 哈希值
hash := sha3.NewLegacyKeccak256()
hash.Write([]byte(contractABI))
interfaceId := hash.Sum(nil)[:4] // 只取前4个字节作为 interfaceId
return interfaceId
}
func calculateSelector(selector string) []byte {
hash := sha3.NewLegacyKeccak256()
hash.Write([]byte(selector))
return hash.Sum(nil)[:4]
}
func DecodeABI(abiStr string) (*abi.ABI, error) {
contractAbi, err := abi.JSON(strings.NewReader(abiStr))
if err != nil {
return nil, err
}
return &contractAbi, nil
}
func Call(ctx context.Context, c *rpc.Client, contract string, method abi.Method) (any, error) {
to := common.HexToAddress(contract)
data := method.ID
callData := ðereum.CallMsg{
To: &to,
Data: data,
}
client := ethclient.NewClient(c)
result, err := client.CallContract(ctx, *callData, nil)
if err != nil {
return nil, err
}
out, err := method.Outputs.Unpack(result)
if err != nil {
return nil, err
}
return out[0], nil
}
func CallWithInput(ctx context.Context, c *rpc.Client, contract, methodName string, abiO *abi.ABI, args ...any) (any, error) {
to := common.HexToAddress(contract)
if len(args) == 0 {
return nil, errors.New("invalid input")
}
method := abiO.Methods[methodName]
data, err := abiO.Pack(methodName, args...)
if err != nil {
return nil, err
}
callData := ðereum.CallMsg{
To: &to,
Data: data,
}
client := ethclient.NewClient(c)
result, err := client.CallContract(ctx, *callData, nil)
if err != nil {
return nil, err
}
out, err := method.Outputs.Unpack(result)
if err != nil {
return nil, err
}
return out[0], nil
}
func CodeAt(ctx context.Context, c *rpc.Client, contract string) (string, error) {
client := ethclient.NewClient(c)
code, err := client.CodeAt(ctx, common.HexToAddress(contract), nil)
if err != nil {
return "", err
}
fmt.Println(common.Bytes2Hex(code))
return calcCodeHash(code), nil
}
func calcCodeHash(code []byte) string {
if len(code) == 0 {
return "0x"
}
return crypto.Keccak256Hash(code).Hex()
}