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

Send/Receive functions + tests working #617

Merged
merged 6 commits into from
Dec 27, 2024
Merged
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
1,386 changes: 631 additions & 755 deletions poetry.lock

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion prediction_market_agent/agents/microchain_agent/deploy.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,9 @@ def run_general_agent(
initial_formatted_system_prompt = agent.system_prompt

iteration = 0
while self.max_iterations is None or iteration < self.max_iterations:
while not agent.do_stop and (
self.max_iterations is None or iteration < self.max_iterations
):
starting_history_length = len(agent.history)
try:
# After the first iteration, resume=True to not re-initialize the agent.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,16 @@
ReceiveMessage,
SendPaidMessageToAnotherAgent,
)
from prediction_market_agent.db.blockchain_transaction_fetcher import (
BlockchainTransactionFetcher,
)
from prediction_market_agent.db.agent_communication import fetch_unseen_transactions
from prediction_market_agent.db.long_term_memory_table_handler import (
LongTermMemories,
LongTermMemoryTableHandler,
)
from prediction_market_agent.db.prompt_table_handler import PromptTableHandler
from prediction_market_agent.tools.message_utils import compress_message
from prediction_market_agent.tools.message_utils import (
compress_message,
unzip_message_else_do_nothing,
)

st.set_page_config(
page_title="Agent's NFT-locked Treasury Game", page_icon="🎮", layout="wide"
Expand All @@ -57,11 +58,6 @@ class DummyFunctionName(str, Enum):
RESPONSE_FUNCTION_NAME = "Response"


@st.cache_resource
def blockchain_transaction_fetcher() -> BlockchainTransactionFetcher:
return BlockchainTransactionFetcher()


@st.cache_resource
def long_term_memory_table_handler(
identifier: AgentIdentifier,
Expand Down Expand Up @@ -244,19 +240,17 @@ def show_about_agent_part(nft_agent: type[DeployableAgentNFTGameAbstract]) -> No
)
st.markdown("---")
with st.popover("Show unprocessed incoming messages"):
transactions = blockchain_transaction_fetcher().fetch_unseen_transactions(
nft_agent.wallet_address
)
messages = fetch_unseen_transactions(nft_agent.wallet_address)

if not transactions:
if not messages:
st.info("No unprocessed messages")
else:
for transaction in transactions:
for message in messages:
st.markdown(
f"""
**From:** {transaction.sender_address}
**Message:** {transaction.data_field}
**Value:** {wei_to_xdai(transaction.value_wei_parsed)} xDai
**From:** {message.sender}
**Message:** {unzip_message_else_do_nothing(message.message.hex())}
**Value:** {wei_to_xdai(message.value)} xDai
"""
)
st.divider()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
from microchain import Function
from prediction_market_agent_tooling.gtypes import wei_type, xdai_type
from prediction_market_agent_tooling.config import APIKeys as APIKeys_PMAT
from prediction_market_agent_tooling.gtypes import xdai_type
from prediction_market_agent_tooling.loggers import logger
from prediction_market_agent_tooling.tools.contract import ContractOnGnosisChain
from prediction_market_agent_tooling.tools.hexbytes_custom import HexBytes
from prediction_market_agent_tooling.tools.web3_utils import send_xdai_to, xdai_to_wei
from prediction_market_agent_tooling.tools.web3_utils import xdai_to_wei
from web3 import Web3

from prediction_market_agent.agents.microchain_agent.microchain_agent_keys import (
MicrochainAgentKeys,
)
from prediction_market_agent.agents.microchain_agent.nft_treasury_game.constants_nft_treasury_game import (
TREASURY_SAFE_ADDRESS,
from prediction_market_agent.db.agent_communication import (
fetch_count_unprocessed_transactions,
pop_message,
send_message,
)
from prediction_market_agent.db.blockchain_transaction_fetcher import (
BlockchainTransactionFetcher,
from prediction_market_agent.tools.message_utils import (
compress_message,
parse_message_for_agent,
)
from prediction_market_agent.tools.message_utils import compress_message


class BroadcastPublicMessageToHumans(Function):
Expand Down Expand Up @@ -47,12 +49,12 @@ def example_args(self) -> list[str]:

def __call__(self, address: str, message: str, fee: float) -> str:
keys = MicrochainAgentKeys()
send_xdai_to(
web3=ContractOnGnosisChain.get_web3(),
from_private_key=keys.bet_from_private_key,
to_address=Web3.to_checksum_address(address),
value=xdai_to_wei(keys.cap_sending_xdai(xdai_type(fee))),
data_text=compress_message(message),
api_keys = APIKeys_PMAT(BET_FROM_PRIVATE_KEY=keys.bet_from_private_key)
send_message(
api_keys=api_keys,
recipient=Web3.to_checksum_address(address),
message=HexBytes(compress_message(message)),
amount_wei=xdai_to_wei(keys.cap_sending_xdai(xdai_type(fee))),
)
return self.OUTPUT_TEXT

Expand All @@ -63,8 +65,9 @@ class ReceiveMessage(Function):

@staticmethod
def get_count_unseen_messages() -> int:
return BlockchainTransactionFetcher().fetch_count_unprocessed_transactions(
consumer_address=MicrochainAgentKeys().bet_from_address
keys = MicrochainAgentKeys()
return fetch_count_unprocessed_transactions(
consumer_address=keys.bet_from_address
)

@property
Expand All @@ -78,30 +81,18 @@ def example_args(self) -> list[str]:

def __call__(self) -> str:
keys = MicrochainAgentKeys()
fetcher = BlockchainTransactionFetcher()
message_to_process = (
fetcher.fetch_one_unprocessed_blockchain_message_and_store_as_processed(
keys.bet_from_address
)
)

if not message_to_process:
count_unseen_messages = self.get_count_unseen_messages()

if count_unseen_messages == 0:
logger.info("No messages to process.")
else:
# Accumulate a percentage of the message value in the treasury.
tx_receipt = send_xdai_to(
web3=ContractOnGnosisChain.get_web3(),
from_private_key=keys.bet_from_private_key,
to_address=TREASURY_SAFE_ADDRESS,
value=wei_type(
self.TREASURY_ACCUMULATION_PERCENTAGE
* message_to_process.value_wei_parsed
),
)
logger.info(
f"Funded the treasury with xDai, tx_hash: {HexBytes(tx_receipt['transactionHash']).hex()}"
)
return str(message_to_process) if message_to_process else "No new messages"
return "No new messages"

popped_message = pop_message(
api_keys=APIKeys_PMAT(BET_FROM_PRIVATE_KEY=keys.bet_from_private_key),
)

return parse_message_for_agent(message=popped_message)


MESSAGES_FUNCTIONS: list[type[Function]] = [
Expand Down
59 changes: 59 additions & 0 deletions prediction_market_agent/db/agent_communication.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
from eth_typing import ChecksumAddress
from prediction_market_agent_tooling.config import APIKeys as APIKeys_PMAT
from prediction_market_agent_tooling.gtypes import HexBytes, Wei
from prediction_market_agent_tooling.tools.contract import (
AgentCommunicationContract,
ContractOnGnosisChain,
)
from prediction_market_agent_tooling.tools.data_models import MessageContainer
from prediction_market_agent_tooling.tools.parallelism import par_map
from web3.types import TxReceipt


def fetch_unseen_transactions(
consumer_address: ChecksumAddress,
) -> list[MessageContainer]:
agent_comm_contract = AgentCommunicationContract()

count_unseen_messages = fetch_count_unprocessed_transactions(consumer_address)

message_containers = par_map(
items=list(range(count_unseen_messages)),
func=lambda idx: agent_comm_contract.get_at_index(
agent_address=consumer_address, idx=idx
),
)

return message_containers


def fetch_count_unprocessed_transactions(consumer_address: ChecksumAddress) -> int:
agent_comm_contract = AgentCommunicationContract()

count_unseen_messages = agent_comm_contract.count_unseen_messages(consumer_address)
return count_unseen_messages


def pop_message(api_keys: APIKeys_PMAT) -> MessageContainer:
agent_comm_contract = AgentCommunicationContract()
popped_message = agent_comm_contract.pop_message(
api_keys=api_keys,
agent_address=api_keys.bet_from_address,
)
return popped_message


def send_message(
api_keys: APIKeys_PMAT,
recipient: ChecksumAddress,
message: HexBytes,
amount_wei: Wei,
) -> TxReceipt:
agent_comm_contract = AgentCommunicationContract()
return agent_comm_contract.send_message(
api_keys=api_keys,
agent_address=recipient,
message=message,
amount_wei=amount_wei,
web3=ContractOnGnosisChain.get_web3(),
)
54 changes: 0 additions & 54 deletions prediction_market_agent/db/blockchain_message_table_handler.py

This file was deleted.

101 changes: 0 additions & 101 deletions prediction_market_agent/db/blockchain_transaction_fetcher.py

This file was deleted.

Loading
Loading