|
2 | 2 | import logging |
3 | 3 | import os.path |
4 | 4 | import ssl |
| 5 | +import time |
5 | 6 | from io import BytesIO |
6 | 7 | from pathlib import Path |
7 | 8 | from typing import ( |
|
20 | 21 | import aiohttp |
21 | 22 | from aiohttp.web import HTTPNotFound |
22 | 23 | from aleph_message import parse_message |
23 | | -from aleph_message.models import AlephMessage, ItemHash, ItemType, MessageType |
| 24 | +from aleph_message.models import ( |
| 25 | + AlephMessage, |
| 26 | + Chain, |
| 27 | + InstanceContent, |
| 28 | + ItemHash, |
| 29 | + ItemType, |
| 30 | + MessageType, |
| 31 | + ProgramContent, |
| 32 | +) |
24 | 33 | from aleph_message.status import MessageStatus |
25 | 34 | from pydantic import ValidationError |
26 | 35 |
|
|
37 | 46 | from ..utils import ( |
38 | 47 | Writable, |
39 | 48 | check_unix_socket_valid, |
| 49 | + compute_sha256, |
40 | 50 | copy_async_readable_to_buffer, |
41 | 51 | extended_json_encoder, |
42 | 52 | get_message_type_value, |
@@ -448,6 +458,44 @@ async def watch_messages( |
448 | 458 | elif msg.type == aiohttp.WSMsgType.ERROR: |
449 | 459 | break |
450 | 460 |
|
| 461 | + async def get_estimated_price( |
| 462 | + self, |
| 463 | + content: ProgramContent | InstanceContent, |
| 464 | + ) -> PriceResponse: |
| 465 | + item_content: str = json.dumps( |
| 466 | + content, separators=(",", ":"), default=extended_json_encoder |
| 467 | + ) |
| 468 | + message = parse_message( |
| 469 | + dict( |
| 470 | + sender=content.address, |
| 471 | + chain=Chain.ETH, |
| 472 | + type=( |
| 473 | + MessageType.program |
| 474 | + if isinstance(content, ProgramContent) |
| 475 | + else MessageType.instance |
| 476 | + ), |
| 477 | + content=content.dict(exclude_none=True), |
| 478 | + item_content=item_content, |
| 479 | + time=time.time(), |
| 480 | + channel=settings.DEFAULT_CHANNEL, |
| 481 | + item_type=ItemType.inline, |
| 482 | + item_hash=compute_sha256(item_content), |
| 483 | + ) |
| 484 | + ) |
| 485 | + |
| 486 | + async with self.http_session.post( |
| 487 | + "/api/v0/price/estimate", json=dict(message=message) |
| 488 | + ) as resp: |
| 489 | + try: |
| 490 | + resp.raise_for_status() |
| 491 | + response_json = await resp.json() |
| 492 | + return PriceResponse( |
| 493 | + required_tokens=response_json["required_tokens"], |
| 494 | + payment_type=response_json["payment_type"], |
| 495 | + ) |
| 496 | + except aiohttp.ClientResponseError as e: |
| 497 | + raise e |
| 498 | + |
451 | 499 | async def get_program_price(self, item_hash: str) -> PriceResponse: |
452 | 500 | async with self.http_session.get(f"/api/v0/price/{item_hash}") as resp: |
453 | 501 | try: |
|
0 commit comments