github.com/gagliardetto/solana-go@v1.11.0/rpc/ws/slotSubscribe.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 SlotResult struct { 18 Parent uint64 `json:"parent"` 19 Root uint64 `json:"root"` 20 Slot uint64 `json:"slot"` 21 } 22 23 // SlotSubscribe subscribes to receive notification anytime a slot is processed by the validator. 24 func (cl *Client) SlotSubscribe() (*SlotSubscription, error) { 25 genSub, err := cl.subscribe( 26 nil, 27 nil, 28 "slotSubscribe", 29 "slotUnsubscribe", 30 func(msg []byte) (interface{}, error) { 31 var res SlotResult 32 err := decodeResponseFromMessage(msg, &res) 33 return &res, err 34 }, 35 ) 36 if err != nil { 37 return nil, err 38 } 39 return &SlotSubscription{ 40 sub: genSub, 41 }, nil 42 } 43 44 type SlotSubscription struct { 45 sub *Subscription 46 } 47 48 func (sw *SlotSubscription) Recv() (*SlotResult, error) { 49 select { 50 case d := <-sw.sub.stream: 51 return d.(*SlotResult), nil 52 case err := <-sw.sub.err: 53 return nil, err 54 } 55 } 56 57 func (sw *SlotSubscription) Err() <-chan error { 58 return sw.sub.err 59 } 60 61 func (sw *SlotSubscription) Response() <-chan *SlotResult { 62 typedChan := make(chan *SlotResult, 1) 63 go func(ch chan *SlotResult) { 64 // TODO: will this subscription yield more than one result? 65 d, ok := <-sw.sub.stream 66 if !ok { 67 return 68 } 69 ch <- d.(*SlotResult) 70 }(typedChan) 71 return typedChan 72 } 73 74 func (sw *SlotSubscription) Unsubscribe() { 75 sw.sub.Unsubscribe() 76 }