-
Notifications
You must be signed in to change notification settings - Fork 1
/
felt.go
73 lines (62 loc) · 1.25 KB
/
felt.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
package data
import (
"bytes"
"encoding/hex"
"strconv"
"strings"
"github.com/dipdup-io/starknet-go-api/pkg/encoding"
"github.com/shopspring/decimal"
)
// Felt -
type Felt string
// NewFeltFromBytes -
func NewFeltFromBytes(hash []byte) Felt {
return Felt(encoding.EncodeHex(hash))
}
// NewFromAsciiString -
func NewFromAsciiString(s string) Felt {
return Felt("0x" + hex.EncodeToString([]byte(s)))
}
// String -
func (f Felt) String() string {
return string(f)
}
// Decimal -
func (f Felt) Decimal() decimal.Decimal {
return encoding.DecimalFromHex(f.String())
}
// Uint64 -
func (f Felt) Uint64() (uint64, error) {
if f == "" {
return 0, nil
}
return strconv.ParseUint(f.String(), 0, 64)
}
// Bytes -
func (f Felt) Bytes() []byte {
if len(f) == 0 {
return nil
}
data := encoding.MustDecodeHex(f.String())
if len(data) < AddressBytesLength {
padding := bytes.Repeat([]byte{0}, AddressBytesLength-len(data))
data = append(padding, data...)
}
return data
}
// ToAsciiString -
func (f Felt) ToAsciiString() string {
s := strings.TrimPrefix(f.String(), "0x")
if len(s)%2 == 1 {
s = "0" + s
}
b, err := hex.DecodeString(s)
if err != nil {
return f.String()
}
return string(b)
}
// Length -
func (f Felt) Length() int {
return len(f)
}