-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathseller.py
More file actions
284 lines (250 loc) · 11 KB
/
seller.py
File metadata and controls
284 lines (250 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import threading
import logging
import hashlib
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Any
from enum import Enum
from dotenv import load_dotenv
from virtuals_acp.memo import ACPMemo, MemoType
from virtuals_acp.client import VirtualsACP
from virtuals_acp.env import EnvSettings
from virtuals_acp.job import ACPJob
from virtuals_acp.models import ACPJobPhase
from virtuals_acp.configs.configs import BASE_MAINNET_CONFIG_V2
from virtuals_acp.contract_clients.contract_client_v2 import ACPContractClientV2
from virtuals_acp.fare import FareAmount, Fare
# Logging setup
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
logger = logging.getLogger("FundsSellerAgent")
load_dotenv(override=True)
config = BASE_MAINNET_CONFIG_V2
REJECT_AND_REFUND = False # flag to trigger job.reject_payable use cases
class JobName(str, Enum):
OPEN_POSITION = "open_position"
CLOSE_POSITION = "close_position"
SWAP_TOKEN = "swap_token"
@dataclass
class Position:
symbol: str
amount: float
tp: Dict[str, float]
sl: Dict[str, float]
@dataclass
class ClientWallet:
client_address: str
positions: List[Position] = field(default_factory=list)
clients: Dict[str, ClientWallet] = {}
def _derive_wallet_address(addr: str) -> str:
h = hashlib.sha256(addr.encode()).hexdigest()
return f"0x{h}"
def get_client_wallet(address: str) -> ClientWallet:
derived = _derive_wallet_address(address)
if derived not in clients:
clients[derived] = ClientWallet(client_address=derived)
return clients[derived]
def prompt_tp_sl_action(job: ACPJob, wallet: ClientWallet):
logger.info(f"Wallet: {wallet}")
positions = [p for p in wallet.positions if p.amount > 0]
if not positions:
return
action = None
while action not in ("TP", "SL"):
logger.info("\nAvailable actions:\n1. Hit TP\n2. Hit SL")
selection = input("\nSelect an action (enter 1 or 2): ").strip()
if selection == "1":
action = "TP"
elif selection == "2":
action = "SL"
else:
logger.warning("Invalid selection. Please try again.")
position = None
while position is None:
symbol = input("Token symbol to close: ").strip()
position = next((p for p in wallet.positions if p.symbol.lower() == symbol.lower()), None)
if not position or position.amount <= 0:
logger.warning("Invalid token symbol or position amount is zero. Please try again.")
position = None
logger.info(f"{position.symbol} position hits {action}, sending remaining funds back to buyer.")
closing_amount = close_position(wallet, position.symbol)
job.create_payable_notification(
f"{position.symbol} position has hit {action}. Closed {position.symbol} position with txn hash 0x0f60a30d66f1f3d21bad63e4e53e59d94ae286104fe8ea98f28425821edbca1b",
FareAmount(
closing_amount * (
(1 + ((position.tp.get("percentage") or 0) / 100)) if action == "TP"
else (1 - ((position.sl.get("percentage") or 0) / 100))
),
config.base_fare
),
)
logger.info(f"{position.symbol} position funds sent back to buyer.")
logger.info(f"Wallet: {wallet}")
def on_new_task(job: ACPJob, memo_to_sign: Optional[ACPMemo] = None) -> None:
job_id, job_phase, job_name = job.id, job.phase, job.name
if memo_to_sign is None:
logger.warning(f"[on_new_task] No memo to sign | job_id={job_id}")
return
memo_id = memo_to_sign.id
logger.info(
f"[on_new_task] Received job | job_id={job_id}, job_phase={job_phase}, job_name={job_name}, memo_id={memo_id}"
)
if job_phase == ACPJobPhase.REQUEST:
handle_task_request(job, memo_to_sign)
elif job_phase == ACPJobPhase.TRANSACTION:
handle_task_transaction(job)
def handle_task_request(job: ACPJob, memo_to_sign: ACPMemo):
job_name, job_id = job.name, job.id
memo_id = memo_to_sign.id if memo_to_sign else None
if not job_name or memo_to_sign is None:
logger.error(f"[handle_task_request] Missing data | job_id={job_id}, memo_id={memo_id}, job_name={job_name}")
return
if job_name == JobName.OPEN_POSITION:
logger.info(f"Accepts position opening request | requirement={job.requirement}")
job.accept("Accepts position opening")
amount = float(job.requirement.get("amount", 0))
return job.create_payable_requirement(
"Send me USDC to open position",
MemoType.PAYABLE_REQUEST,
FareAmount(
amount,
config.base_fare # Open position against ACP Base Currency: USDC
),
job.provider_address, # funds receiving address, can be any address on Base
)
if job_name == JobName.CLOSE_POSITION:
wallet = get_client_wallet(job.client_address)
symbol = job.requirement.get("symbol")
position = next((p for p in wallet.positions if p.symbol == symbol), None)
position_is_valid = position is not None and position.amount > 0
logger.info(f'{"Accepts" if position_is_valid else "Rejects"} position closing request | requirement={job.requirement}')
if position_is_valid:
response = f"Accepts position closing. Please make payment to close {symbol} position."
job.accept(response)
return job.create_requirement(response)
else:
response = "Rejects position closing. Position is invalid."
return job.reject(response)
if job_name == JobName.SWAP_TOKEN:
logger.info(f"Accepts token swapping request | requirement={job.requirement}")
job.accept("Accepts token swapping request")
amount = float(job.requirement.get("amount", 0))
from_contract = job.requirement.get("fromContractAddress")
return job.create_payable_requirement(
f"Send me {job.requirement.get('fromSymbol', 'USDC')} to swap to {job.requirement.get('toSymbol', 'VIRTUAL')}",
MemoType.PAYABLE_REQUEST,
FareAmount( # Constructing Fare for the token to swap from
amount,
Fare.from_contract_address(
from_contract,
config
)
),
job.provider_address, # funds receiving address, can be any address on Base
)
logger.warning(f"[handle_task_request] Unsupported job name | job_id={job_id}, job_name={job_name}")
def handle_task_transaction(job: ACPJob):
job_name, job_id = job.name, job.id
wallet = get_client_wallet(job.client_address)
if not job_name:
logger.error(f"[handle_task_transaction] Missing job name | job_id={job_id}")
return
if job_name == JobName.OPEN_POSITION:
if REJECT_AND_REFUND: # to cater cases where a reject and refund is needed (ie: internal server error)
reason = f"Internal server error handling {job.requirement.get('symbol')} trades"
logger.info(f"Rejecting and refunding job {job.id} with reason: {reason}")
job.reject_payable(
reason,
FareAmount(
job.net_payable_amount, # return the net payable amount from seller wallet
config.base_fare
)
)
logger.info(f"Job {job.id} rejected job and refunded.")
return
open_position(wallet, job)
logger.info(f"Opening position: {job.requirement}")
job.deliver("Opened position with txn 0x71c038a47fd90069f133e991c4f19093e37bef26ca5c78398b9c99687395a97a")
logger.info("Position opened")
return prompt_tp_sl_action(job, wallet)
if job_name == JobName.CLOSE_POSITION:
symbol = job.requirement.get("symbol")
closing_amount = close_position(wallet, symbol)
logger.info(f"Returning closing amount: {closing_amount} USDC")
job.deliver_payable(
f"Closed {symbol} position with txn hash 0x0f60a30d66f1f3d21bad63e4e53e59d94ae286104fe8ea98f28425821edbca1b",
FareAmount(closing_amount, config.base_fare),
)
logger.info("Closing amount returned")
logger.info(f"Wallet: {wallet}")
if job_name == JobName.SWAP_TOKEN:
if REJECT_AND_REFUND: # to cater cases where a reject and refund is needed (ie: internal server error)
reason = f"Internal server error handling ${job.requirement.get('fromSymbol')} swaps"
logger.info(f"Rejecting and refunding job {job.id} with reason: {reason}")
from_amount = FareAmount(
job.net_payable_amount, # return the net payable amount from seller wallet
Fare.from_contract_address(job.requirement.get("fromContractAddress"), config)
)
job.reject_payable(
reason,
from_amount
)
logger.info(f"Job {job.id} rejected job and refunded.")
return
to_contract = job.requirement.get("toContractAddress")
token_swapping_ratio = 1 / 2 # 2 token from : 1 token to
swapped_amount = FareAmount(
(
job.net_payable_amount # swapping principal after ACP fee deduction
*
token_swapping_ratio
),
Fare.from_contract_address(
to_contract,
config,
config.chain_id
)
)
logger.info(f"Returning swapped token: {swapped_amount}")
job.deliver_payable(
f"Return swapped token {job.requirement.get('toSymbol', 'VIRTUAL')}",
swapped_amount,
True # skip fee to return swapped tokens
)
logger.info("Swapped token returned")
else:
logger.warning(f"[handle_task_transaction] Unsupported job name | job_id={job_id}, job_name={job_name}")
def open_position(wallet: ClientWallet, job: ACPJob) -> None:
payload = job.requirement
amount = job.net_payable_amount # trading principal after ACP fee deduction
pos = next((p for p in wallet.positions if p.symbol == payload.get("symbol")), None)
if pos:
pos.amount += amount
else:
wallet.positions.append(
Position(
symbol=payload.get("symbol"),
amount=amount,
tp=payload.get("tp"),
sl=payload.get("sl")
)
)
def close_position(wallet: ClientWallet, symbol: str) -> Optional[float]:
pos = next((p for p in wallet.positions if p.symbol == symbol), None)
wallet.positions = [p for p in wallet.positions if p.symbol != symbol]
return pos.amount if pos else 0
def seller():
env = EnvSettings()
VirtualsACP(
acp_contract_clients=ACPContractClientV2(
wallet_private_key=env.WHITELISTED_WALLET_PRIVATE_KEY,
agent_wallet_address=env.SELLER_AGENT_WALLET_ADDRESS,
entity_id=env.SELLER_ENTITY_ID,
config=config,
),
on_new_task=on_new_task
)
threading.Event().wait()
if __name__ == "__main__":
seller()