Fix token bug

Bug:  

code incorrectly set tokens = 0, then immediately consumed a token (setting it to -1)

Fix:

Update the last_refill timestamp after waiting (previously missing)

Correctly credit exactly 1 token after waiting the appropriate time

Then consume the token, leaving the balance at 0 (not negative)
This commit is contained in:
Sat 2025-05-15 09:14:03 -06:00 committed by GitHub
parent 3db1133e68
commit e3edcbe2fe
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,3 +1,4 @@
import asyncio
import random
import time
@ -53,16 +54,21 @@ class TokenBucket:
self.tokens = min(self.rate, self.tokens + new_tokens)
self.last_refill = now
# If no tokens available, calculate wait time
# If no tokens available, calculate wait time and wait for a token
if self.tokens < 1:
# Calculate time needed for one token
wait_time = (self.period / self.rate) * (1 - self.tokens)
await asyncio.sleep(wait_time)
self.tokens = 0 # Reset after waiting
# After waiting, update time and add one token
self.last_refill = time.monotonic()
self.tokens = 1 # We now have exactly one token available
# Consume a token
# Consume a token (will be 0 or more after consumption)
self.tokens -= 1
class StrikeWallet(Wallet):
"""
https://developer.strike.me/api