The following code has an expected duration of 1000ms.
package main
import (
"context"
"fmt"
"github.com/ethereum/go-ethereum/ethclient"
"golang.org/x/time/rate"
"time"
)
func main() {
var start time.Time
for {
start = time.Now()
connect()
fmt.Println("Duration", time.Since(start).Milliseconds(), "ms")
}
}
func connect() {
ctx := context.Background()
limiter := rate.NewLimiter(rate.Limit(1), 1)
// Wait for the rate limiter to allow the request
if err := limiter.WaitN(ctx, 1); err != nil {
remainingTime := limiter.ReserveN(time.Now(), 1).Delay()
time.Sleep(remainingTime)
}
nodeURL := "https://sepolia.infura.io/v3/your-infura-project-id"
client, _ := ethclient.DialContext(ctx, nodeURL)
// Use the client to interact with the Ethereum network
// Example: Retrieve the latest block number
blockNumber, _ := client.BlockNumber(ctx)
fmt.Printf("Latest block number: %d\n", blockNumber)
}
Gives me the following output:
Latest block number: 0 Duration 251 ms
Latest block number: 0 Duration 250 ms
Latest block number: 0 Duration 243 ms
Latest block number: 0 Duration 243 ms
Latest block number: 0 Duration 243 ms
Latest block number: 0 Duration 244 ms
Any clue what wrong with my limiter?