Skip to content

Commit

Permalink
Merge pull request #107 from valory-xyz/feat/utilize-wxdai
Browse files Browse the repository at this point in the history
Utilize wxDAI to perform requests
  • Loading branch information
Adamantios authored Oct 13, 2023
2 parents 2c1c74c + 6f3ab9f commit 3c55841
Show file tree
Hide file tree
Showing 12 changed files with 213 additions and 97 deletions.
12 changes: 6 additions & 6 deletions packages/packages.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
{
"dev": {
"skill/valory/market_manager_abci/0.1.0": "bafybeigmy3g2klkzdhttti2ouxf575ua5y7ajmh4a3yfpukeukqxjky47m",
"skill/valory/decision_maker_abci/0.1.0": "bafybeibijhfe2owjeioofnyfbwmla36dksm7rh2tq7acwpdg4sbzoglt6q",
"skill/valory/trader_abci/0.1.0": "bafybeic25p753rteoq6nxrj2hx7sowjkg2v3vjmomeufbfc6gpyrth34wa",
"skill/valory/decision_maker_abci/0.1.0": "bafybeihtydxuzyd35cq23xoxbytpxebpbn3rsyqf4bt6z4sleflqck6riy",
"skill/valory/trader_abci/0.1.0": "bafybeignhbqiajnhec7xipsibm3vpjovxboaak3n3kd2ozc27sjaw7733m",
"contract/valory/market_maker/0.1.0": "bafybeif4mm2s3gxtvp227yypkcnna5ftec7vajcftvtbdmqddh7nprah5m",
"agent/valory/trader/0.1.0": "bafybeidlzrnqm4i6255lilhmufdu3tfjvstxr37slfi73c3s3satcbqmgi",
"service/valory/trader/0.1.0": "bafybeifowg6z52r6xucwhqipcohuxylr6nqsv4e4cdeuio3benhtmf3frm",
"contract/valory/erc20/0.1.0": "bafybeig53maqwplpbzd63niffnslqcwsr3wse6lytwg772373s33mbpmaa",
"skill/valory/tx_settlement_multiplexer_abci/0.1.0": "bafybeiglmk6oe2yjsnx73w52c5qx4jbtxfzaf5qvzs2xfsyna3p3agg234",
"agent/valory/trader/0.1.0": "bafybeibpafgfqxva32x4y22zsw6pjur43xcbirjizlornqwvl5vykopdgy",
"service/valory/trader/0.1.0": "bafybeiadxvczqasdeukfmt2c2h66z4dxtgeyzinio7cm4alm2meboh65ye",
"contract/valory/erc20/0.1.0": "bafybeibysifjwhlcn7nntsjkowdmja53ed6urfzypi6sxfc7chtheecvpi",
"skill/valory/tx_settlement_multiplexer_abci/0.1.0": "bafybeigfkdkpkrktw4wippon6al7vreg3qh7xax33xafomepy6xrv5paa4",
"contract/valory/mech/0.1.0": "bafybeifaavuqr2bz7nypapjwkufc5c6vwxm5ifucmtd3w7sh42tne35nga",
"contract/valory/realitio/0.1.0": "bafybeic3wihpzz4deguslpzlnsgrlrabclq3njwuagyaiiv6rzqujfrs6e",
"contract/valory/realitio_proxy/0.1.0": "bafybeidx37xzjjmapwacedgzhum6grfzhp5vhouz4zu3pvpgdy5pgb2fr4",
Expand Down
8 changes: 4 additions & 4 deletions packages/valory/agents/trader/aea-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ contracts:
- valory/gnosis_safe_proxy_factory:0.1.0:bafybeigxqwbd6wds57ecsfkl2hf4z4vbz5gokex6nutu5zcdpw6irh573y
- valory/service_registry:0.1.0:bafybeiebuuhs7fmigfh4c5dvzt6rbm5ekwrcnz7zouyjey7yyyqmpa6dyu
- valory/market_maker:0.1.0:bafybeif4mm2s3gxtvp227yypkcnna5ftec7vajcftvtbdmqddh7nprah5m
- valory/erc20:0.1.0:bafybeig53maqwplpbzd63niffnslqcwsr3wse6lytwg772373s33mbpmaa
- valory/erc20:0.1.0:bafybeibysifjwhlcn7nntsjkowdmja53ed6urfzypi6sxfc7chtheecvpi
- valory/multisend:0.1.0:bafybeig5byt5urg2d2bsecufxe5ql7f4mezg3mekfleeh32nmuusx66p4y
- valory/mech:0.1.0:bafybeifaavuqr2bz7nypapjwkufc5c6vwxm5ifucmtd3w7sh42tne35nga
- valory/conditional_tokens:0.1.0:bafybeif5jwc6owfe6brmqq5sfnhrwo2ajdtt4glrmyhlqxcvtkyofahwsa
Expand All @@ -41,10 +41,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:bafybeiglmk6oe2yjsnx73w52c5qx4jbtxfzaf5qvzs2xfsyna3p3agg234
- valory/tx_settlement_multiplexer_abci:0.1.0:bafybeigfkdkpkrktw4wippon6al7vreg3qh7xax33xafomepy6xrv5paa4
- valory/market_manager_abci:0.1.0:bafybeigmy3g2klkzdhttti2ouxf575ua5y7ajmh4a3yfpukeukqxjky47m
- valory/decision_maker_abci:0.1.0:bafybeibijhfe2owjeioofnyfbwmla36dksm7rh2tq7acwpdg4sbzoglt6q
- valory/trader_abci:0.1.0:bafybeic25p753rteoq6nxrj2hx7sowjkg2v3vjmomeufbfc6gpyrth34wa
- valory/decision_maker_abci:0.1.0:bafybeihtydxuzyd35cq23xoxbytpxebpbn3rsyqf4bt6z4sleflqck6riy
- valory/trader_abci:0.1.0:bafybeignhbqiajnhec7xipsibm3vpjovxboaak3n3kd2ozc27sjaw7733m
default_ledger: ethereum
required_ledgers:
- ethereum
Expand Down
12 changes: 12 additions & 0 deletions packages/valory/contracts/erc20/contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,18 @@ def build_deposit_tx(
data = contract_instance.encodeABI("deposit")
return {"data": bytes.fromhex(data[2:])}

@classmethod
def build_withdraw_tx(
cls,
ledger_api: EthereumApi,
contract_address: str,
amount: int,
) -> Dict[str, bytes]:
"""Build a deposit transaction."""
contract_instance = cls.get_instance(ledger_api, contract_address)
data = contract_instance.encodeABI("withdraw", args=(amount,))
return {"data": bytes.fromhex(data[2:])}

@classmethod
def build_approval_tx(
cls,
Expand Down
2 changes: 1 addition & 1 deletion packages/valory/contracts/erc20/contract.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ fingerprint:
README.md: bafybeifmfma6rglvpa22odtozyosnp5mwljum64utxip2wgmezuhnjjjyi
__init__.py: bafybeia2k2vmq7lmd3uchmm6jmzj7ebqkogk5aolpw4nwsawnkgqfobltm
build/ERC20.json: bafybeiemn5b5nszuss7xj6lmvmjuendltp6wz7ubihdvd7c6wqw4bohbpa
contract.py: bafybeib257slx7p53emy7rrs6tpkbbzrfuv6gwvviuy27hboynqjsxbsj4
contract.py: bafybeigk7vgluyhpr65rllw4z5jrozjmrlufkxsfvnicuvpr5l5k3vmm6u
fingerprint_ignore_patterns: []
contracts: []
class_name: ERC20
Expand Down
2 changes: 1 addition & 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:bafybeidlzrnqm4i6255lilhmufdu3tfjvstxr37slfi73c3s3satcbqmgi
agent: valory/trader:0.1.0:bafybeibpafgfqxva32x4y22zsw6pjur43xcbirjizlornqwvl5vykopdgy
number_of_agents: 4
deployment: {}
---
Expand Down
53 changes: 53 additions & 0 deletions packages/valory/skills/decision_maker_abci/behaviours/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

from aea.configurations.data_types import PublicId

from packages.valory.contracts.erc20.contract import ERC20
from packages.valory.contracts.gnosis_safe.contract import (
GnosisSafeContract,
SafeOperation,
Expand Down Expand Up @@ -58,6 +59,7 @@
# more info here: https://safe-docs.dev.gnosisdev.com/safe/docs/contracts_tx_execution/
SAFE_GAS = 0
CID_PREFIX = "f01701220"
WXDAI = "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d"


def remove_fraction_wei(amount: int, fraction: float) -> int:
Expand All @@ -74,6 +76,8 @@ class DecisionMakerBaseBehaviour(BaseBehaviour, ABC):
def __init__(self, **kwargs: Any) -> None:
"""Initialize the bet placement behaviour."""
super().__init__(**kwargs)
self.token_balance = 0
self.wallet_balance = 0
self.multisend_batches: List[MultisendBatch] = []
self.multisend_data = b""
self._safe_tx_hash = ""
Expand Down Expand Up @@ -146,11 +150,60 @@ def is_first_period(self) -> bool:
"""Return whether it is the first period of the service."""
return self.synchronized_data.period_count == 0

@property
def collateral_token(self) -> str:
"""Get the contract address of the token that the market maker supports."""
return self.synchronized_data.sampled_bet.collateralToken

@property
def is_wxdai(self) -> bool:
"""Get whether the collateral address is wxDAI."""
return self.collateral_token.lower() == WXDAI.lower()

@staticmethod
def wei_to_native(wei: int) -> float:
"""Convert WEI to native token."""
return wei / 10**18

def _collateral_amount_info(self, amount: int) -> str:
"""Get a description of the collateral token's amount."""
return (
f"{self.wei_to_native(amount)} wxDAI"
if self.is_wxdai
else f"{amount} WEI of the collateral token with address {self.collateral_token}"
)

def check_balance(self) -> WaitableConditionType:
"""Check the safe's balance."""
response_msg = yield from self.get_contract_api_response(
performative=ContractApiMessage.Performative.GET_RAW_TRANSACTION, # type: ignore
contract_address=self.collateral_token,
contract_id=str(ERC20.contract_id),
contract_callable="check_balance",
account=self.synchronized_data.safe_contract_address,
)
if response_msg.performative != ContractApiMessage.Performative.RAW_TRANSACTION:
self.context.logger.error(
f"Could not calculate the balance of the safe: {response_msg}"
)
return False

token = response_msg.raw_transaction.body.get("token", None)
wallet = response_msg.raw_transaction.body.get("wallet", None)
if token is None or wallet is None:
self.context.logger.error(
f"Something went wrong while trying to get the balance of the safe: {response_msg}"
)
return False

self.token_balance = int(token)
self.wallet_balance = int(wallet)

native = self.wei_to_native(self.wallet_balance)
collateral = self._collateral_amount_info(self.token_balance)
self.context.logger.info(f"The safe has {native} xDAI and {collateral}.")
return True

def default_error(
self, contract_id: str, contract_callable: str, response_msg: ContractApiMessage
) -> None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from packages.valory.protocols.contract_api import ContractApiMessage
from packages.valory.skills.decision_maker_abci.behaviours.base import (
DecisionMakerBaseBehaviour,
WXDAI,
WaitableConditionType,
remove_fraction_wei,
)
Expand All @@ -40,9 +41,6 @@
)


WXDAI = "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d"


class BetPlacementBehaviour(DecisionMakerBaseBehaviour):
"""A behaviour in which the agents blacklist the sampled bet."""

Expand All @@ -51,20 +49,8 @@ class BetPlacementBehaviour(DecisionMakerBaseBehaviour):
def __init__(self, **kwargs: Any) -> None:
"""Initialize the bet placement behaviour."""
super().__init__(**kwargs)
self.token_balance = 0
self.wallet_balance = 0
self.buy_amount = 0

@property
def collateral_token(self) -> str:
"""Get the contract address of the token that the market maker supports."""
return self.synchronized_data.sampled_bet.collateralToken

@property
def is_wxdai(self) -> bool:
"""Get whether the collateral address is wxDAI."""
return self.collateral_token.lower() == WXDAI.lower()

@property
def market_maker_contract_address(self) -> str:
"""Get the contract address of the market maker on which the service is going to place the bet."""
Expand All @@ -77,53 +63,14 @@ def investment_amount(self) -> int:

@property
def w_xdai_deficit(self) -> int:
"""Get the amount of missing wxDAI fo placing the bet."""
"""Get the amount of missing wxDAI for placing the bet."""
return self.investment_amount - self.token_balance

@property
def outcome_index(self) -> int:
"""Get the index of the outcome that the service is going to place a bet on."""
return cast(int, self.synchronized_data.vote)

def _collateral_amount_info(self, amount: int) -> str:
"""Get a description of the collateral token's amount."""
return (
f"{self.wei_to_native(amount)} wxDAI"
if self.is_wxdai
else f"{amount} WEI of the collateral token with address {self.collateral_token}"
)

def _check_balance(self) -> WaitableConditionType:
"""Check the safe's balance."""
response_msg = yield from self.get_contract_api_response(
performative=ContractApiMessage.Performative.GET_RAW_TRANSACTION, # type: ignore
contract_address=self.collateral_token,
contract_id=str(ERC20.contract_id),
contract_callable="check_balance",
account=self.synchronized_data.safe_contract_address,
)
if response_msg.performative != ContractApiMessage.Performative.RAW_TRANSACTION:
self.context.logger.error(
f"Could not calculate the balance of the safe: {response_msg}"
)
return False

token = response_msg.raw_transaction.body.get("token", None)
wallet = response_msg.raw_transaction.body.get("wallet", None)
if token is None or wallet is None:
self.context.logger.error(
f"Something went wrong while trying to get the balance of the safe: {response_msg}"
)
return False

self.token_balance = int(token)
self.wallet_balance = int(wallet)

native = self.wei_to_native(self.wallet_balance)
collateral = self._collateral_amount_info(self.token_balance)
self.context.logger.info(f"The safe has {native} xDAI and {collateral}.")
return True

def _build_exchange_tx(self) -> WaitableConditionType:
"""Exchange xDAI to wxDAI."""
response_msg = yield from self.get_contract_api_response(
Expand Down Expand Up @@ -258,7 +205,7 @@ def _prepare_safe_tx(self) -> Generator[None, None, Optional[str]]:
def async_act(self) -> Generator:
"""Do the action."""
with self.context.benchmark_tool.measure(self.behaviour_id).local():
yield from self.wait_for_condition_with_sleep(self._check_balance)
yield from self.wait_for_condition_with_sleep(self.check_balance)
tx_submitter = betting_tx_hex = None

can_exchange = (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@


ZERO_ADDRESS = "0x0000000000000000000000000000000000000000"
SLIPPAGE = 1.05


class DecisionReceiveBehaviour(DecisionMakerBaseBehaviour):
Expand Down Expand Up @@ -286,14 +287,19 @@ def _is_profitable(self, confidence: float, vote: int) -> bool:
bet_threshold = 0

potential_net_profit = num_shares - net_bet_amount - bet_threshold
is_profitable = potential_net_profit >= 0 and num_shares <= available_shares
shares_out = self.wei_to_native(num_shares)
available_in = self.wei_to_native(available_shares)
shares_out_of = f"{shares_out} / {available_in}"
is_profitable = potential_net_profit >= 0

if num_shares > available_shares * SLIPPAGE:
self.context.logger.warning(
"Kindly contemplate reducing your bet amount, as the pool's liquidity is low compared to your bet. "
"Consequently, this situation entails a higher level of risk as the obtained number of shares, "
"and therefore the potential net profit, will be lower than if the pool had higher liquidity!"
)

self.context.logger.info(
f"The current liquidity of the market is {bet.scaledLiquidityMeasure} xDAI. "
f"The potential net profit is {self.wei_to_native(potential_net_profit)} xDAI "
f"from buying {shares_out_of} shares for the option {bet.get_outcome(vote)}.\n"
f"from buying {self.wei_to_native(num_shares)} shares for the option {bet.get_outcome(vote)}.\n"
f"Decision for profitability of this market: {is_profitable}."
)

Expand Down
Loading

0 comments on commit 3c55841

Please sign in to comment.