github.com/gagliardetto/solana-go@v1.11.0/rpc/ws/rootSubscribe.go (about)

     1  // Copyright 2021 github.com/gagliardetto
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package ws
    16  
    17  type RootResult uint64
    18  
    19  // SignatureSubscribe subscribes to receive notification
    20  // anytime a new root is set by the validator.
    21  func (cl *Client) RootSubscribe() (*RootSubscription, error) {
    22  	genSub, err := cl.subscribe(
    23  		nil,
    24  		nil,
    25  		"rootSubscribe",
    26  		"rootUnsubscribe",
    27  		func(msg []byte) (interface{}, error) {
    28  			var res RootResult
    29  			err := decodeResponseFromMessage(msg, &res)
    30  			return &res, err
    31  		},
    32  	)
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  	return &RootSubscription{
    37  		sub: genSub,
    38  	}, nil
    39  }
    40  
    41  type RootSubscription struct {
    42  	sub *Subscription
    43  }
    44  
    45  func (sw *RootSubscription) Recv() (*RootResult, error) {
    46  	select {
    47  	case d := <-sw.sub.stream:
    48  		return d.(*RootResult), nil
    49  	case err := <-sw.sub.err:
    50  		return nil, err
    51  	}
    52  }
    53  
    54  func (sw *RootSubscription) Err() <-chan error {
    55  	return sw.sub.err
    56  }
    57  
    58  func (sw *RootSubscription) Response() <-chan *RootResult {
    59  	typedChan := make(chan *RootResult, 1)
    60  	go func(ch chan *RootResult) {
    61  		// TODO: will this subscription yield more than one result?
    62  		d, ok := <-sw.sub.stream
    63  		if !ok {
    64  			return
    65  		}
    66  		ch <- d.(*RootResult)
    67  	}(typedChan)
    68  	return typedChan
    69  }
    70  
    71  func (sw *RootSubscription) Unsubscribe() {
    72  	sw.sub.Unsubscribe()
    73  }