forked from hashgraph/hedera-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
contract_id.go
91 lines (76 loc) · 2.26 KB
/
contract_id.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
package hedera
import (
"fmt"
protobuf "github.com/golang/protobuf/proto"
"github.com/hashgraph/hedera-sdk-go/v2/proto"
)
// ContractID is the ID for a Hedera smart contract
type ContractID struct {
Shard uint64
Realm uint64
Contract uint64
}
// ContractIDFromString constructs a ContractID from a string formatted as `Shard.Realm.Contract` (for example "0.0.3")
func ContractIDFromString(s string) (ContractID, error) {
shard, realm, num, err := idFromString(s)
if err != nil {
return ContractID{}, err
}
return ContractID{
Shard: uint64(shard),
Realm: uint64(realm),
Contract: uint64(num),
}, nil
}
// ContractIDFromSolidityAddress constructs a ContractID from a string representation of a solidity address
func ContractIDFromSolidityAddress(s string) (ContractID, error) {
shard, realm, contract, err := idFromSolidityAddress(s)
if err != nil {
return ContractID{}, err
}
return ContractID{
Shard: shard,
Realm: realm,
Contract: contract,
}, nil
}
// String returns the string representation of a ContractID formatted as `Shard.Realm.Contract` (for example "0.0.3")
func (id ContractID) String() string {
return fmt.Sprintf("%d.%d.%d", id.Shard, id.Realm, id.Contract)
}
// ToSolidityAddress returns the string representation of the ContractID as a solidity address.
func (id ContractID) ToSolidityAddress() string {
return idToSolidityAddress(id.Shard, id.Realm, id.Contract)
}
func (id ContractID) toProtobuf() *proto.ContractID {
return &proto.ContractID{
ShardNum: int64(id.Shard),
RealmNum: int64(id.Realm),
ContractNum: int64(id.Contract),
}
}
func contractIDFromProtobuf(pb *proto.ContractID) ContractID {
return ContractID{
Shard: uint64(pb.ShardNum),
Realm: uint64(pb.RealmNum),
Contract: uint64(pb.ContractNum),
}
}
func (id ContractID) toProtoKey() *proto.Key {
return &proto.Key{Key: &proto.Key_ContractID{ContractID: id.toProtobuf()}}
}
func (id ContractID) ToBytes() []byte {
data, err := protobuf.Marshal(id.toProtobuf())
if err != nil {
return make([]byte, 0)
}
return data
}
func ContractIDFromBytes(data []byte) (ContractID, error) {
pb := proto.ContractID{}
err := protobuf.Unmarshal(data, &pb)
if err != nil {
return ContractID{}, err
}
return contractIDFromProtobuf(&pb), nil
}