You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.9 KiB

  1. package common
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. "math/big"
  6. "time"
  7. ethCommon "github.com/ethereum/go-ethereum/common"
  8. "github.com/hermeznetwork/tracerr"
  9. )
  10. // tokenIDBytesLen defines the length of the TokenID byte array representation
  11. const tokenIDBytesLen = 4
  12. // Token is a struct that represents an Ethereum token that is supported in Hermez network
  13. type Token struct {
  14. TokenID TokenID `json:"id" meddler:"token_id"`
  15. // EthBlockNum indicates the Ethereum block number in which this token was registered
  16. EthBlockNum int64 `json:"ethereumBlockNum" meddler:"eth_block_num"`
  17. EthAddr ethCommon.Address `json:"ethereumAddress" meddler:"eth_addr"`
  18. Name string `json:"name" meddler:"name"`
  19. Symbol string `json:"symbol" meddler:"symbol"`
  20. Decimals uint64 `json:"decimals" meddler:"decimals"`
  21. }
  22. // TokenInfo provides the price of the token in USD
  23. type TokenInfo struct {
  24. TokenID uint32
  25. Value float64
  26. LastUpdated time.Time
  27. }
  28. // TokenID is the unique identifier of the token, as set in the smart contract
  29. type TokenID uint32 // current implementation supports up to 2^32 tokens
  30. // Bytes returns a byte array of length 4 representing the TokenID
  31. func (t TokenID) Bytes() []byte {
  32. var tokenIDBytes [4]byte
  33. binary.BigEndian.PutUint32(tokenIDBytes[:], uint32(t))
  34. return tokenIDBytes[:]
  35. }
  36. // BigInt returns the *big.Int representation of the TokenID
  37. func (t TokenID) BigInt() *big.Int {
  38. return big.NewInt(int64(t))
  39. }
  40. // TokenIDFromBytes returns TokenID from a byte array
  41. func TokenIDFromBytes(b []byte) (TokenID, error) {
  42. if len(b) != tokenIDBytesLen {
  43. return 0, tracerr.Wrap(fmt.Errorf("can not parse TokenID, bytes len %d, expected 4",
  44. len(b)))
  45. }
  46. tid := binary.BigEndian.Uint32(b[:4])
  47. return TokenID(tid), nil
  48. }
  49. // TokenIDFromBigInt returns a TokenID with the value of the given *big.Int
  50. func TokenIDFromBigInt(b *big.Int) TokenID {
  51. return TokenID(b.Int64())
  52. }