@@ -3,6 +3,7 @@ package lumera
33import (
44 "context"
55 "fmt"
6+ "sort"
67
78 "github.com/LumeraProtocol/supernode/v2/sdk/log"
89
@@ -194,13 +195,14 @@ func toSdkSupernodes(resp *sntypes.QueryGetTopSuperNodesForBlockResponse) []Supe
194195 continue
195196 }
196197
197- // Check if States slice has at least one element
198- if len (sn .States ) == 0 {
198+ // Get the latest state based on height
199+ latestState , err := getLatestState (sn )
200+ if err != nil {
199201 continue
200202 }
201203
202- // Check if the first state is active
203- if sn . States [ 0 ] .State .String () != string (SUPERNODE_STATE_ACTIVE ) {
204+ // Check if the latest state is active
205+ if latestState .State .String () != string (SUPERNODE_STATE_ACTIVE ) {
204206 continue
205207 }
206208
@@ -213,6 +215,29 @@ func toSdkSupernodes(resp *sntypes.QueryGetTopSuperNodesForBlockResponse) []Supe
213215 return result
214216}
215217
218+ func getLatestState (supernode * sntypes.SuperNode ) (* sntypes.SuperNodeStateRecord , error ) {
219+ if supernode == nil {
220+ return nil , fmt .Errorf ("supernode is nil" )
221+ }
222+
223+ // Check if the slice has elements before accessing it
224+ if len (supernode .States ) == 0 {
225+ return nil , fmt .Errorf ("no state history exists for the supernode" )
226+ }
227+
228+ // Sort by height in descending order to get the latest first
229+ sort .Slice (supernode .States , func (i , j int ) bool {
230+ return supernode .States [i ].Height > supernode .States [j ].Height
231+ })
232+
233+ // Access the latest state safely
234+ if supernode .States [0 ] == nil {
235+ return nil , fmt .Errorf ("latest state in history is nil" )
236+ }
237+
238+ return supernode .States [0 ], nil
239+ }
240+
216241func getLatestIP (supernode * sntypes.SuperNode ) (string , error ) {
217242 if supernode == nil {
218243 return "" , fmt .Errorf ("supernode is nil" )
@@ -223,9 +248,14 @@ func getLatestIP(supernode *sntypes.SuperNode) (string, error) {
223248 return "" , fmt .Errorf ("no ip history exists for the supernode" )
224249 }
225250
226- // Access the first element safely
251+ // Sort by height in descending order to get the latest first
252+ sort .Slice (supernode .PrevIpAddresses , func (i , j int ) bool {
253+ return supernode .PrevIpAddresses [i ].Height > supernode .PrevIpAddresses [j ].Height
254+ })
255+
256+ // Access the latest IP address safely
227257 if supernode .PrevIpAddresses [0 ] == nil {
228- return "" , fmt .Errorf ("first IP address in history is nil" )
258+ return "" , fmt .Errorf ("latest IP address in history is nil" )
229259 }
230260
231261 return supernode .PrevIpAddresses [0 ].Address , nil
0 commit comments