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

[WIP]: Polymarket support #195

Draft
wants to merge 21 commits into
base: main
Choose a base branch
from
Draft
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
3 changes: 3 additions & 0 deletions .gitleaksignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,6 @@ b520b0c67a9ae55ba501e1e9a99abfc0738e8d49:packages/valory/skills/staking_abci/ski
4063acab1bf2654eeaa6fca86bfbc3f6ab57e399:packages/valory/services/trader/service.yaml:generic-api-key:9
392a14119facddbad6edd8f1d7553db08cdbf20c:packages/valory/skills/market_manager_abci/skill.yaml:generic-api-key:17
cfbec155d82abe64814af23610a4c69017d69096:packages/valory/skills/market_manager_abci/skill.yaml:generic-api-key:17
ed30ffbaaf3c10476dc642d388985c250afaeb8d:packages/valory/skills/market_manager_abci/graph_tooling/requests.py:generic-api-key:221
ed30ffbaaf3c10476dc642d388985c250afaeb8d:packages/valory/skills/market_manager_abci/graph_tooling/requests.py:generic-api-key:222
d004f2345bf31b27c343eb52c1bc5a2698e838d6:packages/valory/skills/market_manager_abci/graph_tooling/requests.py:generic-api-key:221
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": "bafybeifdf6uoscrgvlgqceqcph2pgoygobznw6hbodpav7lubbqsyh4kby",
"skill/valory/decision_maker_abci/0.1.0": "bafybeigv6vymf2jisrrwnvobyzmtpa6566ldaq2u7r2vdslrv7h6fhvprq",
"skill/valory/trader_abci/0.1.0": "bafybeifd7s5nnyqow7pmylpdxlydezj2bipktscx2tdze6o7n3kstwbami",
"skill/valory/market_manager_abci/0.1.0": "bafybeia7vrpts3jeldxr4osltz5ekw7p3h2ib5ossutpviplkzqvfwhjua",
"skill/valory/decision_maker_abci/0.1.0": "bafybeihxo35ycripnuwcltfy64lxhaox43av7lbcozdgw2w3wupzzpdnn4",
"skill/valory/trader_abci/0.1.0": "bafybeid6md2wq6m4nwahdvv4kfbhvl67rvpn4tokgtbjvjb4qkmzhqxgui",
"contract/valory/market_maker/0.1.0": "bafybeiain372i5t6eteem36vzhwh6ppka6hc4oyrxjtyzuar6rd6bjocem",
"agent/valory/trader/0.1.0": "bafybeidb4omu5cwpedqrlyjeqnkafpgje6xkt3i6ky6igoynue7ojpcegm",
"service/valory/trader/0.1.0": "bafybeibzdyrxu4scbuc6n67kggq4zxl4kaqnv7rn5yyy4zjmsynpu777p4",
"agent/valory/trader/0.1.0": "bafybeidjs3la6qd655ajn2u4lbchdi7suy5gne5rvzwgiscqrcvghz4oqy",
"service/valory/trader/0.1.0": "bafybeidkc4ww2dgcdpkoy5umbqudlz5ljufjuvhruvhil73xg3dkbj5qbq",
"contract/valory/erc20/0.1.0": "bafybeiad6qbyhr3sgvclqne7tvyvqt32pcj5aq47hhkd2vmawaflhy5vna",
"skill/valory/tx_settlement_multiplexer_abci/0.1.0": "bafybeicrvyshqokgxd7azjy6g3yzhk44lscerwnkci33eisam2foetjv4m",
"skill/valory/tx_settlement_multiplexer_abci/0.1.0": "bafybeibal5o2ji3rxjf5plwsexpiafv6ufnntre2pikfd5qrykff3icaoi",
"contract/valory/mech/0.1.0": "bafybeiauxqogu726oeethvzux6r77zgn7sw5j2l4uigqb47zlqawblkv6e",
"contract/valory/realitio/0.1.0": "bafybeic5ie4oodetj4krdogydvbfxg4qggc3matpiflocah626tpevpreq",
"contract/valory/realitio_proxy/0.1.0": "bafybeidx37xzjjmapwacedgzhum6grfzhp5vhouz4zu3pvpgdy5pgb2fr4",
Expand Down
11 changes: 6 additions & 5 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:bafybeibnwjcjx4lluf4cwb6es5peelu3gm7vrzlieygrzpbjlubxpvbvzy
- valory/termination_abci:0.1.0:bafybeifdtxgldw33kwvsavcituzewwbr6iqfcsgk5qouqfhpwdrivyyyom
- valory/transaction_settlement_abci:0.1.0:bafybeifpnkwgwpzz6uwrvfgurm26allr6shjfbp7bfbrxwy64sw3nf3fsa
- valory/tx_settlement_multiplexer_abci:0.1.0:bafybeicrvyshqokgxd7azjy6g3yzhk44lscerwnkci33eisam2foetjv4m
- valory/market_manager_abci:0.1.0:bafybeifdf6uoscrgvlgqceqcph2pgoygobznw6hbodpav7lubbqsyh4kby
- valory/decision_maker_abci:0.1.0:bafybeigv6vymf2jisrrwnvobyzmtpa6566ldaq2u7r2vdslrv7h6fhvprq
- valory/trader_abci:0.1.0:bafybeifd7s5nnyqow7pmylpdxlydezj2bipktscx2tdze6o7n3kstwbami
- valory/tx_settlement_multiplexer_abci:0.1.0:bafybeibal5o2ji3rxjf5plwsexpiafv6ufnntre2pikfd5qrykff3icaoi
- valory/market_manager_abci:0.1.0:bafybeia7vrpts3jeldxr4osltz5ekw7p3h2ib5ossutpviplkzqvfwhjua
- valory/decision_maker_abci:0.1.0:bafybeihxo35ycripnuwcltfy64lxhaox43av7lbcozdgw2w3wupzzpdnn4
- valory/trader_abci:0.1.0:bafybeid6md2wq6m4nwahdvv4kfbhvl67rvpn4tokgtbjvjb4qkmzhqxgui
- valory/staking_abci:0.1.0:bafybeiccopehegiiwxzghrttdhuxtnjp7zvuiclx5zchbtvqpy45rrvdxy
default_ledger: ethereum
required_ledgers:
Expand Down Expand Up @@ -158,7 +158,8 @@ models:
use_termination: ${bool:false}
on_chain_service_id: ${int:null}
creator_per_subgraph:
omen_subgraph: ${list:["0x89c5cc945dd550BcFfb72Fe42BfF002429F46Fec"]}
omen_subgraph: ${list:[]}
polymarket_gamma_subgraph: ${list:["0x91430cad2d3975766499717fa0d66a78d814e5c5"]}
slot_count: ${int:2}
opening_margin: ${int:300}
languages: ${list:["en_US"]}
Expand Down
5 changes: 3 additions & 2 deletions 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:bafybeidb4omu5cwpedqrlyjeqnkafpgje6xkt3i6ky6igoynue7ojpcegm
agent: valory/trader:0.1.0:bafybeidjs3la6qd655ajn2u4lbchdi7suy5gne5rvzwgiscqrcvghz4oqy
number_of_agents: 4
deployment: {}
---
Expand Down Expand Up @@ -71,7 +71,8 @@ type: skill
validate_timeout: ${VALIDATE_TIMEOUT:int:1205}
history_check_timeout: ${HISTORY_CHECK_TIMEOUT:int:1205}
creator_per_subgraph: &id003
omen_subgraph: ${OMEN_CREATORS:list:["0x89c5cc945dd550BcFfb72Fe42BfF002429F46Fec"]}
omen_subgraph: ${OMEN_CREATORS:list:[]}
polymarket_gamma_subgraph: ${POLYMARKET_CREATORS:list:["0x91430cad2d3975766499717fa0d66a78d814e5c5"]}
slot_count: ${SLOT_COUNT:int:2}
opening_margin: ${OPENING_MARGIN:int:300}
languages: ${LANGUAGES:list:["en_US"]}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def available_bets(self) -> Iterator[Bet]:

# Note: the openingTimestamp is misleading as it is the closing timestamp of the bet
if self.params.using_kelly:
# get only bets that close in the next 48 hours
# get only bets that close in the next `sample_bets_closing_days`
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The sample_bets_closing_days override can be set to a large value to test kelly for Polymarket.

self.bets = [
bet
for bet in self.bets
Expand Down
4 changes: 2 additions & 2 deletions packages/valory/skills/decision_maker_abci/models.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2023 Valory AG
# Copyright 2023-2024 Valory AG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -69,7 +69,7 @@
DEFAULT_FROM_BLOCK = "earliest"
ZERO_HEX = HASH_ZERO[2:]
ZERO_BYTES = bytes.fromhex(ZERO_HEX)
STRATEGY_BET_AMOUNT_PER_CONF_THRESHOLD = "bet_amount_per_conf_threshold"
STRATEGY_BET_AMOUNT_PER_CONF_THRESHOLD = "bet_amount_per_threshold"
STRATEGY_KELLY_CRITERION = "kelly_criterion"


Expand Down
8 changes: 4 additions & 4 deletions packages/valory/skills/decision_maker_abci/skill.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@ fingerprint:
behaviours/randomness.py: bafybeidmr33teizrs4uxlo5tdz766ds6os4pe5lttstm7jpmhgmjz5ti3q
behaviours/reedem.py: bafybeibenzbek5qdtk3gobjxfmsm6tg6i3d4yltozymy23izpgbcpal5ye
behaviours/round_behaviour.py: bafybeibymtirxbazjalmvfstnohaeqhmk4tggwwqhu62gm7mxdv6eabe3y
behaviours/sampling.py: bafybeibxcth4gsn7ov5liz5ma5tcflt7nvi64ku4gxlngno5vn3qr7km4u
behaviours/sampling.py: bafybeihtcqi3fpeygsp7hbwhr22vyliem4ewly6z27t7zo3e73ob3stw5a
behaviours/tool_selection.py: bafybeicxw4je76uc7znx4u2hq2b2aaxcf7blwfla7lhdhkqnf3kkupsczq
dialogues.py: bafybeigpwuzku3we7axmxeamg7vn656maww6emuztau5pg3ebsoquyfdqm
fsm_specification.yaml: bafybeigub5ekfxfj4xaitern7lbjtlpdgjqzgwmuijrea5b6dpu2npau7m
handlers.py: bafybeiggoetspwcvdojmbjdd67tmkoeedikmt6vsbcium3zjaljb6jzqu4
io_/__init__.py: bafybeifxgmmwjqzezzn3e6keh2bfo4cyo7y5dq2ept3stfmgglbrzfl5rq
io_/loader.py: bafybeih3sdsx5dhe4kzhtoafexjgkutsujwqy3zcdrlrkhtdks45bc7exa
models.py: bafybeif63pruksc6fpvmg77jmsrphc36uiawypzzcrk6nbpzoglbpxnlfy
models.py: bafybeigw3tbiojunr5iwuqgr6vdx6s355htlrbugiz2tgokxupauhx52iy
payloads.py: bafybeigcic4vewdglakzpyqevhfwsolh4ywnbvxo5bgned7gl5uo3jif7m
policy.py: bafybeihca4gc5gdj3wmvtzulqq3cr4zm6ouyt7aoscfedutzr4so4bksna
redeem_info.py: bafybeifiiix4gihfo4avraxt34sfw35v6dqq45do2drrssei2shbps63mm
Expand All @@ -37,7 +37,7 @@ fingerprint:
states/base.py: bafybeiag6q3nlndsu4nt66rxrgogueh364v3lekqo4c5ynuuo4hql2bxum
states/bet_placement.py: bafybeibalhxhp2c4oljmiwqi6ds3g36fgtabmf42mb5sgq6z22znrcbhda
states/blacklisting.py: bafybeifruvxwwltndwazkzzbpc5nnnad3z5t5ofy6d3i7nssljbxl6gvxu
states/decision_receive.py: bafybeib3roo27nccj4eylaqwwzztzzzwsi6px5atjrch5wbqmpln2kyy6y
states/decision_receive.py: bafybeiclng2o5skqc7jwuqggpk6guexaot6e2clgfbhejwe4zlkgayeshq
states/decision_request.py: bafybeic7otc3hjb753svbmur3yyk6szahc25yii3x4w4vcnpfz6jwvacuu
states/final_states.py: bafybeidiwhuyd5zm2cq7vhv2owcrxdpm7fnvn3db6p6tql4jz5hgpalflu
states/handle_failed_tx.py: bafybeihewm2vernvhktuorljdupjqcg2p5vs6wvsira2d62wkoyo5xlzjm
Expand Down Expand Up @@ -67,7 +67,7 @@ protocols:
- valory/ipfs:0.1.0:bafybeiedxeismnx3k5ty4mvvhlqideixlhqmi5mtcki4lxqfa7uqh7p33u
skills:
- valory/abstract_round_abci:0.1.0:bafybeicrzndcdbue34yxwwb4hmmdhgzw4owcdcdag3ifj6thpx5wie3dp4
- valory/market_manager_abci:0.1.0:bafybeifdf6uoscrgvlgqceqcph2pgoygobznw6hbodpav7lubbqsyh4kby
- valory/market_manager_abci:0.1.0:bafybeia7vrpts3jeldxr4osltz5ekw7p3h2ib5ossutpviplkzqvfwhjua
- valory/transaction_settlement_abci:0.1.0:bafybeifpnkwgwpzz6uwrvfgurm26allr6shjfbp7bfbrxwy64sw3nf3fsa
behaviours:
main:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2023 Valory AG
# Copyright 2023-2024 Valory AG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
Expand Down
4 changes: 2 additions & 2 deletions packages/valory/skills/market_manager_abci/behaviours.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,10 +150,10 @@ def _update_bets(
if not can_proceed:
break

bets_market_chunk = yield from self._fetch_bets()
bets_market_chunk, deserializer = yield from self._fetch_bets()
if bets_market_chunk is not None:
bets_updates = (
Bet(**bet, market=self._current_market)
deserializer(**bet, market=self._current_market)
for bet in bets_market_chunk
if bet.get("id", "") not in existing_ids
)
Expand Down
38 changes: 37 additions & 1 deletion packages/valory/skills/market_manager_abci/bets.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2023 Valory AG
# Copyright 2023-2024 Valory AG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
Expand All @@ -24,11 +24,21 @@
import dataclasses
import json
import sys
from datetime import datetime, timezone
from enum import Enum, auto
from typing import Any, Dict, List, Optional, Union


BINARY_N_SLOTS = 2
USDC = "0x2791bca1f2de4661ed88a30c99a7a9449aa84174"
NULL_ADDRESS = "0x" + "0" * 40
OMEN_TO_POLYWRAP = dict(
id="marketMakerAddress",
market="market",
title="question",
fee="fee",
scaledLiquidityMeasure="liquidity",
)


class BetStatus(Enum):
Expand Down Expand Up @@ -58,6 +68,32 @@ class Bet:
status: BetStatus = BetStatus.UNPROCESSED
blacklist_expiration: float = -1

@classmethod
def from_gamma_subgraph(cls, **kwargs: Any) -> "Bet":
"""Initialize a bet's instance from gamma subgraph's attributes."""
Adamantios marked this conversation as resolved.
Show resolved Hide resolved
outcomes = eval(kwargs["outcomes"]) # nosec
outcome_token_amounts = [0] * len(outcomes)
Adamantios marked this conversation as resolved.
Show resolved Hide resolved
end_date = datetime.strptime(kwargs["endDate"], "%Y-%m-%dT%H:%M:%S.%fZ")
opening_timestamp = int(end_date.replace(tzinfo=timezone.utc).timestamp())
submitted_by = kwargs["submitted_by"] or NULL_ADDRESS
outcome_prices = eval(kwargs["outcomePrices"]) # nosec

omen_to_polywrap_mapping = {
omen_key: kwargs[polywrap_key]
for omen_key, polywrap_key in OMEN_TO_POLYWRAP.items()
}

return cls(
collateralToken=USDC,
Copy link
Collaborator

@Adamantios Adamantios Jan 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO: make sure collateralToken is not used when making a request to the mech, but xdai or wxdai is used.

Note: we need to interact with both gnosis and polygon chains for Polymarket.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do you need to interact with both chains?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To interact with the mech on Gnosis. Is the mech deployed on Polygon?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We will deploy it on Polygon eventually. For testing use it on Gnosis

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this is only for testing then it would be faster to test this by mocking the mech request-response part locally and keep the code unchanged for when the mech is deployed on Polygon.

creator=submitted_by,
openingTimestamp=opening_timestamp,
outcomeSlotCount=len(outcomes),
outcomeTokenAmounts=outcome_token_amounts,
outcomeTokenMarginalPrices=outcome_prices,
outcomes=outcomes,
**omen_to_polywrap_mapping,
)

def __post_init__(self) -> None:
"""Post initialization to adjust the values."""
self._validate()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2023-2024 Valory AG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ------------------------------------------------------------------------------

"""Polymarket queries."""

from string import Template


questions_polymarket_gamma = Template(
"""
{
markets(
where: "active=true AND closed=false AND outcomes='[\\\"Yes\\\", \\\"No\\\"]' AND NOT market_maker_address=''"
order: "start_date DESC"
limit: 100
) {
marketMakerAddress
question
denominationToken
submitted_by
fee
endDate
outcomes
outcomePrices
liquidity
}
}
"""
)


questions_polymarket = Template(
"""
{
fixedProductMarketMakers(
where: {
outcomeSlotCount: ${slot_count},
},
orderBy: creationTimestamp
orderDirection: desc
first: 1000
){
id
collateralToken {
id
name
symbol
}
creator
fee
outcomeSlotCount
outcomeTokenAmounts
outcomeTokenPrices
scaledLiquidityParameter
conditions {
id
questionId
}
}
}
"""
)

# Missing fields:
# language_in: ${languages},
# openingTimestamp
# outcomes


# Different fields:
# outcomeTokenMarginalPrices == outcomeTokenPrices ?
# scaledLiquidityParameter == scaledLiquidityMeasure ?


trades = Template(
"""
{
fpmmTrades (
where: {
type: Buy,
creator: "${creator}",
fpmm_: {
creationTimestamp_gt: "${creationTimestamp_gt}",
answerFinalizedTimestamp_not: null,
isPendingArbitration: false
}
}
orderBy: fpmm__creationTimestamp
orderDirection: asc
first: ${first}
){
fpmm {
answerFinalizedTimestamp
collateralToken
condition {
id
outcomeSlotCount
}
creator
creationTimestamp
currentAnswer
question {
id
data
}
templateId
}
outcomeIndex
outcomeTokenMarginalPrice
outcomeTokensTraded
transactionHash
}
}
"""
)
Loading