Skip to content

Commit

Permalink
Merge pull request #142 from valory-xyz/feat/check-agents-balances
Browse files Browse the repository at this point in the history
Check agents' balances
  • Loading branch information
Adamantios authored Nov 17, 2023
2 parents bf34819 + d175755 commit df7c32f
Show file tree
Hide file tree
Showing 12 changed files with 224 additions and 48 deletions.
8 changes: 4 additions & 4 deletions packages/packages.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
"dev": {
"skill/valory/market_manager_abci/0.1.0": "bafybeibrjre5yka3sbvb6lsefgc5yutovb6h4ffzrpecplfkjwtl5i36te",
"skill/valory/decision_maker_abci/0.1.0": "bafybeighimm45dlkagx5uig2i4wa7ikmiajlcyqkpms64amm5osxrnzroi",
"skill/valory/trader_abci/0.1.0": "bafybeihss6lmdt3khxktp2jzuuxsargspa3wb46jpdty6nqrwhxrq5ktde",
"skill/valory/trader_abci/0.1.0": "bafybeicp43s3irprp5qqn3qvf646voaqd2ffwbztwtchoyk6zue2rlli34",
"contract/valory/market_maker/0.1.0": "bafybeif4mm2s3gxtvp227yypkcnna5ftec7vajcftvtbdmqddh7nprah5m",
"agent/valory/trader/0.1.0": "bafybeigt2t6okczlbwsx7vwydq7c4cqniettxmmtidvdibvjkngadpk2wa",
"service/valory/trader/0.1.0": "bafybeiee5x6fx2rhzizmpcnuzwcgia2iu4qwzzfbegiwqh4okda6edlwg4",
"agent/valory/trader/0.1.0": "bafybeignnn4urnckjui37jyrjk5336ccnqa7wgjnrevglnxruvoggi6af4",
"service/valory/trader/0.1.0": "bafybeigaja33j4ljnii6iogv2c3iuhq75sfe3luvjlflboguzkrumuyg2i",
"contract/valory/erc20/0.1.0": "bafybeieqj7dea4tcv6z2yqkgtmhd23vbiycsr5trhwxdvlbwulpl6vhmam",
"skill/valory/tx_settlement_multiplexer_abci/0.1.0": "bafybeidaamjhhyayxprfi6pgoijmjhbybnlmhjugegm2pb4kj6ax623bna",
"skill/valory/tx_settlement_multiplexer_abci/0.1.0": "bafybeig5q4qy6potpciy2ja6hbo7qjebk66b5fvhg6ficyswwi3b6nzofy",
"contract/valory/mech/0.1.0": "bafybeihvc6btuk3nvernzcx4qpezvuhiw2wwnagqj5nkeljvszghv7mq64",
"contract/valory/realitio/0.1.0": "bafybeiamgkwwqhray4fs2hlipwxkq7mosmi7ev7jut4vneetaaycc4ruji",
"contract/valory/realitio_proxy/0.1.0": "bafybeidx37xzjjmapwacedgzhum6grfzhp5vhouz4zu3pvpgdy5pgb2fr4",
Expand Down
6 changes: 4 additions & 2 deletions packages/valory/agents/trader/aea-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ skills:
- valory/reset_pause_abci:0.1.0:bafybeicpxn2khtaesuf4cq6ypwdmdmonlqroj2q2i6cxvpizc2y4cw66pe
- valory/termination_abci:0.1.0:bafybeieqm46zuccaagnko3qlw6p3nvoohdrfgvpmw467r5lyil2dqrzjsy
- valory/transaction_settlement_abci:0.1.0:bafybeia6cdxdlqrcwk2maw25fo7dafzd2p3rs7syropvufophk2pitzbwy
- valory/tx_settlement_multiplexer_abci:0.1.0:bafybeidaamjhhyayxprfi6pgoijmjhbybnlmhjugegm2pb4kj6ax623bna
- valory/tx_settlement_multiplexer_abci:0.1.0:bafybeig5q4qy6potpciy2ja6hbo7qjebk66b5fvhg6ficyswwi3b6nzofy
- valory/market_manager_abci:0.1.0:bafybeibrjre5yka3sbvb6lsefgc5yutovb6h4ffzrpecplfkjwtl5i36te
- valory/decision_maker_abci:0.1.0:bafybeighimm45dlkagx5uig2i4wa7ikmiajlcyqkpms64amm5osxrnzroi
- valory/trader_abci:0.1.0:bafybeihss6lmdt3khxktp2jzuuxsargspa3wb46jpdty6nqrwhxrq5ktde
- valory/trader_abci:0.1.0:bafybeicp43s3irprp5qqn3qvf646voaqd2ffwbztwtchoyk6zue2rlli34
- valory/staking_abci:0.1.0:bafybeifdxywwwtwgfmtufkvvjvepil6qwetbldftf5eab5v2r3b3zh574q
default_ledger: ethereum
required_ledgers:
Expand Down Expand Up @@ -202,6 +202,8 @@ models:
"stabilityai-stable-diffusion-xl-beta-v2-2-2", "stabilityai-stable-diffusion-512-v2-1",
"stabilityai-stable-diffusion-768-v2-1"]}
staking_contract_address: ${str:0x5add592ce0a1B5DceCebB5Dcac086Cd9F9e3eA5C}
agent_balance_threshold: ${int:10000000000000000}
refill_check_interval: ${int:10}
---
public_id: valory/p2p_libp2p_client:0.1.0
type: connection
Expand Down
10 changes: 9 additions & 1 deletion packages/valory/services/trader/service.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ license: Apache-2.0
fingerprint:
README.md: bafybeigtuothskwyvrhfosps2bu6suauycolj67dpuxqvnicdrdu7yhtvq
fingerprint_ignore_patterns: []
agent: valory/trader:0.1.0:bafybeigt2t6okczlbwsx7vwydq7c4cqniettxmmtidvdibvjkngadpk2wa
agent: valory/trader:0.1.0:bafybeignnn4urnckjui37jyrjk5336ccnqa7wgjnrevglnxruvoggi6af4
number_of_agents: 4
deployment: {}
---
Expand Down Expand Up @@ -116,6 +116,8 @@ type: skill
"stabilityai-stable-diffusion-xl-beta-v2-2-2", "stabilityai-stable-diffusion-512-v2-1",
"stabilityai-stable-diffusion-768-v2-1"]}
staking_contract_address: ${STAKING_CONTRACT_ADDRESS:str:0x5add592ce0a1B5DceCebB5Dcac086Cd9F9e3eA5C}
agent_balance_threshold: ${AGENT_BALANCE_THRESHOLD:int:10000000000000000}
refill_check_interval: ${REFILL_CHECK_INTERVAL:int:10}
benchmark_tool: &id005
args:
log_dir: ${LOG_DIR:str:/benchmarks}
Expand Down Expand Up @@ -192,6 +194,8 @@ type: skill
"stabilityai-stable-diffusion-xl-beta-v2-2-2", "stabilityai-stable-diffusion-512-v2-1",
"stabilityai-stable-diffusion-768-v2-1"]}
staking_contract_address: ${STAKING_CONTRACT_ADDRESS:str:0x5add592ce0a1B5DceCebB5Dcac086Cd9F9e3eA5C}
agent_balance_threshold: ${AGENT_BALANCE_THRESHOLD:int:10000000000000000}
refill_check_interval: ${REFILL_CHECK_INTERVAL:int:10}
benchmark_tool: *id005
2:
models:
Expand Down Expand Up @@ -266,6 +270,8 @@ type: skill
"stabilityai-stable-diffusion-xl-beta-v2-2-2", "stabilityai-stable-diffusion-512-v2-1",
"stabilityai-stable-diffusion-768-v2-1"]}
staking_contract_address: ${STAKING_CONTRACT_ADDRESS:str:0x5add592ce0a1B5DceCebB5Dcac086Cd9F9e3eA5C}
agent_balance_threshold: ${AGENT_BALANCE_THRESHOLD:int:10000000000000000}
refill_check_interval: ${REFILL_CHECK_INTERVAL:int:10}
benchmark_tool: *id005
3:
models:
Expand Down Expand Up @@ -340,6 +346,8 @@ type: skill
"stabilityai-stable-diffusion-xl-beta-v2-2-2", "stabilityai-stable-diffusion-512-v2-1",
"stabilityai-stable-diffusion-768-v2-1"]}
staking_contract_address: ${STAKING_CONTRACT_ADDRESS:str:0x5add592ce0a1B5DceCebB5Dcac086Cd9F9e3eA5C}
agent_balance_threshold: ${AGENT_BALANCE_THRESHOLD:int:10000000000000000}
refill_check_interval: ${REFILL_CHECK_INTERVAL:int:10}
benchmark_tool: *id005
---
public_id: valory/ledger:0.19.0
Expand Down
7 changes: 5 additions & 2 deletions packages/valory/skills/trader_abci/composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,13 @@
TransactionSubmissionAbciApp,
)
from packages.valory.skills.tx_settlement_multiplexer_abci.rounds import (
ChecksPassedRound,
FinishedBetPlacementTxRound,
FinishedDecisionRequestTxRound,
FinishedRedeemingTxRound,
FinishedStakingTxRound,
PostTxSettlementRound,
PreTxSettlementRound,
TxSettlementMultiplexerAbciApp,
)

Expand All @@ -89,7 +91,8 @@
FinishedRegistrationRound: UpdateBetsRound,
FinishedMarketManagerRound: SamplingRound,
FailedMarketManagerRound: ResetAndPauseRound,
FinishedDecisionMakerRound: RandomnessTransactionSubmissionRound,
FinishedDecisionMakerRound: PreTxSettlementRound,
ChecksPassedRound: RandomnessTransactionSubmissionRound,
RefillRequiredRound: ResetAndPauseRound,
FinishedTransactionSubmissionRound: PostTxSettlementRound,
FailedTransactionSubmissionRound: HandleFailedTxRound,
Expand All @@ -99,7 +102,7 @@
FinishedWithoutDecisionRound: RedeemRound,
FinishedWithoutRedeemingRound: CallCheckpointRound,
FinishedStakingRound: ResetAndPauseRound,
CheckpointCallPreparedRound: RandomnessTransactionSubmissionRound,
CheckpointCallPreparedRound: PreTxSettlementRound,
FinishedStakingTxRound: ResetAndPauseRound,
FinishedResetAndPauseRound: UpdateBetsRound,
FinishedResetAndPauseErrorRound: RegistrationRound,
Expand Down
15 changes: 11 additions & 4 deletions packages/valory/skills/trader_abci/fsm_specification.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
alphabet_in:
- BET_PLACEMENT_DONE
- BLACKLIST
- CHECKS_PASSED
- CHECK_HISTORY
- CHECK_LATE_ARRIVING_MESSAGE
- CHECK_TIMEOUT
Expand All @@ -20,6 +21,7 @@ alphabet_in:
- NO_OP
- NO_REDEEMING
- REDEEMING_DONE
- REFILL_REQUIRED
- RESET_AND_PAUSE_TIMEOUT
- RESET_TIMEOUT
- ROUND_TIMEOUT
Expand Down Expand Up @@ -53,6 +55,7 @@ states:
- HandleFailedTxRound
- ImpossibleRound
- PostTxSettlementRound
- PreTxSettlementRound
- RandomnessTransactionSubmissionRound
- RedeemRound
- RegistrationRound
Expand All @@ -68,7 +71,7 @@ states:
- UpdateBetsRound
- ValidateTransactionRound
transition_func:
(BetPlacementRound, DONE): RandomnessTransactionSubmissionRound
(BetPlacementRound, DONE): PreTxSettlementRound
(BetPlacementRound, INSUFFICIENT_BALANCE): ResetAndPauseRound
(BetPlacementRound, NONE): ImpossibleRound
(BetPlacementRound, NO_MAJORITY): BetPlacementRound
Expand All @@ -78,7 +81,7 @@ transition_func:
(BlacklistingRound, NONE): ImpossibleRound
(BlacklistingRound, NO_MAJORITY): BlacklistingRound
(BlacklistingRound, ROUND_TIMEOUT): BlacklistingRound
(CallCheckpointRound, DONE): RandomnessTransactionSubmissionRound
(CallCheckpointRound, DONE): PreTxSettlementRound
(CallCheckpointRound, NEXT_CHECKPOINT_NOT_REACHED_YET): ResetAndPauseRound
(CallCheckpointRound, NO_MAJORITY): CallCheckpointRound
(CallCheckpointRound, ROUND_TIMEOUT): CallCheckpointRound
Expand All @@ -104,7 +107,7 @@ transition_func:
(DecisionReceiveRound, ROUND_TIMEOUT): DecisionReceiveRound
(DecisionReceiveRound, TIE): BlacklistingRound
(DecisionReceiveRound, UNPROFITABLE): BlacklistingRound
(DecisionRequestRound, DONE): RandomnessTransactionSubmissionRound
(DecisionRequestRound, DONE): PreTxSettlementRound
(DecisionRequestRound, NONE): ImpossibleRound
(DecisionRequestRound, NO_MAJORITY): DecisionRequestRound
(DecisionRequestRound, ROUND_TIMEOUT): DecisionRequestRound
Expand All @@ -124,10 +127,14 @@ transition_func:
(PostTxSettlementRound, ROUND_TIMEOUT): PostTxSettlementRound
(PostTxSettlementRound, STAKING_DONE): ResetAndPauseRound
(PostTxSettlementRound, UNRECOGNIZED): FailedMultiplexerRound
(PreTxSettlementRound, CHECKS_PASSED): RandomnessTransactionSubmissionRound
(PreTxSettlementRound, NO_MAJORITY): PreTxSettlementRound
(PreTxSettlementRound, REFILL_REQUIRED): PreTxSettlementRound
(PreTxSettlementRound, ROUND_TIMEOUT): PreTxSettlementRound
(RandomnessTransactionSubmissionRound, DONE): SelectKeeperTransactionSubmissionARound
(RandomnessTransactionSubmissionRound, NO_MAJORITY): RandomnessTransactionSubmissionRound
(RandomnessTransactionSubmissionRound, ROUND_TIMEOUT): RandomnessTransactionSubmissionRound
(RedeemRound, DONE): RandomnessTransactionSubmissionRound
(RedeemRound, DONE): PreTxSettlementRound
(RedeemRound, NONE): ImpossibleRound
(RedeemRound, NO_MAJORITY): RedeemRound
(RedeemRound, NO_REDEEMING): CallCheckpointRound
Expand Down
7 changes: 6 additions & 1 deletion packages/valory/skills/trader_abci/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@
from packages.valory.skills.termination_abci.models import TerminationParams
from packages.valory.skills.trader_abci.composition import TraderAbciApp
from packages.valory.skills.transaction_settlement_abci.rounds import Event as TSEvent
from packages.valory.skills.tx_settlement_multiplexer_abci.models import (
TxSettlementMultiplexerParams,
)


EventType = Union[
Expand Down Expand Up @@ -81,7 +84,9 @@ class RandomnessApi(ApiSpecs):
"""A model for randomness api specifications."""


class TraderParams(DecisionMakerParams, TerminationParams, StakingParams):
class TraderParams(
DecisionMakerParams, TerminationParams, StakingParams, TxSettlementMultiplexerParams
):
"""A model to represent the trader params."""


Expand Down
10 changes: 6 additions & 4 deletions packages/valory/skills/trader_abci/skill.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ fingerprint:
README.md: bafybeiab4xgadptz4mhvno4p6xvkh7p4peg7iuhotabydriu74dmj6ljga
__init__.py: bafybeido7wa33h4dtleap57vzgyb4fsofk4vindsqcekyfo5i56i2rll2a
behaviours.py: bafybeieesrefrpo5c5upzztgm5fwfrmxeagilacuau5nacobhsfvgpbzby
composition.py: bafybeif4gsc2kfpsyy7rol74v3ir6ckgrm76jygy3rrcnjt3pen32pgcoi
composition.py: bafybeifakbd6n3lqvmxhb2svdst7wbagrplw23yf45zdexw34abtglxqke
dialogues.py: bafybeiebofyykseqp3fmif36cqmmyf3k7d2zbocpl6t6wnlpv4szghrxbm
fsm_specification.yaml: bafybeihh7qkvge7srvrc25hvo6qwtezhewjcegbrqk5rukwpbrx4a2fq3m
fsm_specification.yaml: bafybeifduigketlvdwyhn47jfwf77otixljibl45firz5ijyhdgilhcyja
handlers.py: bafybeicamc6vmozij5dwvkxmbxjazsgf3sacojhstbjtq7vfggszxugvey
models.py: bafybeifrz6dfncsxksvyh4jhbl4am2uzivfv6fyqs5mhw4qdpy5ruik7fm
models.py: bafybeifxiptjrnv4hbw5l3mfxvb7hksmxf726kvab5lcms5btuc3vaahem
fingerprint_ignore_patterns: []
connections: []
contracts: []
Expand All @@ -26,7 +26,7 @@ skills:
- valory/termination_abci:0.1.0:bafybeieqm46zuccaagnko3qlw6p3nvoohdrfgvpmw467r5lyil2dqrzjsy
- valory/market_manager_abci:0.1.0:bafybeibrjre5yka3sbvb6lsefgc5yutovb6h4ffzrpecplfkjwtl5i36te
- valory/decision_maker_abci:0.1.0:bafybeighimm45dlkagx5uig2i4wa7ikmiajlcyqkpms64amm5osxrnzroi
- valory/tx_settlement_multiplexer_abci:0.1.0:bafybeidaamjhhyayxprfi6pgoijmjhbybnlmhjugegm2pb4kj6ax623bna
- valory/tx_settlement_multiplexer_abci:0.1.0:bafybeig5q4qy6potpciy2ja6hbo7qjebk66b5fvhg6ficyswwi3b6nzofy
- valory/staking_abci:0.1.0:bafybeifdxywwwtwgfmtufkvvjvepil6qwetbldftf5eab5v2r3b3zh574q
behaviours:
main:
Expand Down Expand Up @@ -187,6 +187,8 @@ models:
- stabilityai-stable-diffusion-512-v2-1
- stabilityai-stable-diffusion-768-v2-1
staking_contract_address: '0x5add592ce0a1B5DceCebB5Dcac086Cd9F9e3eA5C'
agent_balance_threshold: 10000000000000000
refill_check_interval: 10
class_name: TraderParams
network_subgraph:
args:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,102 @@

"""This package contains the behaviours of the transaction settlement multiplexer."""

from abc import ABC
from typing import Generator, Set, Type
from typing import Generator, Optional, Set, Type, cast

from aea.exceptions import AEAEnforceError

from packages.valory.protocols.ledger_api import LedgerApiMessage
from packages.valory.skills.abstract_round_abci.behaviours import (
AbstractRoundBehaviour,
BaseBehaviour,
)
from packages.valory.skills.decision_maker_abci.payloads import VotingPayload
from packages.valory.skills.tx_settlement_multiplexer_abci.models import (
TxSettlementMultiplexerParams,
)
from packages.valory.skills.tx_settlement_multiplexer_abci.rounds import (
PostTxSettlementRound,
PreTxSettlementRound,
SynchronizedData,
TxSettlementMultiplexerAbciApp,
)


class PostTxSettlementBehaviour(BaseBehaviour, ABC):
class PreTxSettlementBehaviour(BaseBehaviour):
"""
The pre transaction settlement behaviour.
This behaviour should be executed before a tx is sent via the transaction_settlement_abci.
"""

matching_round = PreTxSettlementRound

@property
def params(self) -> TxSettlementMultiplexerParams:
"""Return the params."""
return cast(TxSettlementMultiplexerParams, self.context.params)

def _get_balance(self, agent: str) -> Generator[None, None, Optional[int]]:
"""Get the given agent's balance."""
self.context.logger.info(f"Checking balance for agent with address {agent}...")
ledger_api_response = yield from self.get_ledger_api_response(
performative=LedgerApiMessage.Performative.GET_STATE, # type: ignore
ledger_callable="get_balance",
account=agent,
)

try:
balance = int(ledger_api_response.state.body["get_balance_result"])
except (AEAEnforceError, KeyError, ValueError, TypeError):
balance = None

if balance is None:
log_msg = f"Failed to get the balance for agent with address {agent}."
self.context.logger.error(f"{log_msg}: {ledger_api_response}")
return None

self.context.logger.info(f"The agent with address {agent} has {balance} WEI.")
return balance

def _check_balance(self, agent: str) -> Generator[None, None, bool]:
"""Check if the given agent's balance is sufficient."""
balance = None
while balance is None:
balance = yield from self._get_balance(agent)

threshold = self.params.agent_balance_threshold
refill_required = balance < threshold
if refill_required:
msg = f"Please refill agent with address {agent}. Balance is below {threshold}."
self.context.logger.warning(msg)

return refill_required

def _refill_required(self) -> Generator[None, None, bool]:
"""Check whether a refill is required."""
refill_required = False
for agent in self.synchronized_data.all_participants:
refill_required |= yield from self._check_balance(agent)
return refill_required

def async_act(self) -> Generator:
"""Check whether the agents' balances are sufficient."""
with self.context.benchmark_tool.measure(self.behaviour_id).local():
refill_required = yield from self._refill_required()
if refill_required:
# pause to give the user some time to refill before transitioning to the same round again
yield from self.sleep(self.params.refill_check_interval)

payload = VotingPayload(self.context.agent_address, not refill_required)

with self.context.benchmark_tool.measure(self.behaviour_id).consensus():
yield from self.send_a2a_transaction(payload)
yield from self.wait_until_round_end()

self.set_done()


class PostTxSettlementBehaviour(BaseBehaviour):
"""
The post transaction settlement behaviour.
Expand All @@ -60,4 +141,7 @@ class PostTxSettlementFullBehaviour(AbstractRoundBehaviour):

initial_behaviour_cls = PostTxSettlementBehaviour
abci_app_cls = TxSettlementMultiplexerAbciApp
behaviours: Set[Type[BaseBehaviour]] = {PostTxSettlementBehaviour} # type: ignore
behaviours: Set[Type[BaseBehaviour]] = {
PreTxSettlementBehaviour, # type: ignore
PostTxSettlementBehaviour, # type: ignore
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
alphabet_in:
- BET_PLACEMENT_DONE
- CHECKS_PASSED
- DECISION_REQUESTING_DONE
- NO_MAJORITY
- REDEEMING_DONE
- REFILL_REQUIRED
- ROUND_TIMEOUT
- STAKING_DONE
- UNRECOGNIZED
default_start_state: PostTxSettlementRound
default_start_state: PreTxSettlementRound
final_states:
- ChecksPassedRound
- FailedMultiplexerRound
- FinishedBetPlacementTxRound
- FinishedDecisionRequestTxRound
Expand All @@ -15,17 +19,24 @@ final_states:
label: TxSettlementMultiplexerAbciApp
start_states:
- PostTxSettlementRound
- PreTxSettlementRound
states:
- ChecksPassedRound
- FailedMultiplexerRound
- FinishedBetPlacementTxRound
- FinishedDecisionRequestTxRound
- FinishedRedeemingTxRound
- FinishedStakingTxRound
- PostTxSettlementRound
- PreTxSettlementRound
transition_func:
(PostTxSettlementRound, BET_PLACEMENT_DONE): FinishedBetPlacementTxRound
(PostTxSettlementRound, DECISION_REQUESTING_DONE): FinishedDecisionRequestTxRound
(PostTxSettlementRound, REDEEMING_DONE): FinishedRedeemingTxRound
(PostTxSettlementRound, ROUND_TIMEOUT): PostTxSettlementRound
(PostTxSettlementRound, STAKING_DONE): FinishedStakingTxRound
(PostTxSettlementRound, UNRECOGNIZED): FailedMultiplexerRound
(PreTxSettlementRound, CHECKS_PASSED): ChecksPassedRound
(PreTxSettlementRound, NO_MAJORITY): PreTxSettlementRound
(PreTxSettlementRound, REFILL_REQUIRED): PreTxSettlementRound
(PreTxSettlementRound, ROUND_TIMEOUT): PreTxSettlementRound
Loading

0 comments on commit df7c32f

Please sign in to comment.