forked from fbsobreira/gotron-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trc10.go
460 lines (422 loc) · 13.4 KB
/
trc10.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
package cmd
import (
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
"time"
"github.com/araddon/dateparse"
"github.com/fbsobreira/gotron-sdk/pkg/address"
"github.com/fbsobreira/gotron-sdk/pkg/client/transaction"
"github.com/fbsobreira/gotron-sdk/pkg/common"
"github.com/fbsobreira/gotron-sdk/pkg/keystore"
"github.com/fbsobreira/gotron-sdk/pkg/proto/core"
"github.com/fbsobreira/gotron-sdk/pkg/store"
"github.com/spf13/cobra"
)
var (
issueStartDate string
issueDuration uint32
issueFrozen []string
issueDecimals int32
)
func trc10Sub() []*cobra.Command {
cmdIssue := &cobra.Command{
Use: "issue <NAME> <DESCRIPTION> <SYMBOL> <URL> <TOTAL_SUPPLY> <RATIO>",
Short: "Check account balance",
Long: "Query for the latest account balance given Address",
Args: cobra.ExactArgs(6),
RunE: func(cmd *cobra.Command, args []string) error {
if signerAddress.String() == "" {
return fmt.Errorf("no signer specified")
}
trxNum := int64(1)
tokenNum := int64(1)
t, err := dateparse.ParseAny(issueStartDate)
if err != nil {
return err
}
if t.Before(time.Now()) {
return fmt.Errorf("start date cannot be prior issue")
}
if issueDecimals > 6 || issueDecimals < 0 {
return fmt.Errorf("decimals should be >= 0 && <= 6, found %d", issueDecimals)
}
if colon := strings.Index(args[5], ":"); colon > -1 {
if trxNum, err = strconv.ParseInt(args[5][:colon], 10, 32); err != nil {
return err
}
if tokenNum, err = strconv.ParseInt(args[5][colon+1:], 10, 32); err != nil {
return err
}
} else {
// use as float
ratio, err := strconv.ParseFloat(args[5], 32)
if err != nil {
return err
}
// round up to 6 decimals
p := math.Pow10(6)
ratio = float64(int(ratio*p)) / p
for float64(int64(ratio)) != ratio && tokenNum <= int64(math.Pow10(6)) {
ratio *= 10
tokenNum *= 10
}
if tokenNum > int64(math.Pow10(6)) {
return fmt.Errorf("invalid ratio")
}
trxNum = int64(ratio)
}
frozenSupply := make(map[string]string)
for _, value := range issueFrozen {
frozenSupplyKeyValue := strings.Split(value, ":")
if len(frozenSupplyKeyValue) != 2 {
return fmt.Errorf("invalid frozen supply %s", frozenSupplyKeyValue)
}
if len(frozenSupply[frozenSupplyKeyValue[0]]) > 0 {
return fmt.Errorf("frozen supply date colision %s:%s -> %s", frozenSupplyKeyValue[0], frozenSupply[frozenSupplyKeyValue[0]], value)
}
// update frozen supply with decimals
fSupply := ""
if s, err := strconv.ParseFloat(frozenSupplyKeyValue[1], 64); err == nil {
s *= math.Pow10(int(issueDecimals))
fSupply = strconv.FormatInt(int64(s), 10)
} else {
return fmt.Errorf("invalid frozen supply: %s", value)
}
frozenSupply[frozenSupplyKeyValue[0]] = fSupply
}
totalSupply, err := strconv.ParseInt(args[4], 10, 64)
if err != nil {
return err
}
// update total supply with decimals
totalSupply = int64(float64(totalSupply) * math.Pow10(int(issueDecimals)))
tx, err := conn.AssetIssue(signerAddress.String(),
args[0], // Name
args[1], // Description
args[2], // Symbol
args[3], // URL
issueDecimals,
totalSupply,
t.UTC().Unix()*1000,
t.Add(time.Duration(issueDuration)*time.Hour*24).UTC().Unix()*1000,
0, 0, //AssetLimit
int32(trxNum),
int32(tokenNum),
0, // Vote scores
frozenSupply, // Frozen list
)
if err != nil {
return err
}
var ctrlr *transaction.Controller
if useLedgerWallet {
account := keystore.Account{Address: signerAddress.GetAddress()}
ctrlr = transaction.NewController(conn, nil, &account, tx.Transaction, opts)
} else {
ks, acct, err := store.UnlockedKeystore(signerAddress.String(), passphrase)
if err != nil {
return err
}
ctrlr = transaction.NewController(conn, ks, acct, tx.Transaction, opts)
}
if err = ctrlr.ExecuteTransaction(); err != nil {
return err
}
if noPrettyOutput {
fmt.Println(tx)
return nil
}
result := make(map[string]interface{})
result["txID"] = common.BytesToHexString(tx.GetTxid())
result["blockNumber"] = ctrlr.Receipt.BlockNumber
result["message"] = string(ctrlr.Result.Message)
result["receipt"] = map[string]interface{}{
"fee": ctrlr.Receipt.Fee,
"netFee": ctrlr.Receipt.Receipt.NetFee,
"netUsage": ctrlr.Receipt.Receipt.NetUsage,
}
asJSON, _ := json.Marshal(result)
fmt.Println(common.JSONPrettyFormat(string(asJSON)))
return nil
},
}
// Asset issue extras
cmdIssue.Flags().StringVar(&issueStartDate, "start", time.Now().Add(10*time.Minute).String(), "start time")
cmdIssue.Flags().Uint32VarP(&issueDuration, "duration", "d", 30, "ico duration in days")
cmdIssue.Flags().StringSliceVarP(&issueFrozen, "frozen", "0", []string{}, "frozen supply day1:amount1,day2:amount2")
cmdIssue.Flags().Int32VarP(&issueDecimals, "decimals", "p", 0, "decimals precision (max 6)")
cmdSend := &cobra.Command{
Use: "send <ADDRESS_TO> <AMOUNT> <TOKEN_ID or TOKEN_NAME> ",
Short: "send TOKEN to an address",
Args: cobra.ExactArgs(3),
PreRunE: validateAddress,
RunE: func(cmd *cobra.Command, args []string) error {
if signerAddress.String() == "" {
return fmt.Errorf("no signer specified")
}
// get amount
value, err := strconv.ParseFloat(args[1], 64)
if err != nil {
return err
}
// Get asset information
// check if possible id
tokenID := ""
tokenDecimals := int32(0)
if _, err := strconv.Atoi(args[2]); err == nil {
if asset, err := conn.GetAssetIssueByID(args[2]); err == nil {
if asset.Id == args[2] {
tokenID = args[2]
tokenDecimals = asset.Precision
}
} else {
return fmt.Errorf("TRC10 not found: %s", args[3])
}
}
if len(tokenID) == 0 {
// try by name
if asset, err := conn.GetAssetIssueByName(args[2]); err == nil {
if string(asset.Name) == args[2] {
tokenID = asset.Id
tokenDecimals = asset.Precision
} else {
return fmt.Errorf("TRC10 not found: %s", args[3])
}
} else {
return fmt.Errorf("TRC10 not found: %s", args[3])
}
}
value = value * math.Pow10(int(tokenDecimals))
tx, err := conn.TransferAsset(signerAddress.String(), addr.String(), tokenID, int64(value))
if err != nil {
return err
}
var ctrlr *transaction.Controller
if useLedgerWallet {
account := keystore.Account{Address: signerAddress.GetAddress()}
ctrlr = transaction.NewController(conn, nil, &account, tx.Transaction, opts)
} else {
ks, acct, err := store.UnlockedKeystore(signerAddress.String(), passphrase)
if err != nil {
return err
}
ctrlr = transaction.NewController(conn, ks, acct, tx.Transaction, opts)
}
if err = ctrlr.ExecuteTransaction(); err != nil {
return err
}
if noPrettyOutput {
fmt.Println(tx)
return nil
}
result := make(map[string]interface{})
result["txID"] = common.BytesToHexString(tx.GetTxid())
result["blockNumber"] = ctrlr.Receipt.BlockNumber
result["message"] = string(ctrlr.Result.Message)
result["receipt"] = map[string]interface{}{
"fee": ctrlr.Receipt.Fee,
"netFee": ctrlr.Receipt.Receipt.NetFee,
"netUsage": ctrlr.Receipt.Receipt.NetUsage,
}
asJSON, _ := json.Marshal(result)
fmt.Println(common.JSONPrettyFormat(string(asJSON)))
return nil
},
}
cmdICO := &cobra.Command{
Use: "ico <TOKEN_ID or TOKEN_NAME> <AMOUNT>",
Short: "participate TOKEN ICO",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
if signerAddress.String() == "" {
return fmt.Errorf("no signer specified")
}
// get amount
value, err := strconv.ParseFloat(args[1], 64)
if err != nil {
return err
}
// Get asset information
// check if possible id
tokenID := ""
issuerAddress := ""
price := float64(0)
//tokenDecimals := int32(0)
if _, err := strconv.Atoi(args[0]); err == nil {
if asset, err := conn.GetAssetIssueByID(args[0]); err == nil {
if asset.Id == args[0] {
tokenID = args[0]
//tokenDecimals = asset.Precision
issuerAddress = address.Address(asset.GetOwnerAddress()).String()
price = float64(asset.GetTrxNum()) / float64(asset.GetNum())
}
} else {
return fmt.Errorf("TRC10 not found: %s", args[0])
}
}
if len(tokenID) == 0 {
// try by name
if asset, err := conn.GetAssetIssueByName(args[0]); err == nil {
if string(asset.Name) == args[0] {
tokenID = asset.Id
//tokenDecimals = asset.Precision
issuerAddress = address.Address(asset.GetOwnerAddress()).String()
price = float64(asset.GetTrxNum()) / float64(asset.GetNum())
} else {
return fmt.Errorf("TRC10 not found: %s", args[0])
}
} else {
return fmt.Errorf("TRC10 not found: %s", args[0])
}
}
// participate amount is TRX value
valueInt := int64(value * math.Pow10(6))
tx, err := conn.ParticipateAssetIssue(signerAddress.String(), issuerAddress, tokenID, valueInt)
if err != nil {
return err
}
var ctrlr *transaction.Controller
if useLedgerWallet {
account := keystore.Account{Address: signerAddress.GetAddress()}
ctrlr = transaction.NewController(conn, nil, &account, tx.Transaction, opts)
} else {
ks, acct, err := store.UnlockedKeystore(signerAddress.String(), passphrase)
if err != nil {
return err
}
ctrlr = transaction.NewController(conn, ks, acct, tx.Transaction, opts)
}
if err = ctrlr.ExecuteTransaction(); err != nil {
return err
}
if noPrettyOutput {
fmt.Println(tx)
return nil
}
result := make(map[string]interface{})
result["txID"] = common.BytesToHexString(tx.GetTxid())
result["blockNumber"] = ctrlr.Receipt.BlockNumber
result["message"] = string(ctrlr.Result.Message)
result["receipt"] = map[string]interface{}{
"fee": ctrlr.Receipt.Fee,
"netFee": ctrlr.Receipt.Receipt.NetFee,
"netUsage": ctrlr.Receipt.Receipt.NetUsage,
"price": price,
"cost": value,
"tokenAmount": float64(valueInt) * price,
}
asJSON, _ := json.Marshal(result)
fmt.Println(common.JSONPrettyFormat(string(asJSON)))
return nil
},
}
cmdList := &cobra.Command{
Use: "list",
Short: "list TRC10 tokens",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
list, err := conn.GetAssetIssueList(-1)
if err != nil {
return err
}
if noPrettyOutput {
fmt.Println(list.GetAssetIssue())
return nil
}
result := make(map[string]interface{})
result["total"] = len(list.GetAssetIssue())
result["list"] = make([]map[string]interface{}, 0)
for _, e := range list.GetAssetIssue() {
data := map[string]interface{}{
"ID": e.GetId(),
"Name": string(e.GetName()),
"Symbol": string(e.GetAbbr()),
"Decimals": e.GetPrecision(),
"Owner": address.Address(e.GetOwnerAddress()).String(),
"ICOStart": time.Unix(e.GetStartTime()/1000, 0),
"ICOEnd": time.Unix(e.GetEndTime()/1000, 0),
"TotalSupply": e.GetTotalSupply(),
"URL": string(e.GetUrl()),
"Price": float64(e.GetTrxNum()) / float64(e.GetNum()),
}
result["list"] = append(result["list"].([]map[string]interface{}), data)
}
asJSON, _ := json.Marshal(result)
fmt.Println(common.JSONPrettyFormat(string(asJSON)))
return nil
},
}
cmdInfo := &cobra.Command{
Use: "info <TOKEN_ID or ISSUER_ADDRESS or TOKEN_NAME> ",
Short: "get information about TRC10",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
var asset *core.AssetIssueContract
var err error
found := false
if _, err := strconv.Atoi(args[0]); err == nil {
if asset, err = conn.GetAssetIssueByID(args[0]); err == nil {
if asset.Id == args[0] {
found = true
}
}
}
if !found {
// try by name
if asset, err = conn.GetAssetIssueByName(args[0]); err == nil {
if string(asset.Name) == args[0] {
found = true
}
}
}
if !found {
// try by issuer
if list, err := conn.GetAssetIssueByAccount(args[0]); err == nil {
if len(list.AssetIssue) == 1 &&
address.Address(list.AssetIssue[0].GetOwnerAddress()).String() == args[0] {
asset = list.GetAssetIssue()[0]
found = true
}
}
}
if !found {
return fmt.Errorf("TRC 10 not found")
}
if noPrettyOutput {
fmt.Println(asset)
return nil
}
result := map[string]interface{}{
"ID": asset.GetId(),
"Name": string(asset.GetName()),
"Symbol": string(asset.GetAbbr()),
"Decimals": asset.GetPrecision(),
"Owner": address.Address(asset.GetOwnerAddress()).String(),
"ICOStart": time.Unix(asset.GetStartTime()/1000, 0),
"ICOEnd": time.Unix(asset.GetEndTime()/1000, 0),
"TotalSupply": asset.GetTotalSupply(),
"URL": string(asset.GetUrl()),
"Price": float64(asset.GetTrxNum()) / float64(asset.GetNum()),
}
asJSON, _ := json.Marshal(result)
fmt.Println(common.JSONPrettyFormat(string(asJSON)))
return nil
},
}
return []*cobra.Command{cmdIssue, cmdSend, cmdICO, cmdList, cmdInfo}
}
func init() {
cmdTrc10 := &cobra.Command{
Use: "trc10",
Short: "Assets Manager",
RunE: func(cmd *cobra.Command, args []string) error {
cmd.Help()
return nil
},
}
cmdTrc10.AddCommand(trc10Sub()...)
RootCmd.AddCommand(cmdTrc10)
}