forked from thirdweb-dev/go-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
snapshots.go
118 lines (98 loc) · 2.59 KB
/
snapshots.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
package thirdweb
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/cbergoon/merkletree"
"github.com/mitchellh/mapstructure"
)
type SnapshotInput struct {
Address string
MaxClaimable int
}
type SnapshotClaim struct {
Address string `json:"address"`
MaxClaimable int `json:"maxClaimable"`
Proof []string `json:"proof"`
}
type SnapshotInfo struct {
MerkleRoot string `json:"merkleRoot"`
Claims []SnapshotClaim `json:"claims"`
}
type SnapshotInfos struct {
Snapshot SnapshotInfo
MerkleRoot string
SnapshotUri string
}
type MerkleContent struct {
address string
}
func (t MerkleContent) CalculateHash() ([]byte, error) {
h := sha256.New()
if _, err := h.Write([]byte(t.address)); err != nil {
return nil, err
}
return h.Sum(nil), nil
}
func (t MerkleContent) Equals(other merkletree.Content) (bool, error) {
return t.address == other.(MerkleContent).address, nil
}
func createSnapshot(
snapshotInput []*SnapshotInput,
tokenDecimals int,
storage storage,
) (*SnapshotInfos, error) {
addresses := []string{}
for _, s := range snapshotInput {
addresses = append(addresses, s.Address)
}
hasDuplicates := make(map[string]bool)
for _, address := range addresses {
if hasDuplicates[address] {
return nil, fmt.Errorf("DUPLICATE_LEAFS: Address %s is duplicated in snapshot", address)
}
hasDuplicates[address] = true
}
merkleContent := []merkletree.Content{}
for _, address := range addresses {
merkleContent = append(merkleContent, MerkleContent{address: address})
}
tree, err := merkletree.NewTree(merkleContent)
if err != nil {
return nil, err
}
merkleRoot := hex.EncodeToString(tree.MerkleRoot())
claims := []SnapshotClaim{}
for _, s := range snapshotInput {
proof, _, _ := tree.GetMerklePath(MerkleContent{address: s.Address})
encodedProofs := []string{}
for _, p := range proof {
encodedProofs = append(encodedProofs, hex.EncodeToString(p))
}
claims = append(claims, SnapshotClaim{
Address: s.Address,
MaxClaimable: s.MaxClaimable,
Proof: encodedProofs,
})
}
snapshot := SnapshotInfo{
MerkleRoot: merkleRoot,
Claims: claims,
}
// TODO: Hash address and max claimable into content
// TODO: Upload metadata to IPFS
snapshotToUpload := map[string]interface{}{}
if err := mapstructure.Decode(snapshot, &snapshotToUpload); err != nil {
return nil, err
}
uri, err := storage.Upload(context.Background(), snapshotToUpload, "", "")
if err != nil {
return nil, err
}
return &SnapshotInfos{
Snapshot: snapshot,
MerkleRoot: merkleRoot,
SnapshotUri: uri,
}, nil
}