-
Notifications
You must be signed in to change notification settings - Fork 0
/
SRC20Api.go
111 lines (98 loc) · 2.06 KB
/
SRC20Api.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
package ethapi
import (
"strings"
"github.com/dece-cash/go-dece/czero/c_type"
"github.com/dece-cash/go-dece/accounts/abi"
)
const getDecimalByNameDefinition = `[{
"constant": false,
"inputs": [{
"name": "name",
"type": "string"
}],
"name": "getDecimal",
"outputs": [{
"name": "",
"type": "uint8"
}],
"payable": false,
"type": "function"
}]`
const getDecimalDefinition = `[{
"constant": true,
"inputs": [],
"name": "getDecimal",
"outputs": [{
"name": "",
"type": "uint8"
}],
"payable": false,
"type": "function"
}]`
const decimalsDefinition = `[{
"constant": true,
"inputs": [],
"name": "decimals",
"outputs": [{
"name": "",
"type": "uint8"
}],
"payable": false,
"type": "function"
}]`
type SRC20Decimal struct {
tokenName string
definition string
method string
}
func NewSRC20Decimal(tokenName string) []SRC20Decimal {
result := []SRC20Decimal{
{tokenName, decimalsDefinition, "decimals"},
{tokenName, getDecimalByNameDefinition, "getDecimal"},
{tokenName, getDecimalDefinition, "getDecimal"},
}
return result
}
type SRCAbi interface {
Pack() ([]byte, error)
Unpack(outData []byte) (*uint8, error)
}
func packDecimalData(out []byte) []byte {
prefix := [18]byte{}
rand := c_type.RandUint128()
copy(prefix[:], rand[:])
l := 18 + len(out)
result := make([]byte, l)
copy(result[:18], prefix[:])
copy(result[18:], out[:])
return result[:]
}
func (d SRC20Decimal) Pack() ([]byte, error) {
abi, err := abi.JSON(strings.NewReader(d.definition))
if err != nil {
return []byte{}, err
}
method := abi.Methods[d.method]
var out []byte
if len(method.Inputs) > 0 {
out, err = abi.Pack(d.method, d.tokenName)
} else {
out, err = abi.Pack(d.method)
}
if err != nil {
return []byte{}, err
}
return packDecimalData(out[:]), nil
}
func (d SRC20Decimal) Unpack(outData []byte) (*uint8, error) {
abi, err := abi.JSON(strings.NewReader(d.definition))
if err != nil {
return nil, err
}
var decimal uint8
err = abi.Unpack(&decimal, d.method, outData)
if err != nil {
return nil, err
}
return &decimal, nil
}