-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontract.go
364 lines (333 loc) · 9.63 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package nft
import (
"encoding/json"
"errors"
"fmt"
"math/big"
"net/http"
"os"
"github.com/dragonchain/dragonchain-sdk-go"
)
var (
// BigZero is a math/big.Int with a value of 0.
BigZero = big.NewInt(0)
bigOne = big.NewInt(1)
// ErrNoExist is returned when a requested resource does not exist.
ErrNoExist = errors.New("resource does not exist")
// ErrAlreadyExists is returned when a resource already exists and it shouldn't.
ErrAlreadyExists = errors.New("resource already exists")
// ErrInvalidBigIntString is returned when a String cannot be converted to a big.Int
ErrInvalidBigIntString = errors.New("big.Int invalid")
)
// Client is a client for interacting with the DragonChain API.
type Client interface {
GetSmartContractObject(key, smartContractID string) (*dragonchain.Response, error)
}
// Contract is a DCRC1-compatible smart contract.
type Contract interface {
Name() string
Symbol() string
BalanceOf(owner string) (uint64, error)
OwnerOf(tokenID string) (string, error)
Mint(to, tokenID string) error
Burn(tokenID string) error
Transfer(from, to, tokenID string) error
TotalSupply() (*big.Int, error)
TokensOwnedBy(owner string) ([]string, error)
}
// DefaultContract is a basic NFT smart contract implementation that is designed to work with
// the DragonChain platform.
type DefaultContract struct {
TokenOwners map[string]string `json:"tokenOwners,omitempty"`
OwnedTokens map[string][]string `json:"ownedTokens,omitempty"`
OwnedTokenIndex map[string]uint64 `json:"ownedTokenIndex,omitempty"`
TotalTokens string `json:"totalTokens,omitempty"`
ContractName string `json:"name"`
ContractSymbol string `json:"symbol"`
client Client
}
// NewDefaultContract returns a DefaultContract that uses the provided DragonChain client.
func NewDefaultContract(name, symbol string, client Client) *DefaultContract {
return &DefaultContract{
ContractName: name,
ContractSymbol: symbol,
client: client,
}
}
// Name returns the name of the Contract.
func (c *DefaultContract) Name() string {
return c.ContractName
}
// Symbol returns the Contract's symbol.
func (c *DefaultContract) Symbol() string {
return c.ContractSymbol
}
// BalanceOf returns the current number of NFTs owned by owner.
func (c *DefaultContract) BalanceOf(owner string) (uint64, error) {
tokens, err := c.TokensOwnedBy(owner)
return uint64(len(tokens)), err
}
// OwnerOf returns the address of the current owner of a token.
func (c *DefaultContract) OwnerOf(tokenID string) (string, error) {
if c.TokenOwners == nil {
if err := c.fetchTokenOwners(); err != nil {
return "", err
}
}
if owner, ok := c.TokenOwners[tokenID]; ok {
return owner, nil
}
return "", ErrNoExist
}
// Mint mints a new token with the provided ID and assigns it to the "to" address.
func (c *DefaultContract) Mint(to, tokenID string) error {
if c.TokenOwners == nil {
if err := c.fetchTokenOwners(); err != nil {
return err
}
}
if c.OwnedTokens == nil {
if err := c.fetchOwnedTokens(); err != nil {
return err
}
}
if c.OwnedTokenIndex == nil {
if err := c.fetchOwnedTokenIndices(); err != nil {
return err
}
}
// If the token already exists, we don't want to remint it.
if _, ok := c.TokenOwners[tokenID]; ok {
return ErrAlreadyExists
}
totalTokens, err := c.TotalSupply()
if err != nil {
return err
}
// add token to "to" address
c.TokenOwners[tokenID] = to
balance, err := c.BalanceOf(to)
if err != nil && err != ErrNoExist {
return err
}
c.OwnedTokens[to] = append(c.OwnedTokens[to], tokenID)
c.OwnedTokenIndex[tokenID] = balance
c.TotalTokens = totalTokens.Add(totalTokens, bigOne).String()
return nil
}
// Burn destroys a token and removes it from its owner.
func (c *DefaultContract) Burn(tokenID string) error {
owner, err := c.OwnerOf(tokenID)
if err != nil {
return err
}
return c.removeToken(owner, tokenID)
}
// Transfer transfers the token with the given id from the "from" address to the "to" address.
func (c *DefaultContract) Transfer(from, to, tokenID string) error {
if c.TokenOwners == nil {
if err := c.fetchTokenOwners(); err != nil {
return err
}
}
if c.OwnedTokens == nil {
if err := c.fetchOwnedTokens(); err != nil {
return err
}
}
if c.OwnedTokenIndex == nil {
if err := c.fetchOwnedTokenIndices(); err != nil {
return err
}
}
balance, err := c.BalanceOf(to)
if err != nil && err != ErrNoExist {
return err
}
// Make sure the token is actually owned by the from address.
tokenIndex, ok := c.OwnedTokenIndex[tokenID]
if !ok {
return ErrNoExist
}
// Make sure the from address has tokens to begin with.
if _, ok := c.OwnedTokens[from]; !ok {
return ErrNoExist
}
// remove token from "from" address
delete(c.TokenOwners, tokenID)
c.OwnedTokens[from] = append(c.OwnedTokens[from][:tokenIndex], c.OwnedTokens[from][tokenIndex+1:]...)
if len(c.OwnedTokens[from]) == 0 {
delete(c.OwnedTokens, from)
}
delete(c.OwnedTokenIndex, tokenID)
// add token to "to" address
c.TokenOwners[tokenID] = to
c.OwnedTokens[to] = append(c.OwnedTokens[to], tokenID)
c.OwnedTokenIndex[tokenID] = balance
return nil
}
// TotalSupply returns the current known supply of the token. This supply is updated
// every time a new token is minted.
func (c *DefaultContract) TotalSupply() (*big.Int, error) {
if totalSupply, err := BigIntString(c.TotalTokens); err == nil {
return totalSupply, nil
}
if err := c.fetchTotalSupply(); err != nil {
return BigZero, err
}
if c.TotalTokens == "" {
return BigZero, nil
}
return BigIntString(c.TotalTokens)
}
// TokensOwnedBy returns the list of token ids owned by owner.
func (c *DefaultContract) TokensOwnedBy(owner string) ([]string, error) {
if c.OwnedTokens == nil {
if err := c.fetchOwnedTokens(); err != nil {
return nil, err
}
}
if tokens, ok := c.OwnedTokens[owner]; ok {
return tokens, nil
}
return nil, ErrNoExist
}
// GetDragonObject fetches an object with the provided key from the DragonChain smart
// contract's heap. An error is returned if the object could not be fetched.
func (c *DefaultContract) GetDragonObject(key string) ([]byte, error) {
resp, err := c.client.GetSmartContractObject(key, "")
if err != nil {
return nil, err
}
// TODO: Handle not found case.
if !resp.OK {
if resp.Status == http.StatusNotFound {
return []byte{}, nil
}
return nil, fmt.Errorf("bad status code %d received from DragonChain GetSmartContractObject API request: %s", resp.Status, string(resp.Response.([]byte)))
}
return resp.Response.([]byte), nil
}
func (c *DefaultContract) removeToken(from, tid string) error {
if c.TokenOwners == nil {
if err := c.fetchTokenOwners(); err != nil {
return err
}
}
if c.OwnedTokens == nil {
if err := c.fetchOwnedTokens(); err != nil {
return err
}
}
if c.OwnedTokenIndex == nil {
if err := c.fetchOwnedTokenIndices(); err != nil {
return err
}
}
totalTokens, err := c.TotalSupply()
if err != nil {
return err
}
tokenIndex, ok := c.OwnedTokenIndex[tid]
if !ok {
return ErrNoExist
}
// remove token from "from" address
delete(c.TokenOwners, tid)
c.OwnedTokens[from] = append(c.OwnedTokens[from][:tokenIndex], c.OwnedTokens[from][tokenIndex+1:]...)
if len(c.OwnedTokens[from]) == 0 {
delete(c.OwnedTokens, from)
}
delete(c.OwnedTokenIndex, tid)
c.TotalTokens = totalTokens.Sub(totalTokens, bigOne).String()
return nil
}
func (c *DefaultContract) fetchOwnedTokens() error {
resp, err := c.GetDragonObject("ownedTokens")
if err != nil {
return err
}
if len(resp) == 0 {
c.OwnedTokens = make(map[string][]string)
return nil
}
var m map[string][]string
if err = json.Unmarshal(resp, &m); err != nil {
return err
}
c.OwnedTokens = m
return nil
}
func (c *DefaultContract) fetchTokenOwners() error {
resp, err := c.GetDragonObject("tokenOwners")
if err != nil {
return err
}
if len(resp) == 0 {
c.TokenOwners = make(map[string]string)
return nil
}
var m map[string]string
if err = json.Unmarshal(resp, &m); err != nil {
return err
}
c.TokenOwners = m
return nil
}
func (c *DefaultContract) fetchOwnedTokenIndices() error {
resp, err := c.GetDragonObject("ownedTokenIndex")
if err != nil {
return err
}
if len(resp) == 0 {
c.OwnedTokenIndex = make(map[string]uint64)
return nil
}
var m map[string]uint64
if err = json.Unmarshal(resp, &m); err != nil {
return err
}
c.OwnedTokenIndex = m
return nil
}
func (c *DefaultContract) fetchTotalSupply() error {
resp, err := c.GetDragonObject("totalSupply")
if err != nil {
return err
}
if len(resp) != 0 {
c.TotalTokens = string(resp)
}
return nil
}
// BigIntString is a convenience function for creating a big.Int from string. The string is assumed to be
// a base 10 number. If the big.Int could not be created from the provided string, the second boolean return
// argument will be false.
func BigIntString(s string) (*big.Int, error) {
bi := &big.Int{}
bi, ok := bi.SetString(s, 10)
if !ok {
return BigZero, ErrInvalidBigIntString
}
return bi, nil
}
// DefaultContractFactory creates a new DefaultContract from the heap.
type DefaultContractFactory struct{}
// CreateContract returns a new DefaultContract.
func (f *DefaultContractFactory) CreateContract(name, symbol string) (Contract, error) {
dcClient, err := dragonClient()
if err != nil {
return nil, fmt.Errorf("failed to create dragonchain client: %s", err)
}
return NewDefaultContract(name, symbol, dcClient), nil
}
func dragonClient() (*dragonchain.Client, error) {
httpClient := &http.Client{}
creds, err := dragonchain.NewCredentials("", "", "", dragonchain.HashSHA256)
if err != nil {
return nil, err
}
baseAPIURL := os.Getenv("DRAGONCHAIN_ENDPOINT")
client := dragonchain.NewClient(creds, baseAPIURL, httpClient)
return client, nil
}