@@ -54,15 +54,14 @@ export class EvmPriceListener implements PriceListener {
54
54
this . startSubscription ( ) ;
55
55
} else {
56
56
console . log (
57
- "The target network RPC endpoint is not Websocket. Using polling instead..."
57
+ "The target network RPC endpoint is not Websocket. " +
58
+ "Listening for updates only via polling...."
58
59
) ;
59
- setInterval ( this . pollPrices . bind ( this ) , this . pollingFrequency * 1000 ) ;
60
60
}
61
61
62
- // Poll the prices to have values in the beginning until updates arrive.
63
- console . log (
64
- "Polling the prices in the beginning in order to set the initial values."
65
- ) ;
62
+ console . log ( `Polling the prices every ${ this . pollingFrequency } seconds...` ) ;
63
+ setInterval ( this . pollPrices . bind ( this ) , this . pollingFrequency * 1000 ) ;
64
+
66
65
await this . pollPrices ( ) ;
67
66
}
68
67
@@ -100,15 +99,15 @@ export class EvmPriceListener implements PriceListener {
100
99
publishTime : Number ( event . returnValues . publishTime ) ,
101
100
} ;
102
101
103
- this . latestPriceInfo . set ( priceId , priceInfo ) ;
102
+ this . updateLatestPriceInfo ( priceId , priceInfo ) ;
104
103
}
105
104
106
105
private async pollPrices ( ) {
107
106
console . log ( "Polling evm prices..." ) ;
108
107
for ( const priceId of this . priceIds ) {
109
108
const currentPriceInfo = await this . getOnChainPriceInfo ( priceId ) ;
110
109
if ( currentPriceInfo !== undefined ) {
111
- this . latestPriceInfo . set ( priceId , currentPriceInfo ) ;
110
+ this . updateLatestPriceInfo ( priceId , currentPriceInfo ) ;
112
111
}
113
112
}
114
113
}
@@ -134,7 +133,23 @@ export class EvmPriceListener implements PriceListener {
134
133
return {
135
134
conf : priceRaw . conf ,
136
135
price : priceRaw . price ,
137
- publishTime : priceRaw . publishTime ,
136
+ publishTime : Number ( priceRaw . publishTime ) ,
138
137
} ;
139
138
}
139
+
140
+ private updateLatestPriceInfo ( priceId : HexString , observedPrice : PriceInfo ) {
141
+ const cachedLatestPriceInfo = this . getLatestPriceInfo ( priceId ) ;
142
+
143
+ // Ignore the observed price if the cache already has newer
144
+ // price. This could happen because we are using polling and
145
+ // subscription at the same time.
146
+ if (
147
+ cachedLatestPriceInfo !== undefined &&
148
+ cachedLatestPriceInfo . publishTime > observedPrice . publishTime
149
+ ) {
150
+ return ;
151
+ }
152
+
153
+ this . latestPriceInfo . set ( priceId , observedPrice ) ;
154
+ }
140
155
}
0 commit comments