Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: implement sequence number caching support #327

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions cosmpy/aerial/client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ def __init__(
cfg.validate()
self._network_config = cfg
self._gas_strategy: GasStrategy = SimulationGasStrategy(self)
self._last_sequence_numbers: Dict[str, Tuple[datetime, int]] = {}

parsed_url = parse_url(cfg.url)

Expand Down Expand Up @@ -270,6 +271,23 @@ def query_account(self, address: Address) -> Account:
sequence=account.sequence,
)

def get_last_sequence_number(self, address: Address) -> Optional[int]:
raw_address = str(address)

if raw_address not in self._last_sequence_numbers:
return None

expiry, seq = self._last_sequence_numbers.get(raw_address)
if datetime.utcnow() > expiry:
del self._last_sequence_numbers[raw_address]
return None

return seq

def set_last_sequence_number(self, address: Address, sequence: int):
expiry = datetime.utcnow() + timedelta(seconds=120)
self._last_sequence_numbers[str(address)] = (expiry, sequence)

def query_params(self, subspace: str, key: str) -> Any:
"""Query Prams.

Expand Down
14 changes: 13 additions & 1 deletion cosmpy/aerial/client/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,13 @@ def prepare_and_broadcast_basic_transaction(
if account is None:
account = client.query_account(sender.address())

# in cases where the RPC node is slow to update the statement above can return out of date information.
cached_seq = client.get_last_sequence_number(sender.address())
if cached_seq is not None:
if account.sequence < cached_seq:
print(f'RPC Endpoint appears out of sync {account.sequence} vs {cached_seq}')
account.sequence = cached_seq

if gas_limit is not None:
# simply build the fee from the provided gas limit
fee = client.estimate_fee_from_gas(gas_limit)
Expand Down Expand Up @@ -76,7 +83,12 @@ def prepare_and_broadcast_basic_transaction(
tx.sign(sender.signer(), client.network_config.chain_id, account.number)
tx.complete()

return client.broadcast_tx(tx)
resp = client.broadcast_tx(tx)

# store the next sequence number
client.set_last_sequence_number(sender.address(), account.sequence + 1)

return resp


def ensure_timedelta(interval: Union[int, float, timedelta]) -> timedelta:
Expand Down