github.com/stafiprotocol/go-substrate-rpc-client@v1.4.7/types/header.go (about)

     1  // Go Substrate RPC Client (GSRPC) provides APIs and types around Polkadot and any Substrate-based chain RPC calls
     2  //
     3  // Copyright 2020 Stafi Protocol
     4  //
     5  // Licensed under the Apache License, Version 2.0 (the "License");
     6  // you may not use this file except in compliance with the License.
     7  // You may obtain a copy of the License at
     8  //
     9  //     http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  // Unless required by applicable law or agreed to in writing, software
    12  // distributed under the License is distributed on an "AS IS" BASIS,
    13  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14  // See the License for the specific language governing permissions and
    15  // limitations under the License.
    16  
    17  package types
    18  
    19  import (
    20  	"encoding/json"
    21  	"math/big"
    22  	"strconv"
    23  	"strings"
    24  
    25  	"github.com/stafiprotocol/go-substrate-rpc-client/pkg/scale"
    26  )
    27  
    28  type Header struct {
    29  	ParentHash     Hash        `json:"parentHash"`
    30  	Number         BlockNumber `json:"number"`
    31  	StateRoot      Hash        `json:"stateRoot"`
    32  	ExtrinsicsRoot Hash        `json:"extrinsicsRoot"`
    33  	Digest         Digest      `json:"digest"`
    34  }
    35  
    36  type BlockNumber U32
    37  
    38  // UnmarshalJSON fills BlockNumber with the JSON encoded byte array given by bz
    39  func (b *BlockNumber) UnmarshalJSON(bz []byte) error {
    40  	var tmp string
    41  	if err := json.Unmarshal(bz, &tmp); err != nil {
    42  		return err
    43  	}
    44  
    45  	s := strings.TrimPrefix(tmp, "0x")
    46  
    47  	p, err := strconv.ParseUint(s, 16, 32)
    48  	*b = BlockNumber(p)
    49  	return err
    50  }
    51  
    52  // MarshalJSON returns a JSON encoded byte array of BlockNumber
    53  func (b BlockNumber) MarshalJSON() ([]byte, error) {
    54  	s := strconv.FormatUint(uint64(b), 16)
    55  	return json.Marshal(s)
    56  }
    57  
    58  // Encode implements encoding for BlockNumber, which just unwraps the bytes of BlockNumber
    59  func (b BlockNumber) Encode(encoder scale.Encoder) error {
    60  	return encoder.EncodeUintCompact(*big.NewInt(0).SetUint64(uint64(b)))
    61  }
    62  
    63  // Decode implements decoding for BlockNumber, which just wraps the bytes in BlockNumber
    64  func (b *BlockNumber) Decode(decoder scale.Decoder) error {
    65  	u, err := decoder.DecodeUintCompact()
    66  	if err != nil {
    67  		return err
    68  	}
    69  	*b = BlockNumber(u.Uint64())
    70  	return err
    71  }